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
fix: 隔离不兼容资料并保住可恢复案例
wchao68919566570dea19
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b421151..2f47fca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## 1.19.3++- ZIP 分享包、完整资料夹备份与手动跨设备同步共用同一套媒体格式、案例身份、项目关系和清理规则,覆盖音频、动图、现代图片、字幕、视频与文档等可携带资源。+- 单个缺失、损坏、类型错误或结构不兼容的资源只隔离自身,其他健康案例继续导入、恢复或同步;预检会列出被跳过的案例和文件,提交后的资料库不保留悬空媒体、损坏 AI 标签或待修复占位。+- 已标记完成的备份若后来发生局部资源损坏,会明确降级为救援恢复并禁止精确替换;未知解析错误、未来数据版本和无法证明逐项损失的异常仍会停止,避免静默吞掉资料。+- 完整导入采用预检后单次事务提交,支持安全合并、精确替换、自动恢复点与失败回滚;同步在业务提交后才清理旧媒体,存储读取失败时不会写入半成品。+- 保留既有用户数据的正式迁移、语义去重和多项目归属,继续用 1.19.2 正式版本夹具验证升级与完整资料往返。+## 1.19.2- 历史分享包统一经过 v1–v5 迁移后再导入,兼容 `jpeg/jpg` 等同族格式;无效 AI 标签会被丢弃并记录,不再阻断仍可恢复的案例。diff --git a/README.md b/README.mdindex 7b66402..fc415a8 100644--- a/README.md+++ b/README.md@@ -14,7 +14,8 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把- 把案例提炼成可复用的创作 Skill,在创作台组合案例、Skill 和临时附件;- 生成可编辑的图片或视频提示词,也可以连接自己的服务直接生成媒体;- 使用可选的文字分析或画面分析,让资料更容易检索;-- 创建可换电脑恢复的完整资料夹备份(包含回收站,并在备份时复制可读取的本机链接原件),或通过加密同步文件夹在自己的设备间恢复资料。+- 为选定案例生成分享 ZIP;导入时逐项隔离坏文件,单个不兼容媒体不会阻断其他健康案例;+- 创建可换电脑恢复的完整资料夹备份(包含回收站,并在备份时复制可读取的本机链接原件),可选择安全合并或带回退点的精确恢复,也可通过加密同步文件夹在自己的设备间恢复资料。## 隐私与数据diff --git a/asset-formats.js b/asset-formats.jsindex 4dc8e44..d75abfb 100644--- a/asset-formats.js+++ b/asset-formats.js@@ -78,6 +78,14 @@ const DEFINITIONS = [export const ASSET_FORMAT_REGISTRY = Object.freeze(DEFINITIONS);export const SUPPORTED_ASSET_KINDS = Object.freeze(["image", "video", "audio", "document", "attachment"]);+const PORTABLE_ASSET_DIRECTORIES = Object.freeze({+ image: "images",+ video: "videos",+ audio: "audio",+ document: "documents",+ attachment: "attachments"+});+const BY_EXTENSION = new Map();const BY_MIME_TYPE = new Map();for (const definition of ASSET_FORMAT_REGISTRY) {@@ -137,6 +145,54 @@ export function extensionsForAssetKind(kind) {.flatMap((definition) => definition.extensions));}+export function portableAssetDirectory(kindValue) {+ const kind = String(kindValue ?? "").trim();+ const directory = PORTABLE_ASSET_DIRECTORIES[kind];+ if (!directory) throw new Error(`不支持的媒体类型:${kind || "未知"}`);+ return directory;+}++export function resolvePortableAssetFormat(asset = {}, file = {}) {+ const kind = String(asset.kind ?? "").trim();+ const directory = portableAssetDirectory(kind);++ const fileMimeType = normalizeMimeType(file?.type);+ const assetMimeType = normalizeMimeType(asset?.mimeType);+ const reportedMimeType = fileMimeType && !GENERIC_MIME_TYPES.has(fileMimeType)+ ? fileMimeType+ : assetMimeType;+ const candidates = [+ normalizeExtension(asset?.sourceFormat),+ fileExtension(asset?.sourceTitle),+ ...assetFormatsForMimeType(fileMimeType).filter((item) => item.kind === kind).flatMap((item) => item.extensions),+ ...assetFormatsForMimeType(assetMimeType).filter((item) => item.kind === kind).flatMap((item) => item.extensions)+ ].filter(Boolean);++ for (const extension of [...new Set(candidates)]) {+ const definition = assetFormatForExtension(extension);+ if (definition?.kind === kind && isReportedMimeCompatible(definition, reportedMimeType)) {+ return Object.freeze({+ directory,+ extension,+ mimeType: canonicalMimeType(definition, reportedMimeType),+ formatCategory: definition.category,+ playbackCapability: ["image", "video", "audio"].includes(kind) ? "native" : "unknown"+ });+ }+ if (!definition && kind === "attachment" && /^[a-z0-9]+$/u.test(extension)) {+ return Object.freeze({+ directory,+ extension,+ mimeType: reportedMimeType || "application/octet-stream",+ formatCategory: "other-source",+ playbackCapability: "unknown"+ });+ }+ }++ throw new Error(`“${asset?.sourceTitle || asset?.id || "未命名媒体"}”缺少可安全识别的文件扩展名`);+}+export function fileExtension(value) {return String(value ?? "").trim().toLocaleLowerCase("en-US").match(/\.([a-z0-9]+)$/u)?.[1] ?? "";}diff --git a/background.js b/background.jsindex 2f5753e..0c0bf0e 100644--- a/background.js+++ b/background.js@@ -192,16 +192,25 @@ import {} from "./image-transaction.js";import { createEntrySaveUndo, normalizeLastSaveUndo, restoreScreenshotSaveEntry } from "./save-history.js";import {- mergeLibraryPackage,selectLibraryPackage,selectProjectPackage} from "./library-package.js";+import {+ LIBRARY_TRANSFER_MODES,+ LIBRARY_TRANSFER_SOURCES,+ planLibraryTransfer+} from "./library-transfer.js";import {claimLibraryImportTransaction,- createLibraryImportPlanToken,failLibraryImportTransaction,succeedLibraryImportTransaction} from "./library-import-transaction.js";+import {+ createLibraryReplacementRecoveryPoint,+ normalizeLibraryReplacementRecoveryPoint,+ obsoleteRecoveryAssetIds,+ swapLibraryReplacementRecoveryPoint+} from "./library-recovery-point.js";import { mergeCuratedLibraryPackage } from "./curated-import.js";import { prepareCuratedSubmissionState } from "./curated-submission.js";import {@@ -396,6 +405,7 @@ const STORAGE_KEYS = Object.freeze({batchJob: "batchJob",analysisTasks: "analysisTasks",libraryImportTransactions: "libraryImportTransactions",+ libraryReplacementRecoveryPoint: "libraryReplacementRecoveryPoint",libraryMaintenanceJob: "libraryMaintenanceJob",legacyAnalysisBatchJob: "analysisBatchJob",analysisBatchUndo: "analysisBatchUndo",@@ -598,6 +608,8 @@ async function handleMessage(message, interaction = {}) {return enqueueCapture(async () => captureWorkspace());case "GET_DATA_SAFETY_STATUS":return enqueue(async () => dataSafetyStatus(await readState()));+ case "RESTORE_LIBRARY_REPLACEMENT_POINT":+ return enqueue(async () => restoreLibraryReplacementPoint(await readState()));case "GET_SYNC_RUN_STATUS":return Promise.resolve({ ok: true, syncStatus: manualSyncController.status() });case "CANCEL_SYNC": {@@ -737,7 +749,12 @@ async function handleMessage(message, interaction = {}) {return enqueue(async () => applyCreativeExperimentImport(await readState(), message));case "PREVIEW_LIBRARY_IMPORT":return enqueue(async () => previewLibraryImport(await readState(), message.library, {- preserveLibraryConfiguration: message.preserveLibraryConfiguration === true+ preserveLibraryConfiguration: message.preserveLibraryConfiguration === true,+ sourceType: message.sourceType,+ mode: message.mode,+ conflictResolutions: message.conflictResolutions,+ importReport: message.importReport,+ resourceIndex: message.resourceIndex}));case "APPLY_LIBRARY_IMPORT":return enqueue(async () => applyLibraryImport(await readState(), message));@@ -2956,6 +2973,9 @@ async function readState() {importStaging,creativeSkills,activeCreativeResult,+ libraryReplacementRecoveryPoint: normalizeLibraryReplacementRecoveryPoint(+ stored[STORAGE_KEYS.libraryReplacementRecoveryPoint]+ ),syncSettings,syncStatus: await publicSyncStatus(syncSettings),visionUndoEntryIds: Object.keys(stored[STORAGE_KEYS.visionAnalysisUndo] ?? {}),@@ -7043,10 +7063,19 @@ async function applyCreativeExperimentImport(state, message) {}function previewLibraryImport(state, library, options = {}) {- const result = mergeLibraryPackage(state, library, options);+ const result = planLibraryTransfer({+ currentState: state,+ inspection: transferInspectionMessage(library, options),+ options+ });return {ok: true,- planToken: createLibraryImportPlanToken(state, library),+ planToken: result.planToken,+ plan: result.context,+ mode: result.context.mode,+ conflicts: result.conflicts,+ rollback: result.rollback,+ resourceWrites: result.resourceWrites,entryIdMap: result.entryIdMap,compoundIdMap: result.compoundIdMap,visualIdMap: result.visualIdMap,@@ -7074,7 +7103,8 @@ async function applyLibraryImport(state, message) {operationId: message.operationId,planToken: message.planToken,stateValue: state,- sourceValue: message.library+ sourceValue: message.library,+ planValue: message.plan});if (claim.replayed) return claim.result;if (!claim.acquired) {@@ -7089,30 +7119,57 @@ async function applyLibraryImport(state, message) {let result;let response;try {- result = mergeLibraryPackage(state, message.library, {- entryIdMap: message.entryIdMap,- compoundIdMap: message.compoundIdMap,- visualIdMap: message.visualIdMap,- sessionIdMap: message.sessionIdMap,- runIdMap: message.runIdMap,- skillIdMap: message.skillIdMap,- packageAssetIdMap: message.packageAssetIdMap,- preserveLibraryConfiguration: message.preserveLibraryConfiguration === true+ result = planLibraryTransfer({+ currentState: state,+ inspection: transferInspectionMessage(message.library, {+ sourceType: message.plan?.sourceType,+ importReport: message.plan?.importReport,+ resourceIndex: {+ mediaAssetIds: (message.plan?.resourceWrites ?? [])+ .filter((item) => item.resourceType === "media").map((item) => item.sourceId),+ skillAssetIds: (message.plan?.resourceWrites ?? [])+ .filter((item) => item.resourceType === "skill").map((item) => item.sourceId)+ }+ }),+ options: { preferredPlan: message.plan }});+ if (result.planToken !== message.planToken) {+ throw Object.assign(new Error("导入计划已经变化,请重新检查"), { code: "IMPORT_PLAN_STALE" });+ }response = libraryImportResponse(result);const completed = succeedLibraryImportTransaction(claim.state, claim.receipt, response);- await commitLocalChanges({- ...storagePayload(result.state),- [STORAGE_KEYS.settings]: normalizeSettings(result.state.settings ?? state.settings),- [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.state.composerSettings ?? state.composerSettings),- [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.state.composerSessions ?? state.composerSessions),+ const exactReplace = result.context.mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE;+ const previousRecoveryPoint = normalizeLibraryReplacementRecoveryPoint(state.libraryReplacementRecoveryPoint);+ const recoveryPoint = exactReplace+ ? createLibraryReplacementRecoveryPoint(folderBackupState(state), {+ retainedAssetIds: result.rollback.retainedAssetIds+ })+ : previousRecoveryPoint;+ const update = {+ ...storagePayload(result.targetState),+ [STORAGE_KEYS.settings]: normalizeSettings(result.targetState.settings ?? state.settings),+ [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.targetState.composerSettings ?? state.composerSettings),+ [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.targetState.composerSessions ?? state.composerSessions),[STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(- result.state.creativeExperimentSettings ?? state.creativeExperimentSettings+ result.targetState.creativeExperimentSettings ?? state.creativeExperimentSettings),- [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.state.creativeRuns ?? state.creativeRuns),- [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.state.creativeSkills ?? state.creativeSkills),- [STORAGE_KEYS.libraryImportTransactions]: completed.state- });+ [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.targetState.creativeRuns ?? state.creativeRuns),+ [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.targetState.creativeSkills ?? state.creativeSkills),+ [STORAGE_KEYS.libraryImportTransactions]: completed.state,+ ...(exactReplace ? { [STORAGE_KEYS.libraryReplacementRecoveryPoint]: recoveryPoint } : {})+ };+ await commitLocalChanges(update);+ if (exactReplace) {+ const obsoleteAssetIds = obsoleteRecoveryAssetIds(+ previousRecoveryPoint,+ [...collectRetainedLocalAssetIds(result.targetState)],+ recoveryPoint+ );+ await deleteMediaBlobs(obsoleteAssetIds).catch((error) => {+ console.error("Obsolete library recovery media cleanup failed", error);+ });+ response = { ...response, recoveryPointCreatedAt: recoveryPoint.createdAt };+ }} catch (error) {const failed = failLibraryImportTransaction(claim.state, claim.receipt);await commitLocalChanges({@@ -7125,7 +7182,7 @@ async function applyLibraryImport(state, message) {if (importedEntryIds.length) {const importedEntryIdSet = new Set(importedEntryIds);await enqueueAutomaticLibraryMaintenance(- result.state.entries.filter((entry) => importedEntryIdSet.has(entry.id))+ result.targetState.entries.filter((entry) => importedEntryIdSet.has(entry.id))).catch((error) => console.error("Imported library maintenance could not be queued", error));}if (importedEntryIds.length && message.autoAnalyze === true) {@@ -7135,13 +7192,54 @@ async function applyLibraryImport(state, message) {return response;}+async function restoreLibraryReplacementPoint(state) {+ const point = normalizeLibraryReplacementRecoveryPoint(state.libraryReplacementRecoveryPoint);+ if (!point) return { ok: false, message: "当前没有可回退的资料库状态" };+ const currentManagedState = folderBackupState(state);+ const swapped = swapLibraryReplacementRecoveryPoint(currentManagedState, point, {+ retainedAssetIds: [...collectRetainedLocalAssetIds(currentManagedState)]+ });+ await commitLocalChanges({+ ...storagePayload(swapped.targetState),+ [STORAGE_KEYS.settings]: normalizeSettings(swapped.targetState.settings ?? state.settings),+ [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(swapped.targetState.composerSettings),+ [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(swapped.targetState.composerSessions),+ [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(+ swapped.targetState.creativeExperimentSettings+ ),+ [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(swapped.targetState.creativeRuns),+ [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(swapped.targetState.creativeSkills),+ [STORAGE_KEYS.libraryReplacementRecoveryPoint]: swapped.recoveryPoint+ });+ return {+ ok: true,+ message: "已回退到上一次精确替换前的资料库;刚才的状态已保存为新的回退点",+ recoveryPointCreatedAt: swapped.recoveryPoint.createdAt+ };+}++function transferInspectionMessage(library, options = {}) {+ return {+ sourceType: Object.values(LIBRARY_TRANSFER_SOURCES).includes(options.sourceType)+ ? options.sourceType+ : LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ state: library,+ report: options.importReport ?? {+ status: Array.isArray(library?.importDiagnostics) && library.importDiagnostics.length ? "partial" : "ready",+ diagnostics: Array.isArray(library?.importDiagnostics) ? library.importDiagnostics : [],+ stats: library?.importStats && typeof library.importStats === "object" ? library.importStats : {}+ },+ resourceIndex: options.resourceIndex ?? { mediaAssetIds: [], skillAssetIds: [] }+ };+}+function libraryImportResponse(result) {return {ok: true,message: result.importedCount || result.importedRunCount || result.importedSkillCount? `已导入 ${result.importedCount} 个案例、${result.importedRunCount} 次创作运行和 ${result.importedSkillCount} 个 Skill${result.remappedCount ? `;其中 ${result.remappedCount} 个同源案例作为新副本导入,未覆盖旧数据` : ""}${result.skippedCount || result.skippedSkillCount ? `,跳过 ${result.skippedCount} 个已有案例和 ${result.skippedSkillCount} 个已有 Skill` : ""}`: `没有新增内容,${result.skippedCount} 个案例已经存在`,- count: result.state.entries.length,+ count: result.targetState.entries.length,importedCount: result.importedCount,remappedCount: result.remappedCount,skippedCount: result.skippedCount,@@ -7337,11 +7435,16 @@ async function performManualSynchronization(start) {};}if (result.upToDate) {+ const pendingCleanupCount = Math.max(0, Number(result.cleanupPendingCount) || 0);return {...result,ok: true,libraryChanged: false,- message: "两端没有变化,没有写入同步文件夹"+ message: pendingCleanupCount+ ? `两端资料已经一致;${pendingCleanupCount} 项本机过期媒体将在下次同步继续清理`+ : result.effects?.localMediaDeleted+ ? "两端资料没有变化;已完成本机过期媒体清理"+ : "两端没有变化,没有写入同步文件夹"};}return {@@ -7379,7 +7482,31 @@ function syncResultMessage(result = {}) {summary.deleted ? `删除 ${summary.deleted} 项` : "",summary.conflicts ? `保留 ${summary.conflicts} 个冲突副本` : ""].filter(Boolean).join(",");- return changes ? `手动同步完成:${changes}` : "手动同步完成";+ const pendingCleanupCount = Math.max(0, Number(result.cleanupPendingCount) || 0);+ const cleanup = pendingCleanupCount+ ? `;${pendingCleanupCount} 项本机过期媒体将在下次同步继续清理`+ : "";+ const skippedMediaCount = Math.max(0, Number(result.skippedMediaCount) || 0);+ const salvage = skippedMediaCount+ ? `;已跳过并清理 ${skippedMediaCount} 项本机缺失媒体,其他资料已继续同步`+ : "";+ const skippedMediaDetails = syncSkippedMediaLabels(result.skippedMedia);+ const details = skippedMediaDetails.length ? `;缺失项:${skippedMediaDetails.join("、")}` : "";+ return `${changes ? `手动同步完成:${changes}` : "手动同步完成"}${salvage}${details}${cleanup}`;+}++function syncSkippedMediaLabels(itemsValue) {+ const labels = (Array.isArray(itemsValue) ? itemsValue : []).map((item) => {+ const owner = cleanSyncMessagePart(item?.ownerTitle);+ const source = cleanSyncMessagePart(item?.sourceTitle);+ if (owner && source && owner !== source) return `${owner} / ${source}`;+ return owner || source || cleanSyncMessagePart(item?.assetId);+ }).filter(Boolean);+ return [...new Set(labels)];+}++function cleanSyncMessagePart(value) {+ return String(value ?? "").replace(/[;;\r\n]+/gu, " ").trim();}function notifySyncProgress(progress = {}) {@@ -7449,6 +7576,8 @@ async function dataSafetyStatus(state) {mediaCount: media.length,videoCount: media.filter((asset) => asset.kind === "video").length,documentCount: media.filter((asset) => asset.kind === "document").length,+ canRestoreReplacementPoint: Boolean(state.libraryReplacementRecoveryPoint),+ replacementPointCreatedAt: state.libraryReplacementRecoveryPoint?.createdAt || "",syncStatus: state.syncStatus};}@@ -7472,6 +7601,7 @@ async function publicSyncStatus(settingsValue) {lastErrorCode: settings.lastErrorCode,localDirty: meta.localDirty,dirtyAssetCount: meta.dirtyAssetIds.length,+ pendingCleanupAssetCount: meta.pendingCleanupAssetIds.length,...run};}diff --git a/creative-skills.js b/creative-skills.jsindex 277f44e..b1e014e 100644--- a/creative-skills.js+++ b/creative-skills.js@@ -179,6 +179,7 @@ export function mergeCreativeSkillsState(currentValue, importedValue, options =const usedVersionIds = new Set(state.items.flatMap((item) => item.versions.map((version) => version.id)));const usedAssetIds = new Set(state.items.flatMap((item) => item.packageFiles.map((file) => file.assetId)));const skillIdMap = {};+ const skillVersionIdMap = { ...(options.skillVersionIdMap ?? {}) };const packageAssetIdMap = { ...(options.packageAssetIdMap ?? {}) };let importedSkillCount = 0;let skippedSkillCount = 0;@@ -201,8 +202,15 @@ export function mergeCreativeSkillsState(currentValue, importedValue, options =skill.portableId = uniquePortableId(state, skill.portableId);skill.versions = skill.versions.map((version) => {const next = { ...version };- if (usedVersionIds.has(next.id)) next.id = uniqueEntityId("skill-version", usedVersionIds);+ const sourceVersionId = next.id;+ const preferredVersionId = cleanText(skillVersionIdMap[sourceVersionId]);+ if (usedVersionIds.has(next.id)) {+ next.id = preferredVersionId && !usedVersionIds.has(preferredVersionId)+ ? preferredVersionId+ : uniqueEntityId("skill-version", usedVersionIds);+ }usedVersionIds.add(next.id);+ skillVersionIdMap[sourceVersionId] = next.id;return next;});const currentVersionIndex = source.versions.findIndex((version) => version.id === source.currentVersionId);@@ -219,7 +227,7 @@ export function mergeCreativeSkillsState(currentValue, importedValue, options =state.items.push(skill);importedSkillCount += 1;}- return { state, skillIdMap, packageAssetIdMap, importedSkillCount, skippedSkillCount };+ return { state, skillIdMap, skillVersionIdMap, packageAssetIdMap, importedSkillCount, skippedSkillCount };}function normalizeCreativeSkill(value) {diff --git a/docs/DATA_COMPATIBILITY.md b/docs/DATA_COMPATIBILITY.mdindex 8db3400..b4b61bf 100644--- a/docs/DATA_COMPATIBILITY.md+++ b/docs/DATA_COMPATIBILITY.md@@ -10,6 +10,16 @@ PromptDirector 把正式发布的数据格式视为长期产品契约。应用- 无法恢复的字节不会被伪造;程序跳过损坏对象、保留可用内容并返回逐项诊断。- 涉及破坏性持久化变化时,至少保留一个正式版本的紧急回滚兼容窗口。+## 三条资料通道共用的安全合同++- 分享 ZIP、完整资料夹备份和加密同步共用同一套案例身份、媒体资源和清理规则;容器只负责读写文件或加密对象,不能各自解释资料结构。+- 导入和恢复必须先完成版本检查、迁移、逐项校验与计划确认,再一次性提交。一个损坏或不兼容的项目只影响自身,其他可恢复案例继续保留。+- 完整资料夹备份用于跨设备灾难恢复。安全合并保留本机资料并处理冲突;精确替换只接收完整备份,提交前建立可回退状态,容量不足或写入失败不得改变现有资料库。+- 完成标记有效但单个内容资源后来损坏时,恢复会降级为明确的救援流程,只隔离具体坏项并禁止精确替换;无法定位到具体坏项的解析错误仍停止,不以容错隐藏程序故障。+- 同步保留版本合并和可见冲突副本;只有完整内容指纹能够证明相同的不同编号案例才会收敛。缺少完整媒体哈希时保留两份,不猜测覆盖。+- 同步发现本机媒体确已缺失时会列出对应案例和文件,清理该坏引用后继续同步其他资料;媒体存储读取异常仍停止且不提交部分结果。+- 媒体物理删除只能发生在资料状态提交成功之后。清理失败只允许留下额外字节,并在后续手动同步重试;活动资料、回收站、创作记录、暂存任务和恢复回退点仍引用的媒体不得删除。+## 权威清单- `test/fixtures/compat/compatibility-matrix.json`:正式分享包和本机资料库结构清单。@@ -27,4 +37,4 @@ PromptDirector 把正式发布的数据格式视为长期产品契约。应用4. 为案例、媒体、标签、项目、回收站和创作会话写出保留或显式丢弃规则。5. 运行 `npm run check:compat`,再运行完整 `npm run verify`。-`npm run verify` 会在最终打包后执行上一正式版升级演练。GitHub 的 `Release safety` 工作流会对提交重复执行兼容检查、完整 Chromium E2E、两个 Chrome 包以及最终包升级演练。+`npm run verify` 会在最终打包后执行上一正式版升级演练。GitHub 的 `Release safety` 工作流会对提交重复执行兼容检查、完整 Chromium E2E、两个 Chrome 包以及最终包升级演练。另一台设备上的真实事故备份仍需在取得文件后单独验收,重建夹具不能替代原文件证据。diff --git a/docs/KNOWN_LIMITATIONS.md b/docs/KNOWN_LIMITATIONS.mdindex e678179..81f46dc 100644--- a/docs/KNOWN_LIMITATIONS.md+++ b/docs/KNOWN_LIMITATIONS.md@@ -5,9 +5,3 @@PromptDirector 目前依赖 Chrome 的原生媒体解码能力。遇到浏览器无法解码、但系统播放器可以播放的 MPEG-4 文件时,案例仍会保留原文件和来源信息,并提供使用系统播放器打开的路径;当前版本不在扩展内置软件解码器。后续如实施软件解码,至少需要同时满足以下验收条件:不改变原文件、不会把解码失败误报为导入成功、能中止长时间任务、限制内存与临时存储占用,并在发布包体积与浏览器安全策略检查通过后再启用。--## 超大分享 ZIP 的导出前容量预检--分享 ZIP 导入会按文件数量、单文件大小、总大小和元数据大小执行安全校验;当前导出流程还没有在写包前复用全部同一套估算,因此极大资料集可能在接收方导入时才发现超过边界。完整资料库迁移请使用完整资料夹备份,不要把单个超大分享 ZIP 当作灾难恢复备份。--后续增强应让导出与导入共享同一容量计划,在开始生成前列出超限项并阻止产生无法导回的包;不能只放宽限制或在导入端静默丢弃内容。diff --git a/i18n.js b/i18n.jsindex eda4d0a..a59a286 100644--- a/i18n.js+++ b/i18n.js@@ -276,7 +276,42 @@ const EN = Object.freeze({"0 个案例 · 0 张图片": "0 cases · 0 images","备份资料库": "Back up library","恢复资料库": "Restore library",- "备份会把案例和本地媒体逐项写入资料夹;恢复前会先检查内容,不会覆盖现有资料。": "Backup writes cases and local media to a folder one item at a time. Restore checks contents first and never overwrites existing material.",+ "回退上次精确恢复": "Undo last exact restore",+ "备份会把案例和本地媒体逐项写入资料夹;恢复默认安全合并。只有完整备份可在明确选择并建立回退点后精确替换。": "Backup writes cases and local media to a folder one item at a time. Restore uses safe merge by default. Only a complete backup can exactly replace managed library data after you explicitly choose it and a recovery point is created.",+ "完整恢复": "Complete restore",+ "救援恢复": "Rescue restore",+ "{label}预检完成 · {caseCount} 个案例 · {mediaCount} 项本地媒体 · {byteSize}": "{label} preflight complete · {caseCount} cases · {mediaCount} local files · {byteSize}",+ "恢复方式": "Restore method",+ "安全合并(推荐)": "Safe merge (recommended)",+ "恢复成备份当时状态": "Restore to the backup state",+ "安全合并保留本机资料;精确替换会替换完整备份管理的案例、项目、回收站和关联资料。": "Safe merge keeps local content. Exact restore replaces the cases, projects, recycle bin, and related content managed by the complete backup.",+ "冲突案例:本机“{localTitle}” / 备份“{incomingTitle}”": "Conflicting case: local “{localTitle}” / backup “{incomingTitle}”",+ "保留本机版本(推荐)": "Keep local version (recommended)",+ "使用备份版本": "Use backup version",+ "两个版本都保留": "Keep both versions",+ "选择资料库恢复方式": "Choose a library restore method",+ "检查救援恢复方案": "Review rescue restore plan",+ "已检查 {caseCount} 个案例;发现 {conflictCount} 个内容冲突。安全合并为默认方式。": "Checked {caseCount} cases and found {conflictCount} content conflicts. Safe merge is the default.",+ "这是不完整来源,只能安全合并。已检查 {caseCount} 个案例;发现 {conflictCount} 个内容冲突。": "This source is incomplete and can only use safe merge. Checked {caseCount} cases and found {conflictCount} content conflicts.",+ "继续检查": "Continue review",+ "已取消恢复,资料库没有变化": "Restore canceled. The library was not changed.",+ "无法生成资料夹恢复计划": "Could not create the folder restore plan",+ "发现可恢复问题,详情见确认框": "Recoverable issues found; review the confirmation dialog",+ "检查通过": "Checks passed",+ "将资料库恢复成备份当时状态?": "Restore the library to the backup state?",+ "安全合并资料库备份?": "Safely merge the library backup?",+ "按救援方案恢复资料库?": "Restore the library with the rescue plan?",+ "将写入 {byteSize} 资源,并替换完整备份管理的案例、项目、回收站和关联资料。开始前会自动建立回退点;API Key、同步密码、设备信息和文件夹授权保持本机状态。": "This writes {byteSize} of resources and replaces the cases, projects, recycle bin, and related content managed by the complete backup. A recovery point is created first; API keys, sync passwords, device information, and folder permissions remain local.",+ "只会提交预检确认的健康内容;冲突按你的选择处理,其他本机资料不会被覆盖。": "Only healthy content confirmed by preflight is committed. Conflicts follow your choices, and other local content is not overwritten.",+ "建立回退点并精确恢复": "Create recovery point and restore exactly",+ "开始安全合并": "Start safe merge",+ "开始救援恢复": "Start rescue restore",+ "{label}已按预检方案完成": "{label} completed with the preflight plan",+ "回退上次精确恢复?": "Undo the last exact restore?",+ "资料库会回到上次精确恢复前的状态;当前状态也会保存成新的回退点,因此仍可再次切换回来。": "The library returns to its state before the last exact restore. The current state is saved as a new recovery point, so you can switch back again.",+ "确认回退": "Confirm undo",+ "现有资料不会被覆盖。": "Existing content will not be overwritten.",+ "回退点建立于 {date}": "Recovery point created at {date}","连接和解锁只验证文件夹与密码,不会读取、合并或上传资料。只有你再次确认“立即同步”后,才会执行一次同步。": "Connect and unlock only verify the folder and password; they do not read, merge, or upload content. A one-time sync runs only after you confirm Sync now.","停止同步": "Stop sync","正在确认安装方式…": "Checking installation method…",@@ -2093,6 +2128,23 @@ export function translateUiMessage(value) {[/^正在检查 (.+)…$/, "Checking $1..."],[/^正在导入 (.+)…$/, "Importing $1..."],[/^正在导入 (\d+) 个案例…$/, "Importing $1 cases..."],+ [/^完整性标记异常,本次只能按救援方案恢复$/, "The integrity marker is invalid, so this restore can only use a rescue plan"],+ [/^忽略清单外文件 (\d+) 项$/, "Ignored $1 files not listed in the manifest"],+ [/^完全相同,跳过 (\d+) 个$/, "Skipped $1 identical cases"],+ [/^同一来源有新内容,保留副本 (\d+) 个$/, "Kept $1 copies with new content from the same source"],+ [/^丢弃损坏的 AI 标签 (\d+) 条$/, "Discarded $1 damaged AI tags"],+ [/^丢弃损坏的媒体描述 (\d+) 条$/, "Discarded $1 damaged media descriptors"],+ [/^丢弃损坏或缺失的媒体 (\d+) 项$/, "Discarded $1 damaged or missing media items"],+ [/^已跳过并清理 (\d+) 项本机缺失媒体,其他资料已继续同步$/, "Skipped and cleaned up $1 missing local media items. Other library data continued syncing."],+ [/^缺失项:(.+)$/, "Missing items: $1"],+ [/^跳过无法恢复的案例 (\d+) 个$/, "Skipped $1 unrecoverable cases"],+ [/^恢复 (\d+) 个 Skill、(\d+) 项本地文件((.+))$/, "Recovered $1 Skills and $2 local files ($3)"],+ [/^恢复 (\d+) 个 Skill$/, "Recovered $1 Skills"],+ [/^恢复 (\d+) 项本地文件((.+))$/, "Recovered $1 local files ($2)"],+ [/^恢复 (\d+) 项本地文件$/, "Recovered $1 local files"],+ [/^可导入 (\d+) 个新案例$/, "$1 new cases can be imported"],+ [/^没有需要新建的案例$/, "No cases need to be created"],+ [/^导入不会自动启动 AI 分析$/, "Import does not start AI analysis automatically"],[/^没有新增案例,(\d+) 个案例已经存在$/, "No new cases. $1 already exist."],[/^待确认 (\d+)$/, "$1 need review"],[/^待确认建议 (\d+)$/, "$1 suggestions to review"],diff --git a/import-staging.js b/import-staging.jsindex 5843025..666f319 100644--- a/import-staging.js+++ b/import-staging.js@@ -10,6 +10,7 @@ import {isReportedMimeCompatible} from "./asset-formats.js";import { ASSET_IMPORT_FAILURE_CODES } from "./resource-limits.js";+import { libraryStoredAssetIds } from "./library-asset-inventory.js";const KINDS = new Set(SUPPORTED_ASSET_KINDS);@@ -55,24 +56,7 @@ export function importStagingAssetIds(stateValue) {}export function collectRetainedLocalAssetIds(state = {}) {- return new Set([- ...(Array.isArray(state.entries) ? state.entries : [])- .flatMap((entry) => Array.isArray(entry?.mediaAssets) ? entry.mediaAssets.map((asset) => asset?.id) : []),- ...(Array.isArray(state.creativeRuns) ? state.creativeRuns : [])- .flatMap((run) => (Array.isArray(run?.outputs) ? run.outputs : []).map((output) => output?.visual?.id)),- ...(Array.isArray(state.creativeSkills?.items) ? state.creativeSkills.items : [])- .flatMap((skill) => (Array.isArray(skill?.packageFiles) ? skill.packageFiles : []).map((file) => file?.assetId)),- ...(Array.isArray(state.composerSessions) ? state.composerSessions : []).flatMap(temporarySessionAssetIds),- ...(Array.isArray(state.creativeJobs?.items) ? state.creativeJobs.items : [])- .flatMap((job) => temporarySessionAssetIds(job?.request?.session)),- ...importStagingAssetIds(state.importStaging)- ].map(clean).filter(Boolean));-}--function temporarySessionAssetIds(session) {- return (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : [])- .filter((reference) => reference?.sourceType === "temporary")- .flatMap((reference) => (Array.isArray(reference?.assetRefs) ? reference.assetRefs : []).map((asset) => asset?.assetId));+ return libraryStoredAssetIds(state, { includeLocalOnly: true });}function normalizeStagedAsset(value) {diff --git a/library-asset-inventory.js b/library-asset-inventory.jsnew file mode 100644index 0000000..5abc72b--- /dev/null+++ b/library-asset-inventory.js@@ -0,0 +1,115 @@+export function libraryStoredAssets(stateValue = {}, options = {}) {+ const state = stateValue && typeof stateValue === "object" ? stateValue : {};+ const assets = durableAssets(state);+ if (options.includeLocalOnly === true) assets.push(...localOnlyAssets(state));+ return assets.filter((asset) => storedAssetId(asset));+}++export function libraryStoredAssetIds(stateValue = {}, options = {}) {+ return new Set(libraryStoredAssets(stateValue, options).map(storedAssetId));+}++export function libraryLocalOnlyAssets(stateValue = {}) {+ const state = stateValue && typeof stateValue === "object" ? stateValue : {};+ return localOnlyAssets(state).filter((asset) => storedAssetId(asset));+}++export function libraryLocalOnlyAssetIds(stateValue = {}) {+ return new Set(libraryLocalOnlyAssets(stateValue).map(storedAssetId));+}++export function libraryAssetCleanupCandidates(beforeState = {}, afterState = {}, options = {}) {+ const retained = new Set([+ ...libraryStoredAssetIds(afterState),+ ...libraryLocalOnlyAssetIds(options.localOnlyState ?? afterState)+ ]);+ return [...new Set([+ ...libraryStoredAssetIds(beforeState),+ ...(Array.isArray(options.pendingAssetIds) ? options.pendingAssetIds.map(clean) : [])+ ].filter(Boolean))].filter((assetId) => !retained.has(assetId)).sort();+}++function durableAssets(state) {+ return [+ ...entryAssets(state.entries),+ ...trashAssets(state.trashState?.items),+ ...creativeRunAssets(state.creativeRuns),+ ...creativeSkillAssets(state.creativeSkills?.items),+ ...temporarySessionAssets(state.composerSessions)+ ];+}++function localOnlyAssets(state) {+ const recoveryPoint = state.libraryReplacementRecoveryPoint;+ return [+ ...creativeJobAssets(state.creativeJobs?.items),+ ...importStagingAssets(state.importStaging?.assets),+ ...(recoveryPoint?.state && typeof recoveryPoint.state === "object"+ ? durableAssets(recoveryPoint.state)+ : []),+ ...(Array.isArray(recoveryPoint?.retainedAssetIds)+ ? recoveryPoint.retainedAssetIds.map((id) => ({ id }))+ : [])+ ];+}++function entryAssets(entries) {+ return (Array.isArray(entries) ? entries : []).flatMap((entry) =>+ Array.isArray(entry?.mediaAssets)+ ? entry.mediaAssets+ : Array.isArray(entry?.visuals) ? entry.visuals : []+ );+}++function trashAssets(items) {+ return (Array.isArray(items) ? items : []).flatMap((item) => {+ if (!item || typeof item !== "object") return [];+ const snapshot = item.snapshot;+ if (!snapshot || typeof snapshot !== "object") return [];+ if (Array.isArray(snapshot.mediaAssets)) return snapshot.mediaAssets;+ return Array.isArray(snapshot.visuals) ? snapshot.visuals : [];+ });+}++function creativeRunAssets(runs) {+ return (Array.isArray(runs) ? runs : []).flatMap((run) =>+ (Array.isArray(run?.outputs) ? run.outputs : []).map((output) => output?.visual)+ );+}++function creativeSkillAssets(skills) {+ return (Array.isArray(skills) ? skills : []).flatMap((skill) =>+ Array.isArray(skill?.packageFiles) ? skill.packageFiles : []+ );+}++function temporarySessionAssets(sessions) {+ return (Array.isArray(sessions) ? sessions : []).flatMap((session) =>+ (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : [])+ .filter((reference) => reference?.sourceType === "temporary")+ .flatMap((reference) => Array.isArray(reference?.assetRefs) ? reference.assetRefs : [])+ );+}++function creativeJobAssets(jobs) {+ return (Array.isArray(jobs) ? jobs : []).flatMap((job) =>+ temporarySessionAssets([job?.request?.session])+ );+}++function importStagingAssets(items) {+ return (Array.isArray(items) ? items : []).flatMap((item) => [+ clean(item?.assetId) ? { id: clean(item.assetId) } : null,+ item?.posterAsset && typeof item.posterAsset === "object"+ ? item.posterAsset+ : clean(item?.posterAssetId) ? { id: clean(item.posterAssetId) } : null+ ]);+}++export function storedAssetId(asset) {+ return clean(asset?.id ?? asset?.assetId);+}++function clean(value) {+ return String(value ?? "").trim();+}diff --git a/library-asset-salvage.js b/library-asset-salvage.jsnew file mode 100644index 0000000..67dbcfc--- /dev/null+++ b/library-asset-salvage.js@@ -0,0 +1,187 @@+import { removeEntryMedia } from "./media.js";++const AI_ASSIGNMENT_SOURCES = new Set(["deepseek_text", "local_image_review", "vision_model"]);++export function salvageMissingLibraryAssets(stateValue = {}, missingAssetIdsValue = []) {+ const state = stateValue && typeof stateValue === "object" ? structuredClone(stateValue) : {};+ const missing = new Set([...(missingAssetIdsValue instanceof Set+ ? missingAssetIdsValue+ : Array.isArray(missingAssetIdsValue) ? missingAssetIdsValue : [])].map(clean).filter(Boolean));+ const issues = new Map([...missing].map((assetId) => [assetId, { assetId }]));+ if (!missing.size) return { state, issues: [] };++ const annotate = (assetIdValue, owner) => {+ const assetId = clean(assetIdValue);+ if (!missing.has(assetId)) return;+ const current = issues.get(assetId) ?? { assetId };+ if (!current.ownerType) issues.set(assetId, { ...current, ...owner });+ };++ state.entries = (Array.isArray(state.entries) ? state.entries : []).flatMap((entry) => {+ const result = salvageEntry(entry, missing, (assetId, asset) => annotate(assetId, {+ ownerType: "case",+ ownerId: clean(entry?.id),+ ownerTitle: clean(entry?.title),+ sourceTitle: clean(asset?.sourceTitle)+ }));+ return hasRecoverableCaseContent(result) ? [result] : [];+ });+ const activeEntryIds = new Set(state.entries.map((entry) => clean(entry?.id)).filter(Boolean));++ if (state.organizerState && typeof state.organizerState === "object") {+ state.organizerState.collections = (Array.isArray(state.organizerState.collections)+ ? state.organizerState.collections+ : []).map((collection) => ({+ ...collection,+ entryIds: uniqueIds(collection?.entryIds).filter((entryId) => activeEntryIds.has(entryId))+ }));+ }+ state.compoundCases = (Array.isArray(state.compoundCases) ? state.compoundCases : []).flatMap((compound) => {+ const memberEntryIds = uniqueIds(compound?.memberEntryIds).filter((entryId) => activeEntryIds.has(entryId));+ if (memberEntryIds.length < 2) return [];+ return [{+ ...compound,+ memberEntryIds,+ coverVisualId: missing.has(clean(compound?.coverVisualId)) ? "" : clean(compound?.coverVisualId)+ }];+ });++ if (state.trashState && typeof state.trashState === "object") {+ state.trashState.items = (Array.isArray(state.trashState.items) ? state.trashState.items : []).flatMap((item) => {+ if (!item || !["entry", "media"].includes(item.kind)) return [item];+ const assets = Array.isArray(item?.snapshot?.mediaAssets) ? item.snapshot.mediaAssets : [];+ for (const asset of assets) annotate(asset?.id, {+ ownerType: "trash",+ ownerId: clean(item?.targetId),+ ownerTitle: clean(item?.snapshot?.title || item?.snapshot?.sourceTitle),+ sourceTitle: clean(asset?.sourceTitle)+ });+ if (item.kind === "entry") {+ const snapshot = salvageEntry(item.snapshot, missing);+ return hasRecoverableCaseContent(snapshot) ? [{ ...item, snapshot }] : [];+ }+ const mediaAssets = assets.filter((asset) => !missing.has(clean(asset?.id)));+ if (!mediaAssets.some((asset) => clean(asset?.id) === clean(item.targetId))) return [];+ const retained = new Set(mediaAssets.map((asset) => clean(asset?.id)).filter(Boolean));+ return [{+ ...item,+ snapshot: {+ ...item.snapshot,+ mediaAssets,+ facetAssignments: salvageFacetAssignments(item.snapshot?.facetAssignments, missing)+ },+ relationships: {+ ...(item.relationships ?? {}),+ positions: (Array.isArray(item.relationships?.positions) ? item.relationships.positions : [])+ .filter((position) => retained.has(clean(position?.id))),+ primaryMediaId: retained.has(clean(item.relationships?.primaryMediaId))+ ? item.relationships.primaryMediaId+ : "",+ facetAssignments: salvageFacetAssignments(item.relationships?.facetAssignments, missing)+ }+ }];+ });+ }++ state.creativeRuns = (Array.isArray(state.creativeRuns) ? state.creativeRuns : []).map((run) => {+ const outputs = (Array.isArray(run?.outputs) ? run.outputs : []).filter((output) => {+ const assetId = clean(output?.visual?.id);+ annotate(assetId, {+ ownerType: "creative_run",+ ownerId: clean(run?.id),+ ownerTitle: clean(run?.title),+ sourceTitle: clean(output?.visual?.sourceTitle)+ });+ return !missing.has(assetId);+ });+ const retained = new Set(outputs.map((output) => clean(output?.visual?.id)).filter(Boolean));+ return {+ ...run,+ outputs,+ events: (Array.isArray(run?.events) ? run.events : []).filter((event) => retained.has(clean(event?.visualId)))+ };+ });++ if (state.creativeSkills && typeof state.creativeSkills === "object") {+ state.creativeSkills.items = (Array.isArray(state.creativeSkills.items) ? state.creativeSkills.items : []).map((skill) => ({+ ...skill,+ packageFiles: (Array.isArray(skill?.packageFiles) ? skill.packageFiles : []).filter((file) => {+ const assetId = clean(file?.assetId);+ annotate(assetId, {+ ownerType: "creative_skill",+ ownerId: clean(skill?.id),+ ownerTitle: clean(skill?.name || skill?.callName),+ sourceTitle: clean(file?.path)+ });+ return !missing.has(assetId);+ })+ }));+ }++ state.composerSessions = (Array.isArray(state.composerSessions) ? state.composerSessions : []).map((session) => ({+ ...session,+ referenceSnapshots: (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : []).flatMap((reference) => {+ if (reference?.sourceType !== "temporary") return [reference];+ for (const asset of Array.isArray(reference?.assetRefs) ? reference.assetRefs : []) annotate(asset?.assetId, {+ ownerType: "composer_session",+ ownerId: clean(session?.id),+ ownerTitle: clean(session?.title),+ sourceTitle: clean(asset?.name)+ });+ const next = {+ ...reference,+ assetId: missing.has(clean(reference?.assetId)) ? "" : clean(reference?.assetId),+ assetRefs: (Array.isArray(reference?.assetRefs) ? reference.assetRefs : [])+ .filter((asset) => !missing.has(clean(asset?.assetId))),+ imageRefs: (Array.isArray(reference?.imageRefs) ? reference.imageRefs : [])+ .filter((asset) => !missing.has(clean(asset?.visualId))),+ assets: (Array.isArray(reference?.assets) ? reference.assets : [])+ .filter((asset) => !missing.has(clean(asset?.assetId)))+ };+ return clean(next.referenceText) || next.assetRefs.length || next.imageRefs.length ? [next] : [];+ })+ }));++ return { state, issues: [...issues.values()].sort((left, right) => compareIds(left.assetId, right.assetId)) };+}++function salvageEntry(entryValue, missing, onMissing = () => undefined) {+ let entry = entryValue && typeof entryValue === "object" ? structuredClone(entryValue) : {};+ const assets = Array.isArray(entry.mediaAssets) ? entry.mediaAssets : Array.isArray(entry.visuals) ? entry.visuals : [];+ for (const asset of assets) {+ if (!missing.has(clean(asset?.id))) continue;+ onMissing(clean(asset.id), asset);+ entry = removeEntryMedia(entry, asset.id);+ }+ entry.facetAssignments = salvageFacetAssignments(entry.facetAssignments, missing);+ return entry;+}++function salvageFacetAssignments(values, missing) {+ return (Array.isArray(values) ? values : []).flatMap((assignment) => {+ if (!missing.has(clean(assignment?.visualId))) return [assignment];+ if (AI_ASSIGNMENT_SOURCES.has(assignment?.source)) return [];+ const { visualId: _visualId, ...rest } = assignment;+ return [rest];+ });+}++function hasRecoverableCaseContent(entry = {}) {+ if ([entry.title, entry.text, entry.note, entry.url].some((value) => clean(value))) return true;+ if ((entry.mediaAssets ?? []).some((asset) => asset && typeof asset === "object")) return true;+ return (entry.articleDocument?.blocks ?? []).some((block) => clean(block?.text) || clean(block?.assetId));+}++function uniqueIds(values) {+ return [...new Set((Array.isArray(values) ? values : []).map(clean).filter(Boolean))];+}++function compareIds(leftValue, rightValue) {+ const left = clean(leftValue);+ const right = clean(rightValue);+ return left < right ? -1 : left > right ? 1 : 0;+}++function clean(value) {+ return String(value ?? "").trim();+}diff --git a/library-export-plan.js b/library-export-plan.jsindex dde84b1..bb974b8 100644--- a/library-export-plan.js+++ b/library-export-plan.js@@ -1,14 +1,55 @@const FOLDER_BACKUP_FORMAT = "prompt-director-folder-backup";+const FOLDER_RESCUE_FORMAT = "prompt-director-folder-rescue";+const BACKUP_MARKER_PATHS = new Set(["complete.json", "rescue.json"]);export async function buildFolderBackupCompletion(filesValue, metadata = {}) {+ return buildFolderMarker(filesValue, metadata, {+ format: FOLDER_BACKUP_FORMAT,+ version: 2,+ status: "complete"+ });+}++export async function buildFolderRescueCompletion(filesValue, metadata = {}) {+ return buildFolderMarker(filesValue, metadata, {+ format: FOLDER_RESCUE_FORMAT,+ version: 1,+ status: "rescue",+ issues: Array.isArray(metadata.issues) ? structuredClone(metadata.issues) : []+ });+}++export async function buildFolderBackupWritePlan({ files: filesValue, report = {}, metadata = {} } = {}) {+ const files = backupFiles(filesValue);+ if (!(files.get("library.json") instanceof Blob)) throw new Error("备份写入计划缺少 library.json");+ const diagnostics = Array.isArray(report?.diagnostics) ? structuredClone(report.diagnostics) : [];+ const rescue = report?.status === "partial" || diagnostics.length > 0;+ const marker = rescue+ ? await buildFolderRescueCompletion(files, { ...metadata, issues: diagnostics })+ : await buildFolderBackupCompletion(files, metadata);+ if (rescue) await verifyFolderRescueCompletion(marker, files);+ else await verifyFolderBackupCompletion(marker, files);+ return {+ mode: rescue ? "rescue" : "complete",+ markerPath: rescue ? "rescue.json" : "complete.json",+ marker,+ files,+ report: {+ status: rescue ? "partial" : "ready",+ diagnostics,+ stats: report?.stats && typeof report.stats === "object" ? structuredClone(report.stats) : {}+ }+ };+}++async function buildFolderMarker(filesValue, metadata, identity) {const files = backupFiles(filesValue);const manifest = [];for (const [path, blob] of [...files.entries()].sort(([left], [right]) => left.localeCompare(right))) {manifest.push({ path, byteSize: blob.size, sha256: await sha256Blob(blob) });}return {- format: FOLDER_BACKUP_FORMAT,- version: 2,+ ...identity,createdAt: validIso(metadata.createdAt) || new Date().toISOString(),caseCount: nonNegativeInteger(metadata.caseCount),trashCaseCount: nonNegativeInteger(metadata.trashCaseCount),@@ -21,31 +62,145 @@ export async function buildFolderBackupCompletion(filesValue, metadata = {}) {}export async function verifyFolderBackupCompletion(completionValue, filesValue) {+ return verifyFolderMarker(completionValue, filesValue, {+ format: FOLDER_BACKUP_FORMAT,+ version: 2,+ invalidMessage: "完整备份标记无效",+ integrityLabel: "完整备份"+ });+}++export async function verifyFolderRescueCompletion(completionValue, filesValue) {+ return verifyFolderMarker(completionValue, filesValue, {+ format: FOLDER_RESCUE_FORMAT,+ version: 1,+ invalidMessage: "救援备份标记无效",+ integrityLabel: "救援备份"+ });+}++export async function inspectFolderBackupEnvelope(filesValue) {+ const files = filesValue instanceof Map ? filesValue : new Map();+ const libraryFile = files.get("library.json");+ if (!(libraryFile instanceof Blob)) throw new Error("资料夹备份缺少 library.json");++ let completeFailure = null;+ const completeFile = files.get("complete.json");+ if (completeFile instanceof Blob) {+ try {+ const marker = await markerJson(completeFile);+ if (marker?.format === FOLDER_BACKUP_FORMAT && Number(marker.version) > 2) {+ throw updateRequiredError();+ }+ if (marker?.format === FOLDER_BACKUP_FORMAT && marker.version === 1) {+ return folderEnvelope("complete", marker, libraryFile, []);+ }+ const verification = await verifyFolderBackupCompletion(marker, files);+ return folderEnvelope("complete", marker, libraryFile, extraFileDiagnostics(verification.extraPaths));+ } catch (error) {+ if (error?.code === "BACKUP_MARKER_FUTURE") throw error;+ completeFailure = rescueDiagnostic("complete_integrity_failure");+ }+ } else {+ completeFailure = rescueDiagnostic("missing_complete_marker");+ }++ const rescueFile = files.get("rescue.json");+ if (rescueFile instanceof Blob) {+ try {+ const marker = await markerJson(rescueFile);+ if (marker?.format === FOLDER_RESCUE_FORMAT && Number(marker.version) > 1) {+ throw updateRequiredError();+ }+ const verification = await verifyFolderRescueCompletion(marker, files);+ const diagnostics = [+ ...(Array.isArray(marker.issues) ? structuredClone(marker.issues) : []),+ ...extraFileDiagnostics(verification.extraPaths)+ ];+ return folderEnvelope("rescue", marker, libraryFile, diagnostics);+ } catch (error) {+ if (error?.code === "BACKUP_MARKER_FUTURE") throw error;+ return folderEnvelope("rescue", null, libraryFile, [rescueDiagnostic("rescue_integrity_failure")]);+ }+ }++ return folderEnvelope("rescue", null, libraryFile, [completeFailure]);+}++function folderEnvelope(mode, marker, libraryFile, diagnostics) {+ return {+ mode,+ marker,+ libraryFile,+ report: {+ status: diagnostics.length ? "partial" : "ready",+ diagnostics,+ stats: {}+ }+ };+}++function rescueDiagnostic(reason) {+ return {+ code: "backup_integrity_degraded",+ severity: "backup",+ action: "rescue",+ reason+ };+}++function extraFileDiagnostics(paths) {+ return (Array.isArray(paths) ? paths : []).map((path) => ({+ code: "extra_file_ignored",+ severity: "file",+ action: "ignored",+ path,+ reason: "not_in_manifest"+ }));+}++async function markerJson(blob) {+ try {+ return JSON.parse(await blob.text());+ } catch {+ throw new Error("备份标记无法解析");+ }+}++function updateRequiredError() {+ return Object.assign(new Error("该资料夹由更高版本创建,请先更新 PromptDirector"), {+ code: "BACKUP_MARKER_FUTURE"+ });+}++async function verifyFolderMarker(completionValue, filesValue, expected) {const completion = completionValue && typeof completionValue === "object" ? completionValue : {};- if (completion.format !== FOLDER_BACKUP_FORMAT || completion.version !== 2 || !Array.isArray(completion.files)) {- throw new Error("完整备份标记无效");+ if (completion.format !== expected.format || completion.version !== expected.version || !Array.isArray(completion.files)) {+ throw new Error(expected.invalidMessage);}const files = backupFiles(filesValue);- if (completion.fileCount !== completion.files.length || files.size !== completion.files.length) {- throw new Error("完整备份的文件清单完整性校验失败");+ if (completion.fileCount !== completion.files.length) {+ throw new Error(`${expected.integrityLabel}的文件清单完整性校验失败`);}const expectedPaths = new Set();for (const descriptor of completion.files) {const path = safePath(descriptor?.path);- if (!path || expectedPaths.has(path)) throw new Error("完整备份的文件清单完整性校验失败");+ if (!path || expectedPaths.has(path)) throw new Error(`${expected.integrityLabel}的文件清单完整性校验失败`);expectedPaths.add(path);const blob = files.get(path);if (!(blob instanceof Blob) || blob.size !== descriptor.byteSize || await sha256Blob(blob) !== descriptor.sha256) {- throw new Error(`完整备份文件“${path}”完整性校验失败`);+ throw new Error(`${expected.integrityLabel}文件“${path}”完整性校验失败`);}}- return true;+ return {+ extraPaths: [...files.keys()].filter((path) => !expectedPaths.has(path)).sort()+ };}function backupFiles(value) {const source = value instanceof Map ? value : new Map();return new Map([...source].filter(([path, blob]) =>- safePath(path) && path !== "complete.json" && blob instanceof Blob+ safePath(path) && !BACKUP_MARKER_PATHS.has(path) && blob instanceof Blob));}diff --git a/library-import-dialog.js b/library-import-dialog.jsindex 5131766..be0fab3 100644--- a/library-import-dialog.js+++ b/library-import-dialog.js@@ -1,8 +1,14 @@export function buildLibraryImportReport(previewValue = {}, details = {}) {const preview = previewValue && typeof previewValue === "object" ? previewValue : {};const stats = preview.importStats && typeof preview.importStats === "object" ? preview.importStats : {};+ const diagnostics = Array.isArray(preview.importDiagnostics) ? preview.importDiagnostics : [];const importedCount = count(preview.importedCount);const lines = [];+ if (diagnostics.some((item) => item?.code === "backup_integrity_degraded")) {+ lines.push("完整性标记异常,本次只能按救援方案恢复");+ }+ const extraFileCount = diagnostics.filter((item) => item?.code === "extra_file_ignored").length;+ if (extraFileCount) lines.push(`忽略清单外文件 ${extraFileCount} 项`);if (count(preview.skippedCount)) lines.push(`完全相同,跳过 ${count(preview.skippedCount)} 个`);if (count(preview.remappedCount)) lines.push(`同一来源有新内容,保留副本 ${count(preview.remappedCount)} 个`);if (count(stats.droppedAiAssignments)) lines.push(`丢弃损坏的 AI 标签 ${count(stats.droppedAiAssignments)} 条`);@@ -13,7 +19,7 @@ export function buildLibraryImportReport(previewValue = {}, details = {}) {if (count(preview.importedSkillCount)) recoveredExtras.push(`${count(preview.importedSkillCount)} 个 Skill`);if (count(details.mediaCount)) recoveredExtras.push(`${count(details.mediaCount)} 项本地文件${details.byteLabel ? `(${details.byteLabel})` : ""}`);if (recoveredExtras.length) lines.push(`恢复 ${recoveredExtras.join("、")}`);- const partial = [+ const partial = diagnostics.length > 0 || [preview.skippedCount,preview.remappedCount,stats.droppedAiAssignments,diff --git a/library-import-media.js b/library-import-media.jsindex 71b9d1a..1227f1b 100644--- a/library-import-media.js+++ b/library-import-media.js@@ -14,19 +14,43 @@ export async function findInvalidImportedImageIds(images, validateImage) {return invalidIds;}-export function filesWithoutInvalidEntryMedia(libraryValue, files, invalidAssetIds) {+export function filesWithoutInvalidLibraryImages(libraryValue, files, invalidAssetIds) {if (!(files instanceof Map) || !(invalidAssetIds instanceof Set)) {throw new Error("媒体修复输入无效");}const result = new Map(files);- for (const entry of Array.isArray(libraryValue?.entries) ? libraryValue.entries : []) {+ const removeAssetPath = (assetIdValue, pathValue) => {+ if (!invalidAssetIds.has(clean(assetIdValue))) return;+ const path = clean(pathValue);+ if (path) result.delete(path);+ };+ const entries = [+ ...(Array.isArray(libraryValue?.entries) ? libraryValue.entries : []),+ ...(Array.isArray(libraryValue?.trashState?.items) ? libraryValue.trashState.items : []).flatMap((item) => {+ if (item?.kind === "entry") return [item.snapshot];+ if (item?.kind === "media") return [{ mediaAssets: item.snapshot?.mediaAssets ?? [] }];+ return [];+ })+ ];+ for (const entry of entries) {const mediaAssets = Array.isArray(entry?.mediaAssets)? entry.mediaAssets: Array.isArray(entry?.visuals) ? entry.visuals : [];for (const asset of mediaAssets) {- if (!invalidAssetIds.has(clean(asset?.id))) continue;- const path = clean(asset?.assetPath || asset?.screenshotPath);- if (path) result.delete(path);+ removeAssetPath(asset?.id, asset?.assetPath || asset?.screenshotPath);+ }+ }+ for (const run of Array.isArray(libraryValue?.creativeRuns) ? libraryValue.creativeRuns : []) {+ for (const output of Array.isArray(run?.outputs) ? run.outputs : []) {+ removeAssetPath(output?.visual?.id, output?.visual?.assetPath || output?.visual?.screenshotPath);+ }+ }+ for (const session of Array.isArray(libraryValue?.composerSessions) ? libraryValue.composerSessions : []) {+ for (const reference of Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : []) {+ if (reference?.sourceType !== "temporary") continue;+ for (const asset of Array.isArray(reference?.assetRefs) ? reference.assetRefs : []) {+ removeAssetPath(asset?.assetId, asset?.archivePath);+ }}}return result;diff --git a/library-import-transaction.js b/library-import-transaction.jsindex 47a5103..90198b5 100644--- a/library-import-transaction.js+++ b/library-import-transaction.js@@ -13,21 +13,22 @@ import { normalizeTrashState } from "./trash.js";import { caseSemanticFingerprint } from "./library-semantic-identity.js";import { normalizeCreativeSkillsState } from "./creative-skills.js";-const PLAN_TOKEN_VERSION = "v2";+const PLAN_TOKEN_VERSION = "v3";const DEFAULT_RECEIPT_TTL_MS = 30 * 60 * 1000;const RECEIPT_STATUSES = new Set(["pending", "completed"]);-export function createLibraryImportPlanToken(stateValue = {}, sourceValue = {}) {+export function createLibraryImportPlanToken(stateValue = {}, sourceValue = {}, planValue = {}) {const payload = stableJson({state: projectLibraryImportState(stateValue),- source: projectLibraryImportSource(sourceValue)+ source: projectLibraryImportSource(sourceValue),+ plan: cloneData(planValue)});return `import-plan:${PLAN_TOKEN_VERSION}:${fnv1a64(payload)}`;}-export function assertLibraryImportPlanCurrent(tokenValue, stateValue = {}, sourceValue = {}) {+export function assertLibraryImportPlanCurrent(tokenValue, stateValue = {}, sourceValue = {}, planValue = {}) {const token = String(tokenValue ?? "").trim();- if (token && token === createLibraryImportPlanToken(stateValue, sourceValue)) return;+ if (token && token === createLibraryImportPlanToken(stateValue, sourceValue, planValue)) return;throw Object.assign(new Error("预览后资料库发生了变化,请重新检查再导入"), {code: "IMPORT_PLAN_STALE"});@@ -82,7 +83,7 @@ export function claimLibraryImportTransaction(stateValue, request = {}, options};}- assertLibraryImportPlanCurrent(planToken, request.stateValue, request.sourceValue);+ assertLibraryImportPlanCurrent(planToken, request.stateValue, request.sourceValue, request.planValue);const receipt = normalizeLibraryImportTransaction({operationId,diff --git a/library-package.js b/library-package.jsindex c1d785b..69a8302 100644--- a/library-package.js+++ b/library-package.js@@ -6,7 +6,8 @@ import {collectionSubtreeIds,createDefaultOrganizerState,mergeOrganizerStateWithMap,- normalizeOrganizerState+ normalizeOrganizerState,+ removeEntriesFromOrganizer} from "./organizer.js";import { normalizeComposerSessions, normalizeComposerSettings } from "./composer.js";import { normalizeCreativeExperimentSettings, normalizeCreativeRuns } from "./creative-runs.js";@@ -14,7 +15,7 @@ import { mergeCreativeSkillsState, normalizeCreativeSkillsState } from "./creatiimport { formatBytes, portableLibraryLimits } from "./resource-limits.js";import { normalizeEntryVisuals } from "./visuals.js";import { normalizeEntryMedia, removeEntryMedia } from "./media.js";-import { expandLogicalCaseIds, normalizeCompoundCases } from "./compound-cases.js";+import { expandLogicalCaseIds, normalizeCompoundCases, removeEntriesFromCompoundCases } from "./compound-cases.js";import { prepareLibraryPackageDraft } from "./library-package-migrations.js";import { remapArticleDocumentAssets } from "./article-document.js";import { caseSemanticFingerprint } from "./library-semantic-identity.js";@@ -23,11 +24,17 @@ import { boundedMediaBlobFromResponse, isSupportedDocumentMimeType } from "./bouimport {assetFormatForExtension,fileExtension,- isReportedMimeCompatible+ isReportedMimeCompatible,+ portableAssetDirectory} from "./asset-formats.js";const AI_ASSIGNMENT_SOURCES = new Set(["deepseek_text", "local_image_review", "vision_model"]);+export function hasLibrarySalvageDiagnostics(diagnosticsValue) {+ return (Array.isArray(diagnosticsValue) ? diagnosticsValue : [])+ .some((item) => item?.action === "dropped" || item?.action === "skipped");+}+export async function parseCompleteFolderBackup(value, files = new Map(), limitsValue = {}) {const preparedFiles = new Map(files);const limits = portableLibraryLimits(limitsValue);@@ -50,7 +57,14 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})const salvageInvalidMedia = limitsValue?.salvageInvalidMedia === true;const prepared = prepareLibraryPackageDraft(value);const importDiagnostics = [...prepared.diagnostics];- const importStats = { ...prepared.stats, droppedMediaFiles: 0 };+ const importStats = {+ ...prepared.stats,+ droppedMediaFiles: 0,+ droppedTrashMedia: 0,+ droppedTemporaryAssets: 0,+ droppedCreativeOutputs: 0,+ droppedSkillFiles: 0+ };const packageVersion = prepared.sourceVersion;value = prepared.draft;if (value.entries.length > limits.maxEntries) {@@ -86,13 +100,27 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})}}}- data.entries = data.entries.map((entry) => {+ const normalizationDroppedAssetIds = new Map();+ data.entries = data.entries.map((entry, entryIndex) => {const normalized = normalizeEntryVisuals(entry);if (packageVersion >= 4) {const normalizedIds = new Set(normalized.mediaAssets.map((asset) => asset.id));- const missingAsset = (Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : [])- .find((asset) => asset?.storageMode !== "reference" && clean(asset?.id) && !normalizedIds.has(clean(asset.id)));- if (missingAsset) throw new Error("案例包包含无法安全规范化的媒体描述");+ const missingAssets = (Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : [])+ .filter((asset) => asset?.storageMode !== "reference" && clean(asset?.id) && !normalizedIds.has(clean(asset.id)));+ if (missingAssets.length && !salvageInvalidMedia) throw new Error("案例包包含无法安全规范化的媒体描述");+ if (missingAssets.length) {+ const droppedIds = missingAssets.map((asset) => clean(asset.id));+ normalizationDroppedAssetIds.set(entryIndex, droppedIds);+ importStats.droppedMediaDescriptors += droppedIds.length;+ importDiagnostics.push(...droppedIds.map((assetId) => ({+ code: "media_descriptor_dropped",+ severity: "media",+ action: "dropped",+ entryId: clean(entry?.id),+ assetId,+ reason: "invalid_descriptor"+ })));+ }}normalized.customLabels = uniqueNames(entry?.customLabels);normalized.metadataLabels = uniqueNames(entry?.metadataLabels);@@ -105,7 +133,7 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})ids.add(id);entry.id = id;const entryAssets = new Map();- const droppedAssetIds = [];+ const droppedAssetIds = [...(normalizationDroppedAssetIds.get(entryIndex) ?? [])];for (const asset of entry.mediaAssets) {if (visualIds.has(asset.id)) throw new Error("案例包包含重复的媒体编号");visualIds.add(asset.id);@@ -193,9 +221,13 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})}data.compoundCases = normalizeCompoundCases(data.compoundCases, data.entries);data.trashState = normalizeTrashState(data.trashState);+ const retainedTrashItems = [];for (const item of data.trashState.items) {- if (item.kind !== "entry" && item.kind !== "media") continue;- const entry = item.kind === "entry"+ if (item.kind !== "entry" && item.kind !== "media") {+ retainedTrashItems.push(item);+ continue;+ }+ let entry = item.kind === "entry"? normalizeEntryMedia(item.snapshot): normalizeEntryMedia({id: clean(item.relationships?.entryId) || `trash-media:${item.targetId}`,@@ -203,6 +235,43 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})mediaAssets: item.snapshot?.mediaAssets ?? [],primaryMediaId: ""});+ const droppedAssetIds = [];+ for (const asset of entry.mediaAssets) {+ if (visualIds.has(asset.id)) {+ if (!salvageInvalidMedia) throw new Error("完整备份包含重复的媒体编号");+ droppedAssetIds.push(asset.id);+ importStats.droppedTrashMedia += 1;+ importDiagnostics.push(trashMediaDiagnostic(item, asset, "duplicate_asset_id"));+ continue;+ }+ visualIds.add(asset.id);+ if (asset.storageMode === "reference") continue;+ const path = clean(asset.assetPath);+ let format;+ try {+ format = validatePortableMediaDescriptor(asset, path, packageVersion);+ } catch (error) {+ if (!salvageInvalidMedia) throw error;+ droppedAssetIds.push(asset.id);+ importStats.droppedMediaDescriptors += 1;+ importStats.droppedTrashMedia += 1;+ importDiagnostics.push(trashMediaDiagnostic(item, asset, "invalid_descriptor"));+ continue;+ }+ const blob = files.get(path);+ const failure = portableMediaFileFailure(entry, asset, blob, format, packageVersion, limits, skipMediaByteValidation);+ if (failure) {+ if (!salvageInvalidMedia) throw new Error(`回收站中的“${entry.title || "未命名案例"}”${failure.message}`);+ droppedAssetIds.push(asset.id);+ importStats.droppedMediaFiles += 1;+ importStats.droppedTrashMedia += 1;+ importDiagnostics.push(trashMediaDiagnostic(item, asset, failure.reason));+ continue;+ }+ assets.set(asset.id, blob);+ if (asset.kind === "image") images.set(asset.id, blob);+ }+ for (const assetId of droppedAssetIds) entry = removeEntryMedia(entry, assetId);const trashMediaIds = new Set(entry.mediaAssets.map((asset) => asset.id));if (item.kind === "entry") {entry.facetAssignments = dropDanglingAiAssignments(entry.facetAssignments, {@@ -213,7 +282,29 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})importDiagnostics,importStats});+ if (salvageInvalidMedia && !hasRecoverableCaseContent(entry)) {+ importDiagnostics.push({+ code: "trash_item_skipped",+ severity: "trash",+ action: "skipped",+ targetId: item.targetId,+ reason: "no_usable_content"+ });+ continue;+ }+ item.snapshot = entry;} else {+ if (salvageInvalidMedia && !trashMediaIds.has(item.targetId)) {+ importDiagnostics.push({+ code: "trash_item_skipped",+ severity: "trash",+ action: "skipped",+ targetId: item.targetId,+ reason: "missing_target_media"+ });+ continue;+ }+ item.snapshot.mediaAssets = entry.mediaAssets;item.snapshot.facetAssignments = dropDanglingAiAssignments(item.snapshot?.facetAssignments, {facetIds: packageFacetIds,nodeIds: packageNodeIds,@@ -222,6 +313,11 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})importDiagnostics,importStats});+ item.relationships.positions = (item.relationships?.positions ?? [])+ .filter((position) => trashMediaIds.has(clean(position?.id)));+ item.relationships.primaryMediaId = trashMediaIds.has(clean(item.relationships?.primaryMediaId))+ ? item.relationships.primaryMediaId+ : "";item.relationships.facetAssignments = dropDanglingAiAssignments(item.relationships?.facetAssignments, {facetIds: packageFacetIds,nodeIds: packageNodeIds,@@ -231,100 +327,154 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})importStats});}- for (const asset of entry.mediaAssets) {- if (visualIds.has(asset.id)) throw new Error("完整备份包含重复的媒体编号");- visualIds.add(asset.id);- if (asset.storageMode === "reference") continue;- const path = clean(asset.assetPath);- const format = validatePortableMediaDescriptor(asset, path, packageVersion);- const blob = files.get(path);- if (!(blob instanceof Blob) || !blobMatchesKind(blob, asset, format, packageVersion)) {- throw new Error(`回收站中的“${entry.title || "未命名案例"}”缺少媒体文件或类型不符`);- }- if (asset.kind === "image" && blob.size > limits.maxImageBytes) {- throw new Error(`回收站中的图片超过 ${formatBytes(limits.maxImageBytes)} 上限`);- }- if (asset.kind !== "image" && blob.size > limits.maxFileBytes) {- throw new Error(`回收站中的媒体超过 ${formatBytes(limits.maxFileBytes)} 上限`);- }- if (!skipMediaByteValidation && packageVersion >= 3 && asset.byteSize && asset.byteSize !== blob.size) {- throw new Error(`回收站中的媒体大小校验失败:${path}`);- }- assets.set(asset.id, blob);- if (asset.kind === "image") images.set(asset.id, blob);- }- if (item.kind === "entry") item.snapshot = entry;- else item.snapshot.mediaAssets = entry.mediaAssets;+ retainedTrashItems.push(item);}+ data.trashState = normalizeTrashState({ ...data.trashState, items: retainedTrashItems });data.organizerState = normalizeOrganizerState(data.organizerState, [...ids]);data.composerSettings = normalizeComposerSettings(data.composerSettings);data.composerSessions = normalizeComposerSessions(data.composerSessions);for (const session of data.composerSessions) {for (const reference of session.referenceSnapshots) {if (reference.sourceType !== "temporary") continue;+ const retainedAssetRefs = [];+ const droppedAssetIds = new Set();for (const asset of reference.assetRefs) {const path = clean(asset.archivePath);- if (!validTemporaryAssetPath(path)) throw new Error(`临时附件路径无效:${asset.name || asset.assetId}`);+ if (!validTemporaryAssetPath(path)) {+ if (!salvageInvalidMedia) throw new Error(`临时附件路径无效:${asset.name || asset.assetId}`);+ droppedAssetIds.add(asset.assetId);+ importStats.droppedTemporaryAssets += 1;+ importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "invalid_descriptor"));+ continue;+ }const blob = files.get(path);if (!(blob instanceof Blob) || !blobMatchesKind(blob, asset.kind)) {- throw new Error(`临时附件缺失或类型不符:${asset.name || asset.assetId}`);+ if (!salvageInvalidMedia) throw new Error(`临时附件缺失或类型不符:${asset.name || asset.assetId}`);+ droppedAssetIds.add(asset.assetId);+ importStats.droppedMediaFiles += 1;+ importStats.droppedTemporaryAssets += 1;+ importDiagnostics.push(privateResourceDiagnostic(+ "temporary_asset_dropped", asset, path, blob instanceof Blob ? "type_mismatch" : "missing_file"+ ));+ continue;}if (blob.size > limits.maxFileBytes) {- throw new Error(`临时附件超过 ${formatBytes(limits.maxFileBytes)} 上限:${asset.name || asset.assetId}`);+ if (!salvageInvalidMedia) throw new Error(`临时附件超过 ${formatBytes(limits.maxFileBytes)} 上限:${asset.name || asset.assetId}`);+ droppedAssetIds.add(asset.assetId);+ importStats.droppedMediaFiles += 1;+ importStats.droppedTemporaryAssets += 1;+ importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "size_limit"));+ continue;}if (!skipMediaByteValidation && asset.byteSize && asset.byteSize !== blob.size) {- throw new Error(`临时附件大小校验失败:${asset.name || asset.assetId}`);+ if (!salvageInvalidMedia) throw new Error(`临时附件大小校验失败:${asset.name || asset.assetId}`);+ droppedAssetIds.add(asset.assetId);+ importStats.droppedMediaFiles += 1;+ importStats.droppedTemporaryAssets += 1;+ importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "byte_size_mismatch"));+ continue;}const existing = assets.get(asset.assetId);- if (existing && existing.size !== blob.size) throw new Error("案例包包含冲突的临时附件编号");- if (visualIds.has(asset.assetId) && !existing) throw new Error("案例包包含冲突的媒体编号");+ if ((existing && existing.size !== blob.size) || (visualIds.has(asset.assetId) && !existing)) {+ if (!salvageInvalidMedia) throw new Error("案例包包含冲突的临时附件编号");+ droppedAssetIds.add(asset.assetId);+ importStats.droppedTemporaryAssets += 1;+ importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "duplicate_asset_id"));+ continue;+ }visualIds.add(asset.assetId);assets.set(asset.assetId, blob);if (asset.kind === "image") images.set(asset.assetId, blob);+ retainedAssetRefs.push(asset);}+ reference.assetRefs = retainedAssetRefs;+ reference.imageRefs = reference.imageRefs.filter((image) => !droppedAssetIds.has(clean(image?.visualId)));}}data.creativeExperimentSettings = normalizeCreativeExperimentSettings(data.creativeExperimentSettings);data.creativeRuns = normalizeCreativeRuns(data.creativeRuns);data.creativeSkills = normalizeCreativeSkillsState(data.creativeSkills);for (const run of data.creativeRuns) {+ const retainedOutputs = [];for (const output of run.outputs) {const visual = output.visual;const path = clean(visual.assetPath || visual.screenshotPath);const video = visual.kind === "video" || String(visual.mimeType ?? "").startsWith("video/");if (!validCreativeResultPath(path, video ? "video" : "image")) {- throw new Error("创作实验包包含无效的结果媒体路径");+ if (!salvageInvalidMedia) throw new Error("创作实验包包含无效的结果媒体路径");+ importStats.droppedCreativeOutputs += 1;+ importDiagnostics.push(privateResourceDiagnostic("creative_output_dropped", visual, path, "invalid_descriptor"));+ continue;}const asset = files.get(path);if (!(asset instanceof Blob) || !blobMatchesKind(asset, video ? "video" : "image")) {- throw new Error(`创作实验包缺少结果${video ? "视频" : "图片"}`);+ if (!salvageInvalidMedia) throw new Error(`创作实验包缺少结果${video ? "视频" : "图片"}`);+ importStats.droppedMediaFiles += 1;+ importStats.droppedCreativeOutputs += 1;+ importDiagnostics.push(privateResourceDiagnostic(+ "creative_output_dropped", visual, path, asset instanceof Blob ? "type_mismatch" : "missing_file"+ ));+ continue;}if (!video && asset.size > limits.maxImageBytes) {- throw new Error(`创作结果图片超过 ${formatBytes(limits.maxImageBytes)} 上限`);+ if (!salvageInvalidMedia) throw new Error(`创作结果图片超过 ${formatBytes(limits.maxImageBytes)} 上限`);+ importStats.droppedMediaFiles += 1;+ importStats.droppedCreativeOutputs += 1;+ importDiagnostics.push(privateResourceDiagnostic("creative_output_dropped", visual, path, "size_limit"));+ continue;}const existingAsset = assets.get(visual.id);if (visualIds.has(visual.id) && existingAsset && existingAsset.size !== asset.size) {- throw new Error("案例包包含冲突的结果媒体编号");+ if (!salvageInvalidMedia) throw new Error("案例包包含冲突的结果媒体编号");+ importStats.droppedCreativeOutputs += 1;+ importDiagnostics.push(privateResourceDiagnostic("creative_output_dropped", visual, path, "duplicate_asset_id"));+ continue;}visualIds.add(visual.id);assets.set(visual.id, asset);if (!video) images.set(visual.id, asset);+ retainedOutputs.push(output);}+ run.outputs = retainedOutputs;+ const retainedVisualIds = new Set(retainedOutputs.map((output) => output.visual.id));+ run.events = run.events.filter((event) => retainedVisualIds.has(event.visualId));}for (const skill of data.creativeSkills.items) {+ const retainedFiles = [];for (const file of skill.packageFiles) {const path = clean(file.archivePath);if (!/^skills\/[A-Za-z0-9._/-]+$/i.test(path) || path.includes("..")) {- throw new Error(`外部 Skill 原包路径无效:${file.path}`);+ if (!salvageInvalidMedia) throw new Error(`外部 Skill 原包路径无效:${file.path}`);+ importStats.droppedSkillFiles += 1;+ importDiagnostics.push(privateResourceDiagnostic("skill_file_dropped", file, path, "invalid_descriptor"));+ continue;}const blob = files.get(path);- if (!(blob instanceof Blob)) throw new Error(`外部 Skill 原包文件缺失:${file.path}`);- if (blob.size > limits.maxFileBytes) throw new Error(`外部 Skill 文件超过 ${formatBytes(limits.maxFileBytes)} 上限`);+ if (!(blob instanceof Blob)) {+ if (!salvageInvalidMedia) throw new Error(`外部 Skill 原包文件缺失:${file.path}`);+ importStats.droppedMediaFiles += 1;+ importStats.droppedSkillFiles += 1;+ importDiagnostics.push(privateResourceDiagnostic("skill_file_dropped", file, path, "missing_file"));+ continue;+ }+ if (blob.size > limits.maxFileBytes) {+ if (!salvageInvalidMedia) throw new Error(`外部 Skill 文件超过 ${formatBytes(limits.maxFileBytes)} 上限`);+ importStats.droppedMediaFiles += 1;+ importStats.droppedSkillFiles += 1;+ importDiagnostics.push(privateResourceDiagnostic("skill_file_dropped", file, path, "size_limit"));+ continue;+ }if (!skipMediaByteValidation && file.byteSize && file.byteSize !== blob.size) {- throw new Error(`外部 Skill 文件大小校验失败:${file.path}`);+ if (!salvageInvalidMedia) throw new Error(`外部 Skill 文件大小校验失败:${file.path}`);+ importStats.droppedMediaFiles += 1;+ importStats.droppedSkillFiles += 1;+ importDiagnostics.push(privateResourceDiagnostic("skill_file_dropped", file, path, "byte_size_mismatch"));+ continue;}skillAssets.set(file.assetId, blob);+ retainedFiles.push(file);}+ skill.packageFiles = retainedFiles;}return {...data,@@ -450,7 +600,7 @@ function sanitizeSharedEntry(entry) {}export function mergeLibraryPackage(current = {}, importedValue = {}, options = {}) {- const priorImportEvidence = parsedImportEvidence(importedValue);+ const priorImportEvidence = importReportEvidence(options.importReport) ?? parsedImportEvidence(importedValue);const imported = parseLibraryPackage(importedValue, packageImagePlaceholders(importedValue), {skipMediaByteValidation: true});@@ -475,12 +625,23 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =compoundCases: imported.compoundCases,organizerState: imported.organizerState,composerSettings: imported.composerSettings,- composerSessions: imported.composerSessions.map(withoutComposerArchivePaths),+ composerSessions: imported.composerSessions.map((session) => remapAppliedSkillReferences(+ withoutComposerArchivePaths(session),+ skillMerge.skillIdMap,+ skillMerge.skillVersionIdMap+ )),creativeExperimentSettings: imported.creativeExperimentSettings,- creativeRuns: imported.creativeRuns.map(withoutCreativeArchivePaths),+ creativeRuns: imported.creativeRuns.map((run) => remapAppliedSkillReferences(+ withoutCreativeArchivePaths(run),+ skillMerge.skillIdMap,+ skillMerge.skillVersionIdMap+ )),creativeSkills: skillMerge.state},entryIdMap: Object.fromEntries(imported.entries.map((entry) => [entry.id, entry.id])),+ collectionIdMap: Object.fromEntries(imported.organizerState.collections.map((item) => [item.id, item.id])),+ facetIdMap: Object.fromEntries(imported.facetCatalog.facets.map((item) => [item.id, item.id])),+ nodeIdMap: Object.fromEntries(imported.facetCatalog.nodes.map((item) => [item.id, item.id])),compoundIdMap: Object.fromEntries(imported.compoundCases.map((item) => [item.id, item.id])),visualIdMap: Object.fromEntries([...imported.entries.flatMap((entry) => entry.mediaAssets.map((visual) => [visual.id, visual.id])),@@ -495,6 +656,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =...importedTrashAssets.map((asset) => [asset.id, asset.id])]),skillIdMap: skillMerge.skillIdMap,+ skillVersionIdMap: skillMerge.skillVersionIdMap,packageAssetIdMap: skillMerge.packageAssetIdMap,importedSkillCount: skillMerge.importedSkillCount,skippedSkillCount: skillMerge.skippedSkillCount,@@ -518,12 +680,13 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =next.compoundCases = normalizeCompoundCases(next.compoundCases, next.entries);const taxonomyMerge = mergeTaxonomies(next.taxonomy, imported.taxonomy);next.taxonomy = taxonomyMerge.taxonomy;- const { facetIds, nodeIds } = mergeVocabulary(next.facetCatalog, imported.facetCatalog);+ const { facetIds, nodeIds } = mergeVocabulary(next.facetCatalog, imported.facetCatalog, options);const usedEntryIds = new Set(next.entries.map((entry) => entry.id));const usedVisualIds = new Set([...next.entries.flatMap((entry) => normalizeEntryMedia(entry).mediaAssets.map((visual) => visual.id)),...normalizeCreativeRuns(next.creativeRuns).flatMap((run) => run.outputs.map((output) => output.visual.id)),- ...temporaryReferenceAssets(next.composerSessions).map((asset) => asset.assetId)+ ...temporaryReferenceAssets(next.composerSessions).map((asset) => asset.assetId),+ ...(Array.isArray(options.reservedVisualIds) ? options.reservedVisualIds : [])]);const entryIdMap = {};const visualIdMap = { ...(options.visualIdMap ?? {}) };@@ -534,11 +697,10 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =let remappedCount = 0;let skippedCount = 0;for (const source of imported.entries) {- const idCollision = usedEntryIds.has(source.id);- const sourceFingerprint = caseSemanticFingerprint(source);+ let idCollision = usedEntryIds.has(source.id);+ const sourceFingerprint = caseSemanticFingerprint(normalizeEntryMedia(source));const identical = sourceFingerprint && next.entries.find((entry) =>- (entry.id === source.id || clean(entry.importSource?.entryId) === source.id) &&- caseSemanticFingerprint(entry) === sourceFingerprint+ caseSemanticFingerprint(normalizeEntryMedia(entry)) === sourceFingerprint);if (identical) {skippedCount += 1;@@ -551,9 +713,26 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =}continue;}- if (idCollision && options.skipExistingEntryIds === true) {+ const conflictResolution = clean(options.entryConflictResolutions?.[source.id]);+ if (idCollision && conflictResolution === "use-incoming") {+ next.entries = next.entries.filter((entry) => entry.id !== source.id);+ next.organizerState = removeEntriesFromOrganizer(next.organizerState, [source.id]);+ next.compoundCases = removeEntriesFromCompoundCases(next.compoundCases, current.entries, [source.id]);+ usedEntryIds.delete(source.id);+ idCollision = false;+ }+ if (idCollision && (conflictResolution === "keep-local" || options.skipExistingEntryIds === true)) {+ const existing = next.entries.find((entry) => entry.id === source.id);skippedCount += 1;+ entryIdMap[source.id] = source.id;organizerEntryIdMap[source.id] = source.id;+ if (existing) {+ const sourceAssets = normalizeEntryMedia(source).mediaAssets;+ const existingAssets = normalizeEntryMedia(existing).mediaAssets;+ for (let index = 0; index < sourceAssets.length; index += 1) {+ if (existingAssets[index]) visualIdMap[sourceAssets[index].id] = existingAssets[index].id;+ }+ }continue;}const preferred = clean(options.entryIdMap?.[source.id]);@@ -628,7 +807,10 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =next.organizerState,imported.organizerState,organizerEntryIdMap,- options.preserveLibraryConfiguration === true ? { createdAt: importMetadata.libraryAddedAt } : {}+ {+ ...(options.preserveLibraryConfiguration === true ? { createdAt: importMetadata.libraryAddedAt } : {}),+ collectionIdMap: options.collectionIdMap+ });next.organizerState = organizerMerge.state;const usedCompoundIds = new Set([@@ -663,12 +845,16 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =visualIdMap[asset.assetId] = targetAssetId;createdVisualIdMap[asset.assetId] = targetAssetId;}+ const skillMerge = mergeCreativeSkillsState(next.creativeSkills, imported.creativeSkills, options);+ next.creativeSkills = skillMerge.state;const composerMerge = mergeComposerSessions(next.composerSessions,imported.composerSessions,organizerEntryIdMap,options.sessionIdMap,- visualIdMap+ visualIdMap,+ skillMerge.skillIdMap,+ skillMerge.skillVersionIdMap);next.composerSessions = composerMerge.sessions;next.creativeExperimentSettings = normalizeCreativeExperimentSettings(@@ -680,7 +866,9 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =composerMerge.sessionIdMap,usedVisualIds,visualIdMap,- options.runIdMap+ options.runIdMap,+ skillMerge.skillIdMap,+ skillMerge.skillVersionIdMap);next.creativeRuns = creativeMerge.runs;for (const run of imported.creativeRuns) {@@ -689,8 +877,6 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =if (visualIdMap[sourceId]) createdVisualIdMap[sourceId] = visualIdMap[sourceId];}}- const skillMerge = mergeCreativeSkillsState(next.creativeSkills, imported.creativeSkills, options);- next.creativeSkills = skillMerge.state;const trashMerge = mergeImportedTrashState(next.trashState, imported.trashState, {activeEntryIds: next.entries.map((entry) => entry.id),activeCollectionIds: next.organizerState.collections.map((collection) => collection.id),@@ -700,7 +886,11 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =],activeVisualIds: [...usedVisualIds],entryIdMap: organizerEntryIdMap,- collectionIdMap: organizerMerge.collectionIdMap+ collectionIdMap: organizerMerge.collectionIdMap,+ preferredEntryIdMap: options.trashEntryIdMap,+ preferredCollectionIdMap: options.trashCollectionIdMap,+ preferredCompoundIdMap: options.trashCompoundIdMap,+ preferredVisualIdMap: options.visualIdMap});next.trashState = trashMerge.trashState;Object.assign(visualIdMap, trashMerge.visualIdMap);@@ -708,12 +898,16 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =return {state: next,entryIdMap,+ collectionIdMap: organizerMerge.collectionIdMap,+ facetIdMap: Object.fromEntries(facetIds),+ nodeIdMap: Object.fromEntries(nodeIds),visualIdMap,createdVisualIdMap,sessionIdMap: composerMerge.sessionIdMap,runIdMap: creativeMerge.runIdMap,compoundIdMap,skillIdMap: skillMerge.skillIdMap,+ skillVersionIdMap: skillMerge.skillVersionIdMap,packageAssetIdMap: skillMerge.packageAssetIdMap,importedSkillCount: skillMerge.importedSkillCount,skippedSkillCount: skillMerge.skippedSkillCount,@@ -725,6 +919,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =importStats: imported.importStats,trashEntryIdMap: trashMerge.entryIdMap,trashCollectionIdMap: trashMerge.collectionIdMap,+ trashCompoundIdMap: trashMerge.compoundIdMap,remappedCount,skippedCount};@@ -745,7 +940,15 @@ function withLocalImportMetadata(entry, metadata) {return { ...entry, ...metadata };}-function mergeComposerSessions(currentValue, importedValue, entryIdMap, preferredIds = {}, visualIdMap = {}) {+function mergeComposerSessions(+ currentValue,+ importedValue,+ entryIdMap,+ preferredIds = {},+ visualIdMap = {},+ skillIdMap = {},+ skillVersionIdMap = {}+) {const current = normalizeComposerSessions(currentValue);const used = new Set(current.map((item) => item.id));const sessionIdMap = {};@@ -767,12 +970,21 @@ function mergeComposerSessions(currentValue, importedValue, entryIdMap, preferreassetId: visualIdMap[asset.assetId] ?? asset.assetId}))}));- return next;+ return remapAppliedSkillReferences(next, skillIdMap, skillVersionIdMap);});return { sessions: [...current, ...imported], sessionIdMap };}-function mergeCreativeRuns(currentValue, importedValue, sessionIdMap, usedVisualIds, visualIdMap, preferredRunIds = {}) {+function mergeCreativeRuns(+ currentValue,+ importedValue,+ sessionIdMap,+ usedVisualIds,+ visualIdMap,+ preferredRunIds = {},+ skillIdMap = {},+ skillVersionIdMap = {}+) {const current = normalizeCreativeRuns(currentValue);const usedRunIds = new Set(current.map((item) => item.id));const runIdMap = {};@@ -798,12 +1010,23 @@ function mergeCreativeRuns(currentValue, importedValue, sessionIdMap, usedVisual}return { ...output, visual: { ...output.visual, id: targetVisualId } };});- return run;+ return remapAppliedSkillReferences(run, skillIdMap, skillVersionIdMap);});return { runs: normalizeCreativeRuns([...current, ...imported]), runIdMap };}-function mergeVocabulary(target, sourceValue) {+function remapAppliedSkillReferences(value, skillIdMap = {}, skillVersionIdMap = {}) {+ return {+ ...value,+ appliedSkills: (Array.isArray(value?.appliedSkills) ? value.appliedSkills : []).map((skill) => ({+ ...skill,+ skillId: skillIdMap[skill.skillId] ?? skill.skillId,+ versionId: skillVersionIdMap[skill.versionId] ?? skill.versionId+ }))+ };+}++function mergeVocabulary(target, sourceValue, options = {}) {const source = normalizeFacetCatalog(sourceValue);const facetIds = new Map();const nodeIds = new Map();@@ -815,7 +1038,11 @@ function mergeVocabulary(target, sourceValue) {facetIds.set(facet.id, existing.id);continue;}- const id = target.facets.some((item) => item.id === facet.id) ? uniqueId("facet", new Set(target.facets.map((item) => item.id))) : facet.id;+ const usedFacetIds = new Set(target.facets.map((item) => item.id));+ const preferredId = clean(options.facetIdMap?.[facet.id]);+ const id = usedFacetIds.has(facet.id)+ ? preferredId && !usedFacetIds.has(preferredId) ? preferredId : uniqueId("facet", usedFacetIds)+ : facet.id;target.facets.push({ ...facet, id, order: target.facets.length });facetIds.set(facet.id, id);}@@ -831,7 +1058,11 @@ function mergeVocabulary(target, sourceValue) {nodeIds.set(node.id, existing.id);continue;}- const id = target.nodes.some((item) => item.id === node.id) ? uniqueId("tag", new Set(target.nodes.map((item) => item.id))) : node.id;+ const usedNodeIds = new Set(target.nodes.map((item) => item.id));+ const preferredId = clean(options.nodeIdMap?.[node.id]);+ const id = usedNodeIds.has(node.id)+ ? preferredId && !usedNodeIds.has(preferredId) ? preferredId : uniqueId("tag", usedNodeIds)+ : node.id;target.nodes.push({ ...node, id, facetId, parentId, order: target.nodes.length });nodeIds.set(node.id, id);}@@ -863,26 +1094,38 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {}}const collectionIdMap = { ...(context.collectionIdMap ?? {}) };+ const preferredCollectionIdMap = context.preferredCollectionIdMap ?? {};for (const item of imported.items.filter((candidate) => candidate.kind === "collection")) {const sourceId = item.targetId;- const targetId = usedCollectionIds.has(sourceId) ? uniqueId("collection", usedCollectionIds) : sourceId;+ const preferredId = clean(preferredCollectionIdMap[sourceId]);+ const targetId = usedCollectionIds.has(sourceId)+ ? preferredId && !usedCollectionIds.has(preferredId) ? preferredId : uniqueId("collection", usedCollectionIds)+ : sourceId;usedCollectionIds.add(targetId);collectionIdMap[sourceId] = targetId;}const entryIdMap = { ...(context.entryIdMap ?? {}) };+ const preferredEntryIdMap = context.preferredEntryIdMap ?? {};for (const item of imported.items.filter((candidate) => candidate.kind === "entry")) {const sourceId = item.targetId;- const targetId = usedEntryIds.has(sourceId) ? uniqueId("entry", usedEntryIds) : sourceId;+ const preferredId = clean(preferredEntryIdMap[sourceId]);+ const targetId = usedEntryIds.has(sourceId)+ ? preferredId && !usedEntryIds.has(preferredId) ? preferredId : uniqueId("entry", usedEntryIds)+ : sourceId;usedEntryIds.add(targetId);entryIdMap[sourceId] = targetId;}const compoundIds = new Set(context.activeCompoundIds ?? []);const compoundIdMap = {};+ const preferredCompoundIdMap = context.preferredCompoundIdMap ?? {};for (const item of imported.items) {for (const compound of item.relationships?.compoundCases ?? []) {const sourceId = clean(compound?.id);if (!sourceId || compoundIdMap[sourceId]) continue;- const targetId = compoundIds.has(sourceId) ? uniqueId("compound", compoundIds) : sourceId;+ const preferredId = clean(preferredCompoundIdMap[sourceId]);+ const targetId = compoundIds.has(sourceId)+ ? preferredId && !compoundIds.has(preferredId) ? preferredId : uniqueId("compound", compoundIds)+ : sourceId;compoundIds.add(targetId);compoundIdMap[sourceId] = targetId;}@@ -901,7 +1144,7 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {}if (item.kind === "entry") {const targetId = entryIdMap[item.targetId];- const remapped = remapTrashedEntrySnapshot(item.snapshot, targetId, usedVisualIds);+ const remapped = remapTrashedEntrySnapshot(item.snapshot, targetId, usedVisualIds, context.preferredVisualIdMap);Object.assign(visualIdMap, remapped.visualIdMap);item.targetId = targetId;item.id = `trash:entry:${targetId}`;@@ -923,7 +1166,7 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {id: parentEntryId || `trash-media:${item.targetId}`,mediaAssets: item.snapshot?.mediaAssets ?? [],primaryMediaId: ""- }, parentEntryId || `trash-media:${item.targetId}`, usedVisualIds);+ }, parentEntryId || `trash-media:${item.targetId}`, usedVisualIds, context.preferredVisualIdMap);Object.assign(visualIdMap, remapped.visualIdMap);const targetId = remapped.visualIdMap[item.targetId] ?? item.targetId;item.targetId = targetId;@@ -941,16 +1184,20 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {trashState: normalizeTrashState({ items: [...current.items, ...moved] }),entryIdMap: Object.fromEntries(imported.items.filter((item) => item.kind === "entry").map((item) => [item.targetId, entryIdMap[item.targetId]])),collectionIdMap,+ compoundIdMap,visualIdMap};}-function remapTrashedEntrySnapshot(entryValue, targetEntryId, usedVisualIds) {+function remapTrashedEntrySnapshot(entryValue, targetEntryId, usedVisualIds, preferredVisualIdMap = {}) {const entry = normalizeEntryMedia(entryValue);const visualIdMap = {};entry.mediaAssets = entry.mediaAssets.map((asset) => {const preferredId = asset.id === entry.id && targetEntryId !== entry.id ? targetEntryId : asset.id;- const targetId = usedVisualIds.has(preferredId) ? uniqueId("visual", usedVisualIds) : preferredId;+ const plannedId = clean(preferredVisualIdMap[asset.id]);+ const targetId = usedVisualIds.has(preferredId)+ ? plannedId && !usedVisualIds.has(plannedId) ? plannedId : uniqueId("visual", usedVisualIds)+ : preferredId;usedVisualIds.add(targetId);visualIdMap[asset.id] = targetId;return { ...asset, id: targetId };@@ -1096,10 +1343,13 @@ function validatePortableMediaDescriptor(asset, path, packageVersion) {function validMediaPath(path, kind, packageVersion = 4) {if (!path || path.includes("..")) return false;const safeFile = "[A-Za-z0-9._/-]+\\.[A-Za-z0-9]+";- const directories = packageVersion >= 4- ? { image: "images", video: "videos", audio: "audio", document: "documents", attachment: "attachments" }- : { image: "images", video: "videos", document: "documents" };- const directory = directories[kind];+ let directory;+ if (packageVersion >= 4) {+ try { directory = portableAssetDirectory(kind); }+ catch { return false; }+ } else {+ directory = { image: "images", video: "videos", document: "documents" }[kind];+ }if (!directory || !(new RegExp(`^${directory}\\/${safeFile}$`, "i")).test(path)) return false;if (packageVersion >= 4) return true;if (kind === "image") return /\.(?:png|jpe?g|webp)$/i.test(path);@@ -1109,8 +1359,12 @@ function validMediaPath(path, kind, packageVersion = 4) {function validCreativeResultPath(path, kind) {if (!path || path.includes("..")) return false;- if (kind === "video") return /^creative-results\/[A-Za-z0-9._/-]+\.(?:mp4|webm|mov)$/i.test(path);- return /^(?:images|creative-results)\/[A-Za-z0-9._/-]+\.(?:png|jpe?g|webp)$/i.test(path);+ const validPath = kind === "video"+ ? /^creative-results\/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+$/i.test(path)+ : /^(?:images|creative-results)\/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+$/i.test(path);+ if (!validPath) return false;+ const format = assetFormatForExtension(fileExtension(path));+ return format?.kind === kind;}function portableMediaFileFailure(entry, asset, blob, format, packageVersion, limits, skipMediaByteValidation) {@@ -1189,6 +1443,29 @@ function completeBackupDocumentPaths(value = {}) {return paths;}+function trashMediaDiagnostic(item, asset, reason) {+ return {+ code: "trash_media_dropped",+ severity: "trash",+ action: "dropped",+ targetId: clean(item?.targetId),+ assetId: clean(asset?.id),+ path: clean(asset?.assetPath),+ reason+ };+}++function privateResourceDiagnostic(code, value, path, reason) {+ return {+ code,+ severity: "media",+ action: "dropped",+ assetId: clean(value?.assetId || value?.id),+ path: clean(path),+ reason+ };+}+function hasRecoverableCaseContent(entry = {}) {if ([entry.title, entry.text, entry.note, entry.url].some((value) => clean(value))) return true;if ((entry.mediaAssets ?? []).some((asset) => asset && typeof asset === "object")) return true;@@ -1224,6 +1501,14 @@ function parsedImportEvidence(value) {};}+function importReportEvidence(value) {+ if (!Array.isArray(value?.diagnostics) || !value?.stats || typeof value.stats !== "object") return null;+ return {+ diagnostics: structuredClone(value.diagnostics),+ stats: structuredClone(value.stats)+ };+}+function mergeImportDiagnostics(previous, current) {const result = [];const seen = new Set();@@ -1239,7 +1524,15 @@ function mergeImportDiagnostics(previous, current) {function mergeImportStats(previous, current) {const dropped = {};- for (const key of ["droppedAiAssignments", "droppedMediaDescriptors", "droppedMediaFiles"]) {+ for (const key of [+ "droppedAiAssignments",+ "droppedMediaDescriptors",+ "droppedMediaFiles",+ "droppedTrashMedia",+ "droppedTemporaryAssets",+ "droppedCreativeOutputs",+ "droppedSkillFiles"+ ]) {dropped[key] = nonNegativeStat(previous?.[key]) + nonNegativeStat(current?.[key]);}return {diff --git a/library-recovery-point.js b/library-recovery-point.jsnew file mode 100644index 0000000..7738e2a--- /dev/null+++ b/library-recovery-point.js@@ -0,0 +1,74 @@+const RECOVERY_POINT_VERSION = 1;++export function createLibraryReplacementRecoveryPoint(stateValue, options = {}) {+ const state = cloneManagedState(stateValue);+ const createdAt = isoString(options.createdAt) || new Date().toISOString();+ const id = clean(options.id) || `library-recovery:${globalThis.crypto.randomUUID()}`;+ return {+ version: RECOVERY_POINT_VERSION,+ id,+ createdAt,+ state,+ retainedAssetIds: uniqueIds(options.retainedAssetIds)+ };+}++export function normalizeLibraryReplacementRecoveryPoint(value) {+ if (Number(value?.version) !== RECOVERY_POINT_VERSION) return null;+ const id = clean(value?.id);+ const createdAt = isoString(value?.createdAt);+ if (!id || !createdAt || !isManagedState(value?.state)) return null;+ return {+ version: RECOVERY_POINT_VERSION,+ id,+ createdAt,+ state: cloneManagedState(value.state),+ retainedAssetIds: uniqueIds(value.retainedAssetIds)+ };+}++export function swapLibraryReplacementRecoveryPoint(currentStateValue, pointValue, options = {}) {+ const point = normalizeLibraryReplacementRecoveryPoint(pointValue);+ if (!point) throw new Error("没有可用的资料库回退点");+ return {+ targetState: cloneManagedState(point.state),+ recoveryPoint: createLibraryReplacementRecoveryPoint(currentStateValue, {+ id: options.id,+ createdAt: options.createdAt,+ retainedAssetIds: options.retainedAssetIds+ })+ };+}++export function obsoleteRecoveryAssetIds(previousPointValue, retainedStateAssetIdsValue, nextPointValue) {+ const previous = normalizeLibraryReplacementRecoveryPoint(previousPointValue);+ if (!previous) return [];+ const retained = new Set([+ ...uniqueIds(retainedStateAssetIdsValue),+ ...uniqueIds(normalizeLibraryReplacementRecoveryPoint(nextPointValue)?.retainedAssetIds)+ ]);+ return previous.retainedAssetIds.filter((assetId) => !retained.has(assetId));+}++function cloneManagedState(value) {+ if (!isManagedState(value)) throw new Error("资料库回退点缺少有效状态");+ return structuredClone(value);+}++function isManagedState(value) {+ return Boolean(value && typeof value === "object" && Array.isArray(value.entries));+}++function uniqueIds(values) {+ return [...new Set((Array.isArray(values) ? values : [])+ .map(clean).filter(Boolean))].sort();+}++function clean(value) {+ return String(value ?? "").trim();+}++function isoString(value) {+ const timestamp = Date.parse(String(value ?? "").trim());+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : "";+}diff --git a/library-semantic-identity.js b/library-semantic-identity.jsindex 6008f55..00bba71 100644--- a/library-semantic-identity.js+++ b/library-semantic-identity.js@@ -21,6 +21,108 @@ export function caseSemanticFingerprint(entryValue = {}) {return stableJson(withoutReceiverLocalFields(entry));}+export function reconcileLibrarySemanticIdentity(stateValue = {}) {+ const state = stateValue && typeof stateValue === "object" ? structuredClone(stateValue) : {};+ const entries = Array.isArray(state.entries) ? state.entries : [];+ const groups = new Map();+ for (const entry of entries) {+ const fingerprint = caseSemanticFingerprint(entry);+ if (!fingerprint) continue;+ const group = groups.get(fingerprint) ?? [];+ group.push(entry);+ groups.set(fingerprint, group);+ }++ const entryIdMap = new Map();+ const assetIdMap = new Map();+ for (const group of groups.values()) {+ if (group.length < 2) continue;+ const ordered = group.toSorted((left, right) => compareStableIds(left?.id, right?.id));+ const canonical = ordered[0];+ for (const duplicate of ordered.slice(1)) {+ const duplicateId = clean(duplicate?.id);+ const canonicalId = clean(canonical?.id);+ if (!duplicateId || !canonicalId || duplicateId === canonicalId) continue;+ entryIdMap.set(duplicateId, canonicalId);+ const canonicalAssets = Array.isArray(canonical.mediaAssets) ? canonical.mediaAssets : [];+ const duplicateAssets = Array.isArray(duplicate.mediaAssets) ? duplicate.mediaAssets : [];+ for (const [index, duplicateAsset] of duplicateAssets.entries()) {+ const duplicateAssetId = clean(duplicateAsset?.id);+ const canonicalAssetId = clean(canonicalAssets[index]?.id);+ if (duplicateAssetId && canonicalAssetId && duplicateAssetId !== canonicalAssetId) {+ assetIdMap.set(duplicateAssetId, canonicalAssetId);+ }+ }+ }+ }++ if (!entryIdMap.size) {+ return { state, changed: false, entryIdMap: {}, assetIdMap: {} };+ }++ state.entries = entries+ .filter((entry) => !entryIdMap.has(clean(entry?.id)))+ .sort((left, right) => compareStableIds(left?.id, right?.id));+ const remapped = remapLibraryReferences(state, entryIdMap, assetIdMap);+ if (Array.isArray(remapped.compoundCases)) {+ remapped.compoundCases = remapped.compoundCases.filter((compound) =>+ new Set(Array.isArray(compound?.memberEntryIds) ? compound.memberEntryIds : []).size >= 2+ );+ }+ return {+ state: remapped,+ changed: true,+ entryIdMap: Object.fromEntries(entryIdMap),+ assetIdMap: Object.fromEntries(assetIdMap)+ };+}++const ENTRY_ID_FIELDS = new Set(["entryId", "parentEntryId", "sourceEntryId", "targetEntryId"]);+const ENTRY_ID_LIST_FIELDS = new Set([+ "entryIds", "memberEntryIds", "sourceEntryIds", "excludedEntryIds", "screenshotEntryIds", "tempReferenceIds"+]);+const ASSET_ID_FIELDS = new Set([+ "assetId", "posterAssetId", "derivedFromAssetId", "coverVisualId", "primaryMediaId", "primaryVisualId", "visualId", "frameAssetId"+]);+const ASSET_ID_LIST_FIELDS = new Set(["assetIds", "mediaIds", "visualIds"]);++function remapLibraryReferences(value, entryIdMap, assetIdMap, parentKey = "") {+ if (Array.isArray(value)) {+ const remapped = value.map((item) => remapLibraryReferences(item, entryIdMap, assetIdMap, parentKey));+ if (ENTRY_ID_LIST_FIELDS.has(parentKey) || ASSET_ID_LIST_FIELDS.has(parentKey)) {+ return [...new Set(remapped)];+ }+ return remapped;+ }+ if (!value || typeof value !== "object") {+ if (typeof value !== "string") return value;+ if (parentKey === "referenceId") return remapReferenceId(value, entryIdMap, assetIdMap);+ if (ENTRY_ID_FIELDS.has(parentKey) || ENTRY_ID_LIST_FIELDS.has(parentKey)) return entryIdMap.get(value) ?? value;+ if (ASSET_ID_FIELDS.has(parentKey) || ASSET_ID_LIST_FIELDS.has(parentKey)) return assetIdMap.get(value) ?? value;+ return value;+ }+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [+ key,+ remapLibraryReferences(item, entryIdMap, assetIdMap, key)+ ]));+}++function remapReferenceId(value, entryIdMap, assetIdMap) {+ let result = value;+ for (const [sourceId, targetId] of entryIdMap) {+ if (result === sourceId) return targetId;+ if (result.startsWith(`${sourceId}:`)) {+ result = `${targetId}:${result.slice(sourceId.length + 1)}`;+ break;+ }+ }+ for (const [sourceId, targetId] of assetIdMap) {+ if (result === sourceId) return targetId;+ if (result.endsWith(`:${sourceId}`)) return `${result.slice(0, -sourceId.length)}${targetId}`;+ }+ return result;+}+function canonicalizeReceiverIds(entryValue) {const entry = entryValue && typeof entryValue === "object" ? structuredClone(entryValue) : {};const replacements = new Map();@@ -56,6 +158,12 @@ function stableJson(value) {return JSON.stringify(value);}+function compareStableIds(leftValue, rightValue) {+ const left = clean(leftValue);+ const right = clean(rightValue);+ return left < right ? -1 : left > right ? 1 : 0;+}+function clean(value) {return String(value ?? "").trim();}diff --git a/library-transfer.js b/library-transfer.jsnew file mode 100644index 0000000..1379cc0--- /dev/null+++ b/library-transfer.js@@ -0,0 +1,357 @@+import {+ hasLibrarySalvageDiagnostics,+ mergeLibraryPackage,+ parseCompleteFolderBackup,+ parseLibraryPackage+} from "./library-package.js";+import { filesWithoutInvalidLibraryImages, findInvalidImportedImageIds } from "./library-import-media.js";+import { createLibraryImportPlanToken } from "./library-import-transaction.js";+import { caseSemanticFingerprint } from "./library-semantic-identity.js";+import { libraryStoredAssetIds } from "./library-asset-inventory.js";++export const LIBRARY_TRANSFER_SOURCES = Object.freeze({+ SHARE_PACKAGE: "share-package",+ COMPLETE_BACKUP: "complete-backup",+ RESCUE_BACKUP: "rescue-backup"+});++export const LIBRARY_TRANSFER_MODES = Object.freeze({+ SAFE_MERGE: "safe-merge",+ EXACT_REPLACE: "exact-replace"+});++const SOURCE_TYPES = new Set(Object.values(LIBRARY_TRANSFER_SOURCES));++export async function inspectLibraryTransfer({+ sourceType,+ library,+ files = new Map(),+ limits = {},+ validateImage,+ sourceReport+} = {}) {+ if (!SOURCE_TYPES.has(sourceType)) throw new Error("资料检查缺少有效来源类型");+ if (!(files instanceof Map)) throw new Error("资料检查缺少有效资源清单");++ const strict = sourceType === LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP;+ const sourceDiagnostics = Array.isArray(sourceReport?.diagnostics)+ ? structuredClone(sourceReport.diagnostics)+ : [];+ let effectiveSourceType = sourceType;+ let inspected;+ if (strict) {+ try {+ inspected = await parseCompleteFolderBackup(library, files, limits);+ } catch (error) {+ let rescued;+ try {+ rescued = parseLibraryPackage(library, files, { ...limits, salvageInvalidMedia: true });+ } catch {+ throw error;+ }+ if (!hasLibrarySalvageDiagnostics(rescued.importDiagnostics)) throw error;+ inspected = rescued;+ effectiveSourceType = LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP;+ sourceDiagnostics.push(completeBackupRescueDiagnostic());+ }+ } else {+ inspected = parseLibraryPackage(library, files, { ...limits, salvageInvalidMedia: true });+ }+ if (validateImage !== undefined) {+ const invalidImageIds = await findInvalidImportedImageIds(inspected.images, validateImage);+ if (invalidImageIds.size) {+ const salvageFiles = filesWithoutInvalidLibraryImages(library, files, invalidImageIds);+ inspected = parseLibraryPackage(library, salvageFiles, { ...limits, salvageInvalidMedia: true });+ if (strict) {+ effectiveSourceType = LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP;+ sourceDiagnostics.push(completeBackupRescueDiagnostic());+ }+ inspected.importDiagnostics = inspected.importDiagnostics.map((diagnostic) =>+ diagnostic.action === "dropped" && invalidImageIds.has(diagnostic.assetId)+ ? { ...diagnostic, reason: "decode_failure" }+ : diagnostic+ );+ }+ }+ const {+ assets,+ images,+ skillAssets,+ importDiagnostics,+ importStats,+ ...state+ } = inspected;+ const diagnostics = [...sourceDiagnostics, ...structuredClone(importDiagnostics)];++ return {+ sourceType: effectiveSourceType,+ state,+ resources: { assets, images, skillAssets },+ resourceIndex: {+ mediaAssetIds: [...assets.keys()],+ skillAssetIds: [...skillAssets.keys()]+ },+ report: {+ status: diagnostics.length ? "partial" : "ready",+ diagnostics,+ stats: mergeReportStats(sourceReport?.stats, importStats)+ }+ };+}++function completeBackupRescueDiagnostic() {+ return {+ code: "backup_integrity_degraded",+ severity: "backup",+ action: "rescue",+ reason: "recoverable_content_failure"+ };+}++export function planLibraryTransfer({ currentState = {}, inspection, options = {} } = {}) {+ if (!inspection?.state || !inspection?.report) throw new Error("资料恢复计划缺少检查结果");+ const preferredPlan = options.preferredPlan && typeof options.preferredPlan === "object"+ ? options.preferredPlan+ : {};+ const preferredMappings = preferredPlan.mappings && typeof preferredPlan.mappings === "object"+ ? preferredPlan.mappings+ : {};+ const mode = normalizeTransferMode(preferredPlan.mode ?? options.mode);+ if (mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE && inspection.sourceType !== LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP) {+ throw new Error("救援备份只能安全合并,不能恢复成备份当时状态");+ }+ const libraryAddedAt = receiverTimestamp(preferredPlan.libraryAddedAt || options.now);+ const importBatchId = clean(preferredPlan.importBatchId || options.importBatchId) ||+ `library-import:${globalThis.crypto.randomUUID()}`;+ const preserveLibraryConfiguration = preferredPlan.preserveLibraryConfiguration === true ||+ (!Object.hasOwn(preferredPlan, "preserveLibraryConfiguration") && options.preserveLibraryConfiguration === true);+ const importReport = cloneReport(preferredPlan.importReport ?? inspection.report);+ const conflicts = mode === LIBRARY_TRANSFER_MODES.SAFE_MERGE+ ? libraryEntryConflicts(currentState.entries, inspection.state.entries)+ : [];+ const conflictResolutions = plannedConflictResolutions(+ conflicts,+ preferredPlan.conflictResolutions ?? options.conflictResolutions+ );+ const resourceIndex = inspection.resourceIndex ?? {+ mediaAssetIds: inspection.resources?.assets instanceof Map ? [...inspection.resources.assets.keys()] : [],+ skillAssetIds: inspection.resources?.skillAssets instanceof Map ? [...inspection.resources.skillAssets.keys()] : []+ };+ const exactVisualIdMap = mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? isolatedResourceMap(resourceIndex.mediaAssetIds, preferredMappings.visualIds, "restore-media")+ : preferredMappings.visualIds;+ const exactSkillAssetIdMap = mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? isolatedResourceMap(resourceIndex.skillAssetIds, preferredMappings.skillAssetIds, "skill-file:restore")+ : preferredMappings.skillAssetIds;+ const mergeReceiver = mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? exactReplacementReceiver(inspection.state)+ : currentState;+ const result = mergeLibraryPackage(mergeReceiver, inspection.state, {+ preserveLibraryConfiguration: mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE || preserveLibraryConfiguration,+ libraryAddedAt,+ importBatchId,+ importReport,+ facetIdMap: preferredMappings.facetIds,+ nodeIdMap: preferredMappings.nodeIds,+ entryIdMap: preferredMappings.entryIds,+ collectionIdMap: preferredMappings.collectionIds,+ compoundIdMap: preferredMappings.compoundIds,+ visualIdMap: exactVisualIdMap,+ reservedVisualIds: mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE ? resourceIndex.mediaAssetIds : [],+ entryConflictResolutions: conflictResolutions,+ sessionIdMap: preferredMappings.sessionIds,+ runIdMap: preferredMappings.runIds,+ skillIdMap: preferredMappings.skillIds,+ skillVersionIdMap: preferredMappings.skillVersionIds,+ packageAssetIdMap: exactSkillAssetIdMap,+ trashEntryIdMap: preferredMappings.trashEntryIds,+ trashCollectionIdMap: preferredMappings.trashCollectionIds,+ trashCompoundIdMap: preferredMappings.trashCompoundIds+ });+ if (mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE) {+ restoreExactEntryImportMetadata(result.state.entries, inspection.state.entries, result.entryIdMap);+ }+ const mappings = {+ entryIds: result.entryIdMap,+ collectionIds: result.collectionIdMap ?? {},+ facetIds: result.facetIdMap ?? {},+ nodeIds: result.nodeIdMap ?? {},+ compoundIds: result.compoundIdMap,+ visualIds: result.visualIdMap,+ createdVisualIds: result.createdVisualIdMap,+ sessionIds: result.sessionIdMap,+ runIds: result.runIdMap,+ skillIds: result.skillIdMap,+ skillVersionIds: result.skillVersionIdMap ?? {},+ skillAssetIds: result.packageAssetIdMap,+ trashEntryIds: result.trashEntryIdMap ?? {},+ trashCollectionIds: result.trashCollectionIdMap ?? {},+ trashCompoundIds: result.trashCompoundIdMap ?? {}+ };+ const resourceWrites = [+ ...resourceIndex.mediaAssetIds.flatMap((sourceId) => (+ mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE ? mappings.visualIds[sourceId] : mappings.createdVisualIds[sourceId]+ )+ ? [{+ sourceId,+ targetId: mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? mappings.visualIds[sourceId]+ : mappings.createdVisualIds[sourceId],+ resourceType: "media"+ }]+ : []),+ ...resourceIndex.skillAssetIds.flatMap((sourceId) => mappings.skillAssetIds[sourceId]+ ? [{ sourceId, targetId: mappings.skillAssetIds[sourceId], resourceType: "skill" }]+ : [])+ ];+ const rollback = mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? { required: true, retainedAssetIds: retainedLibraryAssetIds(currentState) }+ : { required: false, retainedAssetIds: [] };+ const context = {+ version: 1,+ sourceType: inspection.sourceType,+ mode,+ preserveLibraryConfiguration,+ libraryAddedAt,+ importBatchId,+ importReport,+ mappings,+ conflictResolutions,+ resourceWrites,+ cleanupAssetIds: [],+ rollback+ };++ return {+ ...result,+ targetState: result.state,+ mappings,+ resourceWrites,+ cleanupAssetIds: [],+ rollback,+ conflicts: conflicts.map((conflict) => ({+ ...conflict,+ resolution: conflictResolutions[conflict.entryId]+ })),+ context,+ planToken: createLibraryImportPlanToken(currentState, inspection.state, context)+ };+}++export function libraryTransferWriteBytes(resourceWritesValue, resourcesValue = {}) {+ const assets = resourcesValue?.assets instanceof Map ? resourcesValue.assets : new Map();+ const skillAssets = resourcesValue?.skillAssets instanceof Map ? resourcesValue.skillAssets : new Map();+ let total = 0;+ for (const item of Array.isArray(resourceWritesValue) ? resourceWritesValue : []) {+ const blob = item?.resourceType === "skill"+ ? skillAssets.get(item.sourceId)+ : assets.get(item?.sourceId);+ if (!(blob instanceof Blob)) throw new Error("恢复计划引用的资源已经变化,请重新检查");+ total += blob.size;+ }+ return total;+}++function normalizeTransferMode(value) {+ return value === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ : LIBRARY_TRANSFER_MODES.SAFE_MERGE;+}++function libraryEntryConflicts(currentEntriesValue, incomingEntriesValue) {+ const current = new Map((Array.isArray(currentEntriesValue) ? currentEntriesValue : [])+ .map((entry) => [clean(entry?.id), entry]).filter(([id]) => Boolean(id)));+ return (Array.isArray(incomingEntriesValue) ? incomingEntriesValue : []).flatMap((incoming) => {+ const local = current.get(clean(incoming?.id));+ if (!local) return [];+ const localFingerprint = caseSemanticFingerprint(local);+ const incomingFingerprint = caseSemanticFingerprint(incoming);+ if (localFingerprint && incomingFingerprint && localFingerprint === incomingFingerprint) return [];+ return [{+ entryId: clean(incoming.id),+ localTitle: clean(local.title) || "未命名案例",+ incomingTitle: clean(incoming.title) || "未命名案例"+ }];+ });+}++function plannedConflictResolutions(conflicts, value) {+ const requested = value && typeof value === "object" ? value : {};+ return Object.fromEntries(conflicts.map((conflict) => {+ const resolution = ["keep-local", "use-incoming", "keep-both"].includes(requested[conflict.entryId])+ ? requested[conflict.entryId]+ : "keep-local";+ return [conflict.entryId, resolution];+ }));+}++function isolatedResourceMap(sourceIdsValue, preferredValue, prefix) {+ const preferred = preferredValue && typeof preferredValue === "object" ? preferredValue : {};+ const used = new Set();+ return Object.fromEntries((Array.isArray(sourceIdsValue) ? sourceIdsValue : []).map((sourceIdValue) => {+ const sourceId = clean(sourceIdValue);+ const planned = clean(preferred[sourceId]);+ const targetId = planned && planned !== sourceId && !used.has(planned)+ ? planned+ : `${prefix}:${globalThis.crypto.randomUUID()}`;+ used.add(targetId);+ return [sourceId, targetId];+ }).filter(([sourceId]) => Boolean(sourceId)));+}++function exactReplacementReceiver(source = {}) {+ return {+ ...structuredClone(source),+ entries: [],+ trashState: { version: 1, items: [] },+ organizerState: { version: 1, collections: [] },+ compoundCases: [],+ composerSessions: [],+ creativeRuns: [],+ creativeSkills: { version: 1, items: [] }+ };+}++function restoreExactEntryImportMetadata(targetEntriesValue, sourceEntriesValue, entryIdMap = {}) {+ const targets = new Map((Array.isArray(targetEntriesValue) ? targetEntriesValue : []).map((entry) => [entry.id, entry]));+ for (const source of Array.isArray(sourceEntriesValue) ? sourceEntriesValue : []) {+ const target = targets.get(entryIdMap[source.id] ?? source.id);+ if (!target) continue;+ for (const key of ["libraryAddedAt", "importBatchId", "importSource"]) {+ if (Object.hasOwn(source, key)) target[key] = structuredClone(source[key]);+ else delete target[key];+ }+ }+}++function retainedLibraryAssetIds(state = {}) {+ return [...libraryStoredAssetIds(state)].sort();+}++function receiverTimestamp(value) {+ const requested = clean(value);+ return requested && Number.isFinite(Date.parse(requested))+ ? new Date(requested).toISOString()+ : new Date().toISOString();+}++function cloneReport(value) {+ return {+ status: value?.status === "partial" ? "partial" : "ready",+ diagnostics: Array.isArray(value?.diagnostics) ? structuredClone(value.diagnostics) : [],+ stats: value?.stats && typeof value.stats === "object" ? structuredClone(value.stats) : {}+ };+}++function mergeReportStats(sourceValue, inspectedValue) {+ const merged = sourceValue && typeof sourceValue === "object" ? structuredClone(sourceValue) : {};+ for (const [key, value] of Object.entries(inspectedValue && typeof inspectedValue === "object" ? inspectedValue : {})) {+ const number = Number(value);+ merged[key] = Number.isFinite(number) ? number : value;+ }+ return merged;+}++function clean(value) {+ return String(value ?? "").trim();+}diff --git a/library.html b/library.htmlindex dd985d5..368e796 100644--- a/library.html+++ b/library.html@@ -299,7 +299,10 @@<button id="create-folder-backup" type="button" data-i18n="备份资料库">备份资料库</button><button id="restore-folder-backup" class="button-secondary" type="button" data-i18n="恢复资料库">恢复资料库</button></div>- <p class="data-safety-note" data-i18n="备份会把案例和本地媒体逐项写入资料夹;恢复前会先检查内容,不会覆盖现有资料。">备份会把案例和本地媒体逐项写入资料夹;恢复前会先检查内容,不会覆盖现有资料。</p>+ <div class="data-safety-secondary-actions">+ <button id="restore-library-replacement-point" class="quiet-danger" type="button" hidden data-i18n="回退上次精确恢复">回退上次精确恢复</button>+ </div>+ <p class="data-safety-note" data-i18n="备份会把案例和本地媒体逐项写入资料夹;恢复默认安全合并。只有完整备份可在明确选择并建立回退点后精确替换。">备份会把案例和本地媒体逐项写入资料夹;恢复默认安全合并。只有完整备份可在明确选择并建立回退点后精确替换。</p><details id="sync-settings" class="sync-settings"><summary data-i18n="跨设备同步">跨设备同步</summary><div class="sync-settings-body">diff --git a/library.js b/library.jsindex b82307c..d0e58e4 100644--- a/library.js+++ b/library.js@@ -2,6 +2,7 @@ import { libraryTitleForLocale, libraryTitleForStorage, renderLibraryJson, screeimport { readImageDimensions } from "./image-metadata.js";import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";import {+ assertStorageCapacity,deleteMediaBlob,getAllDerivedMetadata,getDerivedMedia,@@ -12,12 +13,19 @@ import {saveMediaBlob,savePortableAssetBlob} from "./media-store.js";-import { parseCompleteFolderBackup, parseLibraryPackage, projectPackageEntryIds } from "./library-package.js";-import { filesWithoutInvalidEntryMedia, findInvalidImportedImageIds } from "./library-import-media.js";+import { projectPackageEntryIds } from "./library-package.js";+import {+ LIBRARY_TRANSFER_MODES,+ LIBRARY_TRANSFER_SOURCES,+ inspectLibraryTransfer,+ libraryTransferWriteBytes+} from "./library-transfer.js";import { caseSemanticFingerprint } from "./library-semantic-identity.js";import {- buildFolderBackupCompletion,- verifyFolderBackupCompletion+ buildFolderBackupWritePlan,+ inspectFolderBackupEnvelope,+ verifyFolderBackupCompletion,+ verifyFolderRescueCompletion} from "./library-export-plan.js";import { buildLibraryImportReport, importReportDescription } from "./library-import-dialog.js";import { parseCreativeExperimentPackage } from "./creative-experiment-package.js";@@ -29,6 +37,7 @@ import {formatBytes,importFailureDetails} from "./resource-limits.js";+import { resolvePortableAssetFormat } from "./asset-formats.js";import {facetNodes,formatFacetNodePath,@@ -94,7 +103,8 @@ import {normalizeEntryMedia,normalizeMediaAsset,posterAssetForVideo,- primaryMediaAsset+ primaryMediaAsset,+ removeEntryMedia} from "./media.js";import { saveSyncDirectoryHandle } from "./sync-store.js";import { SYNC_ERROR_CODES } from "./sync-model.js";@@ -202,7 +212,7 @@ const elements = Object.fromEntries(["project-section", "project-root-drop", "manage-project-order", "selection-simple-actions", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree","vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default","open-curated", "open-skills", "open-trash", "trash-count", "trash-dialog", "trash-close", "trash-list", "trash-feedback", "trash-restore-all", "trash-empty", "data-safety-dialog", "data-safety-count", "data-safety-status", "data-safety-feedback",- "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "cancel-sync", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback",+ "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "cancel-sync", "create-folder-backup", "restore-folder-backup", "restore-library-replacement-point", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback","vision-batch-dialog", "vision-batch-close", "vision-batch-summary", "vision-batch-service", "vision-batch-all-images", "vision-batch-reanalyze","vision-batch-progress", "vision-batch-progress-bar", "vision-batch-start", "vision-batch-pause", "vision-batch-resume", "vision-batch-retry", "vision-batch-cancel", "vision-batch-feedback","library-drop-target", "import-dialog", "import-dialog-title", "import-close", "import-source", "import-choose-files", "import-last-job", "import-actions", "import-preparing", "import-confirmation", "import-supported-count", "import-skipped-count", "import-duplicate-count", "import-byte-size", "import-project", "import-project-hint", "import-auto-analyze", "import-label-editor", "import-file-list", "import-feedback", "import-job-panel", "import-job-title", "import-job-count", "import-job-progress", "import-job-feedback", "import-cancel", "import-retry", "import-undo", "import-view-project", "import-start"@@ -649,6 +659,7 @@ function bindEvents() {elements.cancelSync.addEventListener("click", cancelManualSync);elements.createFolderBackup.addEventListener("click", createCompleteFolderBackup);elements.restoreFolderBackup.addEventListener("click", restoreCompleteFolderBackup);+ elements.restoreLibraryReplacementPoint.addEventListener("click", restoreLastLibraryReplacementPoint);elements.importLibraryPackage.addEventListener("click", () => elements.libraryPackageFile.click());elements.libraryPackageFile.addEventListener("change", importSharedLibraryPackage);elements.disconnectSyncFolder.addEventListener("click", async () => {@@ -2940,18 +2951,40 @@ function preserveSettingsAnchor(anchor, action = null) {});}+function backupResourceDiagnostic(code, value, error, context = {}) {+ return {+ code,+ severity: "media",+ action: "dropped",+ ...context,+ assetId: String(value?.assetId || value?.id || "").trim(),+ path: String(value?.assetPath || value?.archivePath || value?.path || "").trim(),+ reason: "unreadable_source",+ message: String(error?.message || "资源无法读取").trim()+ };+}++function folderBackupRescueDescription(reportValue = {}) {+ const diagnostics = Array.isArray(reportValue?.diagnostics) ? reportValue.diagnostics : [];+ const visible = diagnostics.slice(0, 12).map((item) => {+ const subject = String(item?.title || item?.path || item?.assetId || "未命名资源").trim();+ const reason = String(item?.message || item?.reason || "无法完整备份").trim();+ return `“${subject}”:${reason}`;+ });+ const remaining = Math.max(0, diagnostics.length - visible.length);+ const details = [...visible, ...(remaining ? [`另有 ${remaining} 项问题`] : [])].join(";");+ return `预检发现 ${diagnostics.length} 项无法完整写入的资源。继续将剔除这些项目并生成明确标识的救援备份,不会写完整备份标记。${details ? ` ${details}` : ""}`;+}+async function createCompleteFolderBackup() {if (dataSafetyOperationActive) return showDataSafetyFeedback("当前操作仍在进行,请等待完成", true);if (typeof window.showDirectoryPicker !== "function") return showDataSafetyFeedback("当前浏览器不支持资料夹备份,请使用最新版 Chrome", true);setDataSafetyBusy(true);try {- const parent = await window.showDirectoryPicker({ mode: "readwrite" });- const permission = typeof parent.requestPermission === "function" ? await parent.requestPermission({ mode: "readwrite" }) : "granted";- if (permission !== "granted") throw new Error("没有获得所选资料夹的写入权限");const response = await chrome.runtime.sendMessage({ type: "GET_FOLDER_BACKUP_STATE" });if (!response?.ok) throw new Error(response?.message || "无法读取资料库");- const stamp = new Date().toISOString().replace(/[:.]/g, "-");- const directory = await parent.getDirectoryHandle(`PromptDirector-Backup-${stamp}`, { create: true });+ const plannedFiles = new Map();+ const preflightDiagnostics = [];const resolvedEntries = [];let mediaCount = 0;let byteSize = 0;@@ -2961,18 +2994,28 @@ async function createCompleteFolderBackup() {? await localAssetReferenceBackupBlob(entry, asset): await getMediaBlob(asset.id);if (!(blob instanceof Blob)) throw new Error(`“${entry.title || "未命名案例"}”的媒体缺失,完整备份已停止`);- const assetPath = folderAssetPath(scopeId, asset, blob.type || asset.mimeType);- showDataSafetyFeedback(`正在写入第 ${mediaCount + 1} 项媒体 · ${formatBytes(byteSize + blob.size)}`);- await writeDirectoryFile(directory, assetPath, blob);+ const portableFormat = resolvePortableAssetFormat(asset, blob);+ const assetPath = folderAssetPath(scopeId, asset, portableFormat);+ showDataSafetyFeedback(`正在检查第 ${mediaCount + 1} 项媒体 · ${formatBytes(byteSize + blob.size)}`);+ plannedFiles.set(assetPath, blob);mediaCount += 1;byteSize += blob.size;- return portableManagedBackupAsset(asset, blob, assetPath, await sha256Blob(blob));+ return portableManagedBackupAsset(asset, blob, assetPath, await sha256Blob(blob), portableFormat);};const materializeEntry = async (entryValue, scopeId = "") => {- const entry = normalizeEntryMedia(entryValue);+ let entry = normalizeEntryMedia(entryValue);const mediaAssets = [];- for (const asset of entry.mediaAssets) {- mediaAssets.push(await materializeAsset(entry, asset, scopeId || entry.id));+ for (const asset of [...entry.mediaAssets]) {+ try {+ mediaAssets.push(await materializeAsset(entry, asset, scopeId || entry.id));+ } catch (error) {+ if (error?.name === "AbortError") throw error;+ preflightDiagnostics.push(backupResourceDiagnostic("library_media_dropped", asset, error, {+ entryId: entry.id,+ title: entry.title+ }));+ entry = removeEntryMedia(entry, asset.id);+ }}return { ...entry, mediaAssets };};@@ -2998,45 +3041,105 @@ async function createCompleteFolderBackup() {for (const run of response.creativeRuns ?? []) {const outputs = [];for (const output of run.outputs ?? []) {- const blob = await getMediaBlob(output.visual.id);- if (!blob) throw new Error("创作结果媒体缺失,完整备份已停止");- const assetPath = `creative-results/${safeFolderPart(run.id)}/${safeFolderPart(output.visual.id)}.${folderExtension(blob.type, output.visual.kind)}`;- await writeDirectoryFile(directory, assetPath, blob);- outputs.push({ ...output, visual: { ...output.visual, assetPath } });- mediaCount += 1;- byteSize += blob.size;+ try {+ const blob = await getMediaBlob(output.visual.id);+ if (!blob) throw new Error("创作结果媒体缺失");+ const portableFormat = resolvePortableAssetFormat(output.visual, blob);+ const assetPath = `creative-results/${safeFolderPart(run.id)}/${safeFolderPart(output.visual.id)}.${portableFormat.extension}`;+ plannedFiles.set(assetPath, blob);+ outputs.push({+ ...output,+ visual: {+ ...output.visual,+ assetPath,+ sourceFormat: portableFormat.extension,+ mimeType: portableFormat.mimeType,+ formatCategory: portableFormat.formatCategory,+ playbackCapability: portableFormat.playbackCapability+ }+ });+ mediaCount += 1;+ byteSize += blob.size;+ } catch (error) {+ if (error?.name === "AbortError") throw error;+ preflightDiagnostics.push(backupResourceDiagnostic("creative_output_dropped", output.visual, error, {+ runId: run.id,+ title: run.title+ }));+ }}- creativeRuns.push({ ...run, outputs });+ const retainedVisualIds = new Set(outputs.map((output) => output.visual.id));+ creativeRuns.push({+ ...run,+ outputs,+ events: (run.events ?? []).filter((event) => retainedVisualIds.has(event.visualId))+ });}const creativeSkills = structuredClone(response.creativeSkills ?? { version: 1, items: [] });for (const skill of creativeSkills.items ?? []) {+ const packageFiles = [];for (const file of skill.packageFiles ?? []) {- const blob = await getMediaBlob(file.assetId);- if (!blob) throw new Error(`外部 Skill 原包文件缺失:${file.path}`);- const archivePath = skillFolderPath(skill.portableId, file.assetId, file.path);- await writeDirectoryFile(directory, archivePath, blob);- file.archivePath = archivePath;- file.byteSize = blob.size;- file.mimeType = blob.type || file.mimeType || "application/octet-stream";- mediaCount += 1;- byteSize += blob.size;+ try {+ const blob = await getMediaBlob(file.assetId);+ if (!blob) throw new Error(`外部 Skill 原包文件缺失:${file.path}`);+ const archivePath = skillFolderPath(skill.portableId, file.assetId, file.path);+ plannedFiles.set(archivePath, blob);+ packageFiles.push({+ ...file,+ archivePath,+ byteSize: blob.size,+ mimeType: blob.type || file.mimeType || "application/octet-stream"+ });+ mediaCount += 1;+ byteSize += blob.size;+ } catch (error) {+ if (error?.name === "AbortError") throw error;+ preflightDiagnostics.push(backupResourceDiagnostic("skill_file_dropped", file, error, {+ skillId: skill.id,+ title: skill.callName+ }));+ }}+ skill.packageFiles = packageFiles;}const composerSessions = structuredClone(response.composerSessions ?? []);for (const session of composerSessions) {for (const reference of session.referenceSnapshots ?? []) {if (reference?.sourceType !== "temporary") continue;+ const retainedAssetRefs = [];+ const retainedAssetIds = new Set();for (const asset of reference.assetRefs ?? []) {- const blob = await getMediaBlob(asset.assetId);- if (!blob) throw new Error(`临时附件“${asset.name || reference.title || "未命名附件"}”缺失,完整备份已停止`);- const archivePath = tempReferenceFolderPath(session.id, asset.assetId, blob.type, asset.kind);- await writeDirectoryFile(directory, archivePath, blob);- asset.archivePath = archivePath;- asset.byteSize = blob.size;- asset.mimeType = blob.type || asset.mimeType || "application/octet-stream";- mediaCount += 1;- byteSize += blob.size;+ try {+ const blob = await getMediaBlob(asset.assetId);+ if (!blob) throw new Error(`临时附件“${asset.name || reference.title || "未命名附件"}”缺失`);+ const portableFormat = resolvePortableAssetFormat({+ ...asset,+ id: asset.assetId,+ sourceTitle: asset.name+ }, blob);+ const archivePath = tempReferenceFolderPath(session.id, asset.assetId, portableFormat);+ plannedFiles.set(archivePath, blob);+ retainedAssetRefs.push({+ ...asset,+ archivePath,+ byteSize: blob.size,+ mimeType: portableFormat.mimeType,+ sourceFormat: portableFormat.extension+ });+ retainedAssetIds.add(asset.assetId);+ mediaCount += 1;+ byteSize += blob.size;+ } catch (error) {+ if (error?.name === "AbortError") throw error;+ preflightDiagnostics.push(backupResourceDiagnostic("temporary_asset_dropped", asset, error, {+ sessionId: session.id,+ title: reference.title+ }));+ }}+ reference.assetRefs = retainedAssetRefs;+ reference.imageRefs = (reference.imageRefs ?? [])+ .filter((image) => retainedAssetIds.has(image.visualId));}}const libraryJson = renderLibraryJson(@@ -3052,36 +3155,135 @@ async function createCompleteFolderBackup() {},response.compoundCases);- await writeDirectoryFile(directory, "library.json", new Blob([libraryJson], { type: "application/json" }));- const writtenFiles = await readDirectoryFiles(directory);- const writtenLibraryFile = writtenFiles.get("library.json");- if (!(writtenLibraryFile instanceof Blob)) throw new Error("无法回读刚写入的 library.json");- const writtenLibrary = JSON.parse(await writtenLibraryFile.text());- const writtenMediaSizes = [...backupMediaPaths(writtenLibrary)].map((path) => writtenFiles.get(path)?.size ?? 0);- const writtenTotalBytes = writtenMediaSizes.reduce((sum, size) => sum + size, 0);- const largestWrittenMedia = Math.max(1, ...writtenMediaSizes);- const verified = await parseCompleteFolderBackup(writtenLibrary, writtenFiles, {- ...PORTABLE_LIBRARY_LIMITS,- maxArchiveBytes: Math.max(1, writtenTotalBytes),- maxFileBytes: largestWrittenMedia,- maxImageBytes: largestWrittenMedia,- maxVideoBytes: largestWrittenMedia+ plannedFiles.set("library.json", new Blob([libraryJson], { type: "application/json" }));+ const plannedLibrary = JSON.parse(libraryJson);+ const initialMediaSizes = [...backupMediaPaths(plannedLibrary)].map((path) => plannedFiles.get(path)?.size ?? 0);+ const initialTotalBytes = initialMediaSizes.reduce((sum, size) => sum + size, 0);+ const initialLargestMedia = Math.max(1, ...initialMediaSizes);+ const inspectPlannedBackup = (sourceType, sourceReport) => inspectLibraryTransfer({+ sourceType,+ library: plannedLibrary,+ files: plannedFiles,+ limits: {+ ...PORTABLE_LIBRARY_LIMITS,+ maxArchiveBytes: Math.max(1, initialTotalBytes),+ maxFileBytes: initialLargestMedia,+ maxImageBytes: initialLargestMedia,+ maxVideoBytes: initialLargestMedia+ },+ validateImage: validateImportedImage,+ sourceReport});- await validateImportedImageDimensions(verified.images);- assertFolderBackupRoundtrip(resolvedEntries, trashState, verified);- const trashCaseCount = trashState.items.filter((item) => item.kind === "entry").length;- const trashProjectCount = trashState.items.filter((item) => item.kind === "collection").length;- const completion = await buildFolderBackupCompletion(writtenFiles, {+ let preflight;+ if (preflightDiagnostics.length) {+ preflight = await inspectPlannedBackup(LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP, {+ status: "partial",+ diagnostics: preflightDiagnostics,+ stats: {}+ });+ } else {+ try {+ preflight = await inspectPlannedBackup(LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP);+ } catch (error) {+ if (error?.name === "AbortError") throw error;+ preflightDiagnostics.push(backupResourceDiagnostic("backup_preflight_degraded", null, error));+ preflight = await inspectPlannedBackup(LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP, {+ status: "partial",+ diagnostics: preflightDiagnostics,+ stats: {}+ });+ }+ }+ const exportState = preflight.state;+ const finalLibraryJson = renderLibraryJson(+ exportState.entries, exportState.settings, exportState.taxonomy, exportState.facetCatalog,+ exportState.classificationRules, exportState.organizerState,+ {+ trashState: exportState.trashState,+ composerSettings: exportState.composerSettings,+ composerSessions: exportState.composerSessions,+ creativeExperimentSettings: exportState.creativeExperimentSettings,+ creativeRuns: exportState.creativeRuns,+ creativeSkills: exportState.creativeSkills+ },+ exportState.compoundCases+ );+ const finalLibrary = JSON.parse(finalLibraryJson);+ const finalFiles = new Map();+ for (const path of backupMediaPaths(finalLibrary)) {+ const blob = plannedFiles.get(path);+ if (!(blob instanceof Blob)) throw new Error(`预检后的资源“${path}”不可读取`);+ finalFiles.set(path, blob);+ }+ finalFiles.set("library.json", new Blob([finalLibraryJson], { type: "application/json" }));+ const finalMediaSizes = [...backupMediaPaths(finalLibrary)].map((path) => finalFiles.get(path)?.size ?? 0);+ byteSize = finalMediaSizes.reduce((sum, size) => sum + size, 0);+ mediaCount = finalMediaSizes.length;+ const largestPlannedMedia = Math.max(1, ...finalMediaSizes);+ const plannedTotalBytes = byteSize;+ const trashCaseCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "entry").length;+ const trashProjectCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "collection").length;+ const writePlan = await buildFolderBackupWritePlan({+ files: finalFiles,+ report: preflight.report,+ metadata: {createdAt: new Date().toISOString(),- caseCount: resolvedEntries.length,+ caseCount: exportState.entries.length,trashCaseCount,trashProjectCount,mediaCount,byteSize+ }+ });+ if (writePlan.mode === "rescue") {+ const approved = await confirmAppAction({+ title: "生成救援备份?",+ description: folderBackupRescueDescription(writePlan.report),+ confirmLabel: "生成救援备份"+ });+ if (!approved) {+ showDataSafetyFeedback("已取消备份,没有创建任何资料夹");+ return;+ }+ }+ const parent = await window.showDirectoryPicker({ mode: "readwrite" });+ const permission = typeof parent.requestPermission === "function" ? await parent.requestPermission({ mode: "readwrite" }) : "granted";+ if (permission !== "granted") throw new Error("没有获得所选资料夹的写入权限");+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");+ const directoryName = writePlan.mode === "rescue" ? `PromptDirector-Rescue-${stamp}` : `PromptDirector-Backup-${stamp}`;+ const directory = await parent.getDirectoryHandle(directoryName, { create: true });+ let writtenCount = 0;+ for (const [path, blob] of writePlan.files) {+ writtenCount += 1;+ showDataSafetyFeedback(`正在写入第 ${writtenCount} / ${writePlan.files.size} 个文件`);+ await writeDirectoryFile(directory, path, blob);+ }+ const writtenFiles = await readDirectoryFiles(directory);+ if (writePlan.mode === "rescue") await verifyFolderRescueCompletion(writePlan.marker, writtenFiles);+ else await verifyFolderBackupCompletion(writePlan.marker, writtenFiles);+ const writtenLibraryFile = writtenFiles.get("library.json");+ if (!(writtenLibraryFile instanceof Blob)) throw new Error("无法回读刚写入的 library.json");+ const writtenLibrary = JSON.parse(await writtenLibraryFile.text());+ const writtenVerification = await inspectLibraryTransfer({+ sourceType: writePlan.mode === "rescue"+ ? LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP+ : LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: writtenLibrary,+ files: writtenFiles,+ limits: {+ ...PORTABLE_LIBRARY_LIMITS,+ maxArchiveBytes: Math.max(1, plannedTotalBytes),+ maxFileBytes: largestPlannedMedia,+ maxImageBytes: largestPlannedMedia,+ maxVideoBytes: largestPlannedMedia+ },+ validateImage: validateImportedImage,+ sourceReport: writePlan.report});- await verifyFolderBackupCompletion(completion, writtenFiles);- await writeDirectoryFile(directory, "complete.json", new Blob([JSON.stringify(completion, null, 2)], { type: "application/json" }));- showDataSafetyFeedback(`完整备份已完成 · ${resolvedEntries.length} 个案例 · ${mediaCount} 项媒体 · ${formatBytes(byteSize)}`);+ assertFolderBackupRoundtrip(exportState.entries, exportState.trashState, writtenVerification.state);+ await writeDirectoryFile(directory, writePlan.markerPath, new Blob([JSON.stringify(writePlan.marker, null, 2)], { type: "application/json" }));+ const completionLabel = writePlan.mode === "rescue" ? "救援备份已完成" : "完整备份已完成";+ showDataSafetyFeedback(`${completionLabel} · ${exportState.entries.length} 个案例 · ${mediaCount} 项媒体 · ${formatBytes(byteSize)}`);} catch (error) {if (error?.name !== "AbortError") showDataSafetyFeedback(`${error.message};未写入完成标记的资料夹不会被当作有效备份`, true);} finally {@@ -3099,23 +3301,18 @@ async function restoreCompleteFolderBackup() {try {const directory = await window.showDirectoryPicker({ mode: "read" });const files = await readDirectoryFiles(directory);- const marker = files.get("complete.json");- const libraryFile = files.get("library.json");- if (!marker || !libraryFile) throw new Error("这不是完整的 PromptDirector 资料夹备份");- let completion;- try { completion = JSON.parse(await marker.text()); }- catch { throw new Error("complete.json 已损坏,无法确认备份完整性"); }- if (completion?.format !== "prompt-director-folder-backup" || ![1, 2].includes(completion.version)) {- throw new Error("完整备份标记无效");- }- if (completion.version === 2) await verifyFolderBackupCompletion(completion, files);+ const envelope = await inspectFolderBackupEnvelope(files);+ const completion = envelope.marker;+ const libraryFile = envelope.libraryFile;let library;try { library = JSON.parse(await libraryFile.text()); }catch { throw new Error("library.json 已损坏,无法恢复"); }const backupPaths = backupMediaPaths(library);const backupMediaSizes = [...backupPaths].map((path) => files.get(path)?.size ?? 0);const totalBytes = backupMediaSizes.reduce((sum, size) => sum + size, 0);- if (completion.mediaCount !== backupPaths.size || completion.byteSize !== totalBytes) {+ if (envelope.mode === "complete" && (+ completion.mediaCount !== backupPaths.size || completion.byteSize !== totalBytes+ )) {throw new Error("完整备份的媒体数量或大小校验失败,未写入资料库");}const largestMediaBytes = Math.max(1, ...backupMediaSizes);@@ -3126,57 +3323,160 @@ async function restoreCompleteFolderBackup() {maxImageBytes: largestMediaBytes,maxVideoBytes: largestMediaBytes};- const parsed = await parseCompleteFolderBackup(library, files, restoreLimits);- await validateImportedImageDimensions(parsed.images);- const restoredLibrary = { ...parsed };- delete restoredLibrary.assets;- delete restoredLibrary.images;- delete restoredLibrary.skillAssets;- showDataSafetyFeedback(`预检完成 · ${parsed.entries.length} 个案例 · ${parsed.assets.size} 项本地媒体 · ${formatBytes(totalBytes)}`);- const preview = await chrome.runtime.sendMessage({ type: "PREVIEW_LIBRARY_IMPORT", library: restoredLibrary });+ const inspection = await inspectLibraryTransfer({+ sourceType: envelope.mode === "complete"+ ? LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP+ : LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP,+ library,+ files,+ limits: restoreLimits,+ validateImage: validateImportedImage,+ sourceReport: envelope.report+ });+ const restoredLibrary = inspection.state;+ const restoredResources = inspection.resources;+ const completeBackup = inspection.sourceType === LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP;+ const recoveryLabel = t(completeBackup ? "完整恢复" : "救援恢复");+ showDataSafetyFeedback(t("{label}预检完成 · {caseCount} 个案例 · {mediaCount} 项本地媒体 · {byteSize}", {+ label: recoveryLabel,+ caseCount: restoredLibrary.entries.length,+ mediaCount: restoredResources.assets.size,+ byteSize: formatBytes(totalBytes)+ }));+ let preview = await chrome.runtime.sendMessage({+ type: "PREVIEW_LIBRARY_IMPORT",+ library: restoredLibrary,+ sourceType: inspection.sourceType,+ mode: LIBRARY_TRANSFER_MODES.SAFE_MERGE,+ importReport: inspection.report,+ resourceIndex: inspection.resourceIndex+ });if (!preview?.ok) throw new Error(preview?.message || "无法检查资料夹备份");- const createdMediaIds = Object.keys(preview.createdVisualIdMap ?? {});- const createdMediaBytes = createdMediaIds.reduce((sum, sourceId) => sum + (parsed.assets.get(sourceId)?.size ?? 0), 0);+ const conflicts = Array.isArray(preview.conflicts) ? preview.conflicts : [];+ const fields = [+ ...(completeBackup ? [{+ id: "mode",+ label: t("恢复方式"),+ type: "select",+ value: LIBRARY_TRANSFER_MODES.SAFE_MERGE,+ options: [+ { value: LIBRARY_TRANSFER_MODES.SAFE_MERGE, label: t("安全合并(推荐)") },+ { value: LIBRARY_TRANSFER_MODES.EXACT_REPLACE, label: t("恢复成备份当时状态") }+ ],+ help: t("安全合并保留本机资料;精确替换会替换完整备份管理的案例、项目、回收站和关联资料。")+ }] : []),+ ...conflicts.map((conflict, index) => ({+ id: `conflict-${index}`,+ label: t("冲突案例:本机“{localTitle}” / 备份“{incomingTitle}”", {+ localTitle: conflict.localTitle,+ incomingTitle: conflict.incomingTitle+ }),+ type: "select",+ value: conflict.resolution || "keep-local",+ options: [+ { value: "keep-local", label: t("保留本机版本(推荐)") },+ { value: "use-incoming", label: t("使用备份版本") },+ { value: "keep-both", label: t("两个版本都保留") }+ ]+ }))+ ];+ const choice = await showAppDialog({+ title: t(completeBackup ? "选择资料库恢复方式" : "检查救援恢复方案"),+ description: completeBackup+ ? t("已检查 {caseCount} 个案例;发现 {conflictCount} 个内容冲突。安全合并为默认方式。", {+ caseCount: restoredLibrary.entries.length,+ conflictCount: conflicts.length+ })+ : t("这是不完整来源,只能安全合并。已检查 {caseCount} 个案例;发现 {conflictCount} 个内容冲突。", {+ caseCount: restoredLibrary.entries.length,+ conflictCount: conflicts.length+ }),+ fields,+ confirmLabel: t("继续检查"),+ onReady: ({ controls, form }) => {+ const modeControl = controls.get("mode");+ if (!modeControl) return;+ const updateConflictVisibility = () => {+ const exact = modeControl.value === LIBRARY_TRANSFER_MODES.EXACT_REPLACE;+ conflicts.forEach((_, index) => {+ const wrapper = form.querySelector(`[data-field-id="conflict-${index}"]`);+ if (wrapper) wrapper.hidden = exact;+ });+ };+ modeControl.addEventListener("change", updateConflictVisibility);+ updateConflictVisibility();+ }+ });+ if (choice === null) {+ showDataSafetyFeedback(t("已取消恢复,资料库没有变化"));+ return;+ }+ const mode = completeBackup && choice.mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ ? LIBRARY_TRANSFER_MODES.EXACT_REPLACE+ : LIBRARY_TRANSFER_MODES.SAFE_MERGE;+ const conflictResolutions = Object.fromEntries(conflicts.map((conflict, index) => [+ conflict.entryId,+ ["keep-local", "use-incoming", "keep-both"].includes(choice[`conflict-${index}`])+ ? choice[`conflict-${index}`]+ : "keep-local"+ ]));+ preview = await chrome.runtime.sendMessage({+ type: "PREVIEW_LIBRARY_IMPORT",+ library: restoredLibrary,+ sourceType: inspection.sourceType,+ mode,+ conflictResolutions,+ importReport: inspection.report,+ resourceIndex: inspection.resourceIndex+ });+ if (!preview?.ok) throw new Error(translateUiMessage(preview?.message || "无法生成资料夹恢复计划"));+ const resourceWrites = Array.isArray(preview.resourceWrites) ? preview.resourceWrites : [];+ const createdMediaBytes = libraryTransferWriteBytes(resourceWrites, restoredResources);+ const storageEstimate = typeof navigator.storage?.estimate === "function"+ ? await navigator.storage.estimate()+ : {};+ assertStorageCapacity(storageEstimate, createdMediaBytes);const report = buildLibraryImportReport(preview, {- mediaCount: createdMediaIds.length + Object.keys(preview.packageAssetIdMap ?? {}).length,+ mediaCount: resourceWrites.length,byteLabel: formatBytes(createdMediaBytes)});- showDataSafetyFeedback(`${report.summary} · ${report.status === "partial" ? "发现可恢复问题,详情见确认框" : "检查通过"}`);+ showDataSafetyFeedback(`${translateUiMessage(report.summary)} · ${t(report.status === "partial" ? "发现可恢复问题,详情见确认框" : "检查通过")}`);+ const exactReplace = mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE;+ const reportDescription = localizedImportReportDescription(report);const approved = await confirmAppAction({- title: "恢复资料库备份?",- description: `${importReportDescription(report)}已有内容不会被覆盖。`,- confirmLabel: "开始恢复"+ title: exactReplace+ ? t("将资料库恢复成备份当时状态?")+ : t(completeBackup ? "安全合并资料库备份?" : "按救援方案恢复资料库?"),+ description: exactReplace+ ? `${reportDescription}${t("将写入 {byteSize} 资源,并替换完整备份管理的案例、项目、回收站和关联资料。开始前会自动建立回退点;API Key、同步密码、设备信息和文件夹授权保持本机状态。", { byteSize: formatBytes(createdMediaBytes) })}`+ : `${reportDescription}${t("只会提交预检确认的健康内容;冲突按你的选择处理,其他本机资料不会被覆盖。")}`,+ confirmLabel: t(exactReplace ? "建立回退点并精确恢复" : completeBackup ? "开始安全合并" : "开始救援恢复"),+ danger: exactReplace});if (!approved) {- showDataSafetyFeedback("已取消恢复,资料库没有变化");+ showDataSafetyFeedback(t("已取消恢复,资料库没有变化"));return;}const operationId = createLibraryImportOperationId();- for (const [sourceId, targetId] of Object.entries(preview.createdVisualIdMap ?? {})) {- const blob = parsed.assets.get(sourceId);- if (!blob) continue;- await savePortableAssetBlob(targetId, blob);- savedIds.push(targetId);- }- for (const [sourceId, targetId] of Object.entries(preview.packageAssetIdMap ?? {})) {- const blob = parsed.skillAssets.get(sourceId);- if (!blob) continue;- await savePortableAssetBlob(targetId, blob);- savedIds.push(targetId);+ for (const item of resourceWrites) {+ const blob = item.resourceType === "skill"+ ? restoredResources.skillAssets.get(item.sourceId)+ : restoredResources.assets.get(item.sourceId);+ if (!(blob instanceof Blob)) throw new Error("预检后的备份资源已经变化,请重新检查");+ await savePortableAssetBlob(item.targetId, blob);+ savedIds.push(item.targetId);}applyStarted = true;const response = await applyLibraryImportWithReceipt({type: "APPLY_LIBRARY_IMPORT", library: restoredLibrary,operationId,planToken: preview.planToken,- entryIdMap: preview.entryIdMap, compoundIdMap: preview.compoundIdMap,- visualIdMap: preview.visualIdMap, sessionIdMap: preview.sessionIdMap, runIdMap: preview.runIdMap,- skillIdMap: preview.skillIdMap, packageAssetIdMap: preview.packageAssetIdMap+ plan: preview.plan});if (!response?.ok) throw new Error(response?.message || "资料夹恢复失败");applySucceeded = true;await refreshLibrary();- showDataSafetyFeedback(`${response.message} · 媒体文件校验并恢复完成`);+ showDataSafetyFeedback(`${translateUiMessage(response.message)} · ${t("{label}已按预检方案完成", { label: recoveryLabel })}`);await renderDataSafetyStatus();} catch (error) {const retained = applySucceeded@@ -3189,6 +3489,21 @@ async function restoreCompleteFolderBackup() {}}+async function restoreLastLibraryReplacementPoint() {+ if (dataSafetyOperationActive) return showDataSafetyFeedback(t("当前操作仍在进行,请等待完成"), true);+ const approved = await confirmAppAction({+ title: t("回退上次精确恢复?"),+ description: t("资料库会回到上次精确恢复前的状态;当前状态也会保存成新的回退点,因此仍可再次切换回来。"),+ confirmLabel: t("确认回退"),+ danger: true+ });+ if (!approved) return;+ await runDataSafetyAction(+ elements.restoreLibraryReplacementPoint,+ { type: "RESTORE_LIBRARY_REPLACEMENT_POINT" }+ );+}+async function importSharedLibraryPackage() {const file = elements.libraryPackageFile.files?.[0];if (!file) return;@@ -3218,43 +3533,43 @@ async function importSharedLibraryPackage() {let library;try { library = JSON.parse(await libraryFile.text()); }catch { throw new Error("分享包中的 library.json 已损坏"); }- const salvageOptions = { ...packageLimits, salvageInvalidMedia: true };- let parsed = parseLibraryPackage(library, files, salvageOptions);- const invalidImageIds = await findInvalidImportedImageIds(parsed.images, validateImportedImage);- if (invalidImageIds.size) {- const salvageFiles = filesWithoutInvalidEntryMedia(library, files, invalidImageIds);- parsed = parseLibraryPackage(library, salvageFiles, salvageOptions);- await validateImportedImageDimensions(parsed.images);- }- const importLibrary = { ...parsed };- delete importLibrary.assets;- delete importLibrary.images;- delete importLibrary.skillAssets;+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library,+ files,+ limits: packageLimits,+ validateImage: validateImportedImage+ });+ const importLibrary = inspection.state;+ const importResources = inspection.resources;const preview = await chrome.runtime.sendMessage({type: "PREVIEW_LIBRARY_IMPORT",library: importLibrary,+ importReport: inspection.report,+ resourceIndex: inspection.resourceIndex,preserveLibraryConfiguration: true});if (!preview?.ok) throw new Error(preview?.message || "无法检查分享包");- const createdMediaIds = Object.keys(preview.createdVisualIdMap ?? {});- const createdMediaBytes = createdMediaIds.reduce((sum, sourceId) => sum + (parsed.assets.get(sourceId)?.size ?? 0), 0);+ const resourceWrites = Array.isArray(preview.resourceWrites) ? preview.resourceWrites : [];+ const createdMediaBytes = resourceWrites.reduce((sum, item) =>+ sum + (importResources.assets.get(item.sourceId)?.size ?? 0), 0);const report = buildLibraryImportReport(preview, {- mediaCount: createdMediaIds.length,+ mediaCount: resourceWrites.length,byteLabel: formatBytes(createdMediaBytes)});showDataSafetyFeedback(`${report.summary} · ${report.status === "partial" ? "发现可恢复问题,详情见确认框" : "检查通过"}`);const approved = await confirmAppAction({title: "导入分享包?",- description: `${importReportDescription(report)}现有资料不会被覆盖。`,+ description: `${localizedImportReportDescription(report)}${t("现有资料不会被覆盖。")}`,confirmLabel: "开始导入"});if (!approved) return showDataSafetyFeedback("已取消导入,资料库没有变化");const operationId = createLibraryImportOperationId();- for (const [sourceId, targetId] of Object.entries(preview.createdVisualIdMap ?? {})) {- const blob = parsed.assets.get(sourceId);- if (!blob) continue;- await savePortableAssetBlob(targetId, blob);- savedIds.push(targetId);+ for (const item of resourceWrites) {+ const blob = importResources.assets.get(item.sourceId);+ if (!(blob instanceof Blob)) throw new Error("预检后的分享包资源已经变化,请重新检查");+ await savePortableAssetBlob(item.targetId, blob);+ savedIds.push(item.targetId);}applyStarted = true;const response = await applyLibraryImportWithReceipt({@@ -3262,12 +3577,7 @@ async function importSharedLibraryPackage() {library: importLibrary,operationId,planToken: preview.planToken,- entryIdMap: preview.entryIdMap,- compoundIdMap: preview.compoundIdMap,- visualIdMap: preview.visualIdMap,- sessionIdMap: preview.sessionIdMap,- runIdMap: preview.runIdMap,- preserveLibraryConfiguration: true+ plan: preview.plan});if (!response?.ok) throw new Error(response?.message || "分享包导入失败");applySucceeded = true;@@ -3387,7 +3697,7 @@ async function localAssetReferenceBackupBlob(entry, asset) {return inspection.file;}-function portableManagedBackupAsset(asset, blob, assetPath, contentHash) {+function portableManagedBackupAsset(asset, blob, assetPath, contentHash, portableFormat) {const {recordType: _recordType,linkStatus: _linkStatus,@@ -3405,8 +3715,10 @@ function portableManagedBackupAsset(asset, blob, assetPath, contentHash) {return {...portable,storageMode: "managed",- ...(asset.kind === "attachment" ? { formatCategory: "other-source" } : {}),- mimeType: blob.type || asset.mimeType || "application/octet-stream",+ sourceFormat: portableFormat.extension,+ mimeType: portableFormat.mimeType,+ formatCategory: portableFormat.formatCategory,+ playbackCapability: portableFormat.playbackCapability,byteSize: blob.size,contentHash,assetPath@@ -3419,8 +3731,8 @@ function skillFolderPath(portableId, assetId, packagePath) {return ["skills", safeFolderPart(portableId), safeFolderPart(assetId), ...parts].join("/");}-function tempReferenceFolderPath(sessionId, assetId, mimeType, kind) {- return `temp-references/${safeFolderPart(sessionId)}/${safeFolderPart(assetId)}.${folderExtension(mimeType, kind)}`;+function tempReferenceFolderPath(sessionId, assetId, portableFormat) {+ return `temp-references/${safeFolderPart(sessionId)}/${safeFolderPart(assetId)}.${portableFormat.extension}`;}async function writeDirectoryFile(root, path, data) {@@ -3452,17 +3764,8 @@ async function readDirectoryFiles(directory, prefix = "") {return files;}-function folderAssetPath(entryId, asset, mimeType) {- const directories = {- image: "images",- video: "videos",- audio: "audio",- document: "documents",- attachment: "attachments"- };- const directory = directories[asset.kind];- if (!directory) throw new Error("媒体类型无效,完整备份已停止");- return `${directory}/${safeFolderPart(entryId)}/${safeFolderPart(asset.id)}.${folderExtension(mimeType, asset.kind, asset.sourceFormat)}`;+function folderAssetPath(entryId, asset, portableFormat) {+ return `${portableFormat.directory}/${safeFolderPart(entryId)}/${safeFolderPart(asset.id)}.${portableFormat.extension}`;}function safeFolderPart(value) {@@ -3471,18 +3774,6 @@ function safeFolderPart(value) {return safe;}-function folderExtension(mimeType, kind, sourceFormat = "") {- const known = {- "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "video/mp4": "mp4", "video/webm": "webm",- "video/quicktime": "mov", "video/x-matroska": "mkv", "video/x-msvideo": "avi", "application/pdf": "pdf",- "application/rtf": "rtf", "text/rtf": "rtf", "application/x-rtf": "rtf",- "text/plain": "txt", "text/markdown": "md", "text/html": "html"- };- const preserved = String(sourceFormat ?? "").trim().toLocaleLowerCase("en-US").replace(/^\./, "");- if (kind === "attachment" && /^[a-z0-9]+$/u.test(preserved)) return preserved;- return known[mimeType] || (kind === "video" ? "video" : ["document", "attachment"].includes(kind) ? "bin" : kind === "audio" ? "audio" : "webp");-}-async function importCreativeExperimentArchive() {const file = elements.creativeExperimentFile.files?.[0];if (!file) return;@@ -9007,6 +9298,11 @@ async function renderDataSafetyStatus() {elements.cancelSync.disabled = syncStatus.cancelRequested === true;elements.dataSafetyPassword.hidden = !(needsFolder || needsUnlock);elements.disconnectSyncFolder.hidden = !syncStatus.connected;+ elements.restoreLibraryReplacementPoint.hidden = !response.canRestoreReplacementPoint;+ elements.restoreLibraryReplacementPoint.disabled = dataSafetyOperationActive || !response.canRestoreReplacementPoint;+ elements.restoreLibraryReplacementPoint.title = response.replacementPointCreatedAt+ ? t("回退点建立于 {date}", { date: new Date(response.replacementPointCreatedAt).toLocaleString() })+ : "";if (missingLocation) elements.syncSettings.open = true;}@@ -9175,6 +9471,7 @@ function setDataSafetyBusy(active, operationType = "") {elements.importLibraryPackage,elements.createFolderBackup,elements.restoreFolderBackup,+ elements.restoreLibraryReplacementPoint,elements.connectSyncFolder,elements.unlockSyncVault,elements.syncNow,@@ -9204,6 +9501,12 @@ function showDataSafetyFeedback(message, isError = false) {elements.dataSafetyFeedback.classList.toggle("error", isError);}+function localizedImportReportDescription(report) {+ const sentences = importReportDescription(report).split("。").map((item) => item.trim()).filter(Boolean);+ const separator = currentLocale() === "en" ? ". " : "。";+ return sentences.map(translateUiMessage).join(separator) + (currentLocale() === "en" ? ". " : "。");+}+function syncStatusMessage(status) {if (!status.connected) return t("尚未连接同步文件夹");if (status.permission !== "granted") return t("同步文件夹需要重新授权");diff --git a/manifest.json b/manifest.jsonindex 25000c9..3b2833f 100644--- a/manifest.json+++ b/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "__MSG_extensionName__",- "version": "1.19.2",+ "version": "1.19.3","key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB","homepage_url": "https://github.com/wchao6891/PromptDirector","default_locale": "zh_CN",diff --git a/manual-sync.js b/manual-sync.jsindex 74e31e0..ce1d6de 100644--- a/manual-sync.js+++ b/manual-sync.js@@ -20,6 +20,9 @@ import {writeSyncObject,writeSyncSnapshot} from "./sync-vault.js";+import { libraryAssetCleanupCandidates, libraryStoredAssetIds } from "./library-asset-inventory.js";+import { salvageMissingLibraryAssets } from "./library-asset-salvage.js";+import { reconcileLibrarySemanticIdentity } from "./library-semantic-identity.js";const TERMINAL_STATES = new Set(["up-to-date", "success", "canceled", "error"]);@@ -156,7 +159,19 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: deprecords: meta.records};const remotePreview = mergeRevisionSnapshots([...remoteSnapshots, unchangedLocal]);- if (sameRevisionRecords(remotePreview.records, meta.records)) {+ const remoteIdentity = reconcileLibrarySemanticIdentity(remotePreview.state);+ if (sameRevisionRecords(remotePreview.records, meta.records) && !remoteIdentity.changed) {+ if (meta.pendingCleanupAssetIds.length) {+ const current = await deps.readState();+ const cleanup = await retryPendingCleanup({+ state: current,+ settings,+ meta,+ dependencies: deps,+ effects+ });+ return upToDateResult(current, cleanup.meta, effects, cleanup.pendingCount);+ }return upToDateResult(remotePreview.state, { ...meta, assetRefs: previousRefs }, effects);}}@@ -170,8 +185,9 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depbaseSnapshot});const preview = mergeRevisionSnapshots([...remoteSnapshots, localSnapshot]);+ const previewIdentity = reconcileLibrarySemanticIdentity(preview.state);- if (!meta.localDirty && !dirtyAssetIds.size && sameRevisionRecords(preview.records, meta.records)) {+ if (!meta.localDirty && !dirtyAssetIds.size && !previewIdentity.changed && sameRevisionRecords(preview.records, meta.records)) {return upToDateResult(current, { ...meta, assetRefs: previousRefs }, effects);}@@ -179,6 +195,7 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depconst missingAssets = collectSyncAssets(localPrepared).filter((asset) =>asset.storageMode !== "reference" && !asset.objectId);+ const missingAssetIds = new Set();if (missingAssets.length) update({ phase: "uploading" });for (const [index, asset] of missingAssets.entries()) {requireNotAborted(signal);@@ -186,7 +203,8 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depconst blob = await deps.readMedia(asset.id);requireNotAborted(signal);if (!(blob instanceof Blob) || !blob.size) {- throw new Error(`本机媒体 ${asset.id} 已缺失,同步已停止且资料未被修改`);+ missingAssetIds.add(asset.id);+ continue;}const objectId = await deps.writeObject(vault, blob, { signal });requireNotAborted(signal);@@ -195,7 +213,10 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: dep}if (missingAssets.length) deps.onProgress({ phase: "uploading", current: missingAssets.length, total: missingAssets.length });- localPrepared = attachSyncImageReferences(current, localRefs);+ const salvage = salvageMissingLibraryAssets(current, missingAssetIds);+ const skippedMedia = salvage.issues;+ for (const assetId of missingAssetIds) delete localRefs[assetId];+ localPrepared = attachSyncImageReferences(salvage.state, localRefs);localSnapshot = await createRevisionSnapshot(localPrepared, {deviceId: settings.deviceId,logicalClock: maximumClock + 1,@@ -203,10 +224,13 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: dep});update({ phase: "merging" });const merged = mergeRevisionSnapshots([...remoteSnapshots, localSnapshot]);- if (syncStateHasContent(current) && !syncStateHasContent(merged.state)) {+ const identity = reconcileLibrarySemanticIdentity(merged.state);+ const finalState = identity.state;+ const finalImageRefs = reconcileImageReferences(merged.imageRefs, identity.assetIdMap, finalState);+ if (!skippedMedia.length && syncStateHasContent(current) && !syncStateHasContent(finalState)) {throw new Error("同步结果异常为空,本机资料未被修改");}- const finalPrepared = attachSyncImageReferences(merged.state, merged.imageRefs);+ const finalPrepared = attachSyncImageReferences(finalState, finalImageRefs);const finalSnapshot = await createRevisionSnapshot(finalPrepared, {deviceId: settings.deviceId,logicalClock: maximumClock + 2,@@ -215,24 +239,37 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depconst changeSummary = summarizeRevisionChanges(meta.records, finalSnapshot.records, merged.conflicts);const appliedChangeSummary = summarizeRevisionChanges(localSnapshot.records, finalSnapshot.records, merged.conflicts);- if (sameRevisionRecords(finalSnapshot.records, meta.records)) {+ if (!skippedMedia.length && sameRevisionRecords(finalSnapshot.records, meta.records)) {+ let nextMeta = { ...meta, assetRefs: localRefs };if (meta.localDirty || dirtyAssetIds.size) {requireNotAborted(signal);+ nextMeta = { ...nextMeta, localDirty: false, dirtyAssetIds: [] };await deps.commit({state: current,settings,- meta: { ...meta, assetRefs: localRefs, localDirty: false, dirtyAssetIds: [] },+ meta: nextMeta,trackingOnly: true,changeSummary});effects.localMetadataCommitted = true;}- return upToDateResult(current, { ...meta, assetRefs: localRefs }, effects);+ if (nextMeta.pendingCleanupAssetIds.length) {+ const cleanup = await retryPendingCleanup({+ state: current,+ settings,+ meta: nextMeta,+ dependencies: deps,+ effects+ });+ nextMeta = cleanup.meta;+ return upToDateResult(current, nextMeta, effects, cleanup.pendingCount);+ }+ return upToDateResult(current, nextMeta, effects);}const replacements = remoteMediaReplacements({vault,- imageRefs: merged.imageRefs,+ imageRefs: finalImageRefs,localRefs,readObject: deps.readObject,signal,@@ -240,8 +277,12 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: dep});update({ phase: "downloading", changeSummary });const lastSyncAt = deps.now();- const restoredMediaCount = countDifferentReferences(merged.imageRefs, localRefs);- effects.localBusinessChanged = hasChanges(appliedChangeSummary) || restoredMediaCount > 0;+ const restoredMediaCount = countDifferentReferences(finalImageRefs, localRefs);+ const cleanupAssetIds = libraryAssetCleanupCandidates(current, finalState, {+ localOnlyState: current,+ pendingAssetIds: meta.pendingCleanupAssetIds+ });+ effects.localBusinessChanged = skippedMedia.length > 0 || hasChanges(appliedChangeSummary) || restoredMediaCount > 0;const nextSettings = normalizeSyncSettings({...settings,lastSyncAt,@@ -260,14 +301,15 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depawait deps.writeSnapshot(vault, finalSnapshot, { retentionCount: settings.retentionCount });effects.snapshotWritten = true;await deps.commit({- state: merged.state,+ state: finalState,settings: nextSettings,meta: {logicalClock: maximumClock + 2,records: finalSnapshot.records,- assetRefs: merged.imageRefs,+ assetRefs: finalImageRefs,localDirty: false,- dirtyAssetIds: []+ dirtyAssetIds: [],+ pendingCleanupAssetIds: cleanupAssetIds},trackingOnly: false,changeSummary@@ -276,13 +318,32 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: dep}});effects.localMediaCommitted = restoredMediaCount;+ const cleanup = await retryPendingCleanup({+ state: {+ ...finalState,+ libraryReplacementRecoveryPoint: current.libraryReplacementRecoveryPoint,+ creativeJobs: current.creativeJobs,+ importStaging: current.importStaging+ },+ settings: nextSettings,+ meta: {+ logicalClock: maximumClock + 2,+ records: finalSnapshot.records,+ assetRefs: finalImageRefs,+ localDirty: false,+ dirtyAssetIds: [],+ pendingCleanupAssetIds: cleanupAssetIds+ },+ dependencies: deps,+ effects+ });return {ok: true,upToDate: false,canceled: false,- entryCount: merged.state.entries?.length ?? 0,- mediaCount: Object.keys(merged.imageRefs).length,+ entryCount: finalState.entries?.length ?? 0,+ mediaCount: Object.keys(finalImageRefs).length,conflictCount: merged.conflicts.length,addedCount: changeSummary.added,updatedCount: changeSummary.updated,@@ -290,10 +351,54 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: depchangeSummary,appliedChangeSummary,lastSyncAt,+ cleanupPendingCount: cleanup.pendingCount,+ skippedMediaCount: skippedMedia.length,+ skippedMedia,effects: structuredClone(effects)};}+async function retryPendingCleanup({ state, settings, meta: metaValue, dependencies: deps, effects }) {+ const meta = normalizeSyncMeta(metaValue);+ const retained = libraryStoredAssetIds(state, { includeLocalOnly: true });+ const candidates = meta.pendingCleanupAssetIds.filter((assetId) => !retained.has(assetId));+ const results = await Promise.allSettled(candidates.map((assetId) => deps.deleteMedia(assetId)));+ const failedIds = candidates.filter((_assetId, index) => results[index].status === "rejected");+ const nextMeta = { ...meta, pendingCleanupAssetIds: failedIds };+ effects.localMediaDeleted += candidates.length - failedIds.length;+ effects.cleanupPendingCount = failedIds.length;+ if (candidates.length || meta.pendingCleanupAssetIds.length !== failedIds.length) {+ try {+ await deps.commit({+ state,+ settings,+ meta: nextMeta,+ trackingOnly: true,+ changeSummary: emptyChangeSummary()+ });+ effects.localMetadataCommitted = true;+ } catch {+ effects.cleanupTrackingPending = true;+ return { meta, pendingCount: meta.pendingCleanupAssetIds.length };+ }+ }+ return { meta: nextMeta, pendingCount: failedIds.length };+}++function reconcileImageReferences(referencesValue, assetIdMap = {}, state = {}) {+ const references = referencesValue && typeof referencesValue === "object" ? referencesValue : {};+ const retained = libraryStoredAssetIds(state);+ const result = {};+ for (const assetId of retained) {+ if (references[assetId]) result[assetId] = structuredClone(references[assetId]);+ }+ for (const [sourceId, targetId] of Object.entries(assetIdMap)) {+ if (!retained.has(targetId) || result[targetId] || !references[sourceId]) continue;+ result[targetId] = structuredClone(references[sourceId]);+ }+ return result;+}+async function* remoteMediaReplacements({ vault, imageRefs, localRefs, readObject, signal, onProgress }) {const pending = Object.entries(imageRefs).filter(([assetId, reference]) =>localRefs?.[assetId]?.objectId !== reference?.objectId@@ -333,7 +438,7 @@ function revisionBase(records) {return { format: SYNC_SNAPSHOT_FORMAT, version: SYNC_SNAPSHOT_VERSION, records };}-function upToDateResult(state, meta, effects) {+function upToDateResult(state, meta, effects, cleanupPendingCount = 0) {return {ok: true,upToDate: true,@@ -344,6 +449,7 @@ function upToDateResult(state, meta, effects) {addedCount: 0,updatedCount: 0,deletedCount: 0,+ cleanupPendingCount,changeSummary: emptyChangeSummary(),effects: structuredClone(effects)};@@ -409,7 +515,10 @@ function emptyEffects() {snapshotWritten: false,localMediaCommitted: 0,localBusinessChanged: false,- localMetadataCommitted: false+ localMetadataCommitted: false,+ localMediaDeleted: 0,+ cleanupPendingCount: 0,+ cleanupTrackingPending: false};}diff --git a/offscreen.js b/offscreen.jsindex 5d9274b..b10d95b 100644--- a/offscreen.js+++ b/offscreen.js@@ -32,13 +32,7 @@ import { normalizeCreativeRuns } from "./creative-runs.js";import { buildCreativeExperimentPackage } from "./creative-experiment-package.js";import { runCreativeJob } from "./creative-job-runner.js";import { composerServiceErrorDetails } from "./composer-service.js";-import {- assetFormatForExtension,- assetFormatsForMimeType,- canonicalMimeType,- fileExtension,- isReportedMimeCompatible-} from "./asset-formats.js";+import { resolvePortableAssetFormat } from "./asset-formats.js";import {LOCAL_ASSET_LINK_STATUS,getLocalAssetHandleRecord,@@ -353,10 +347,10 @@ export async function createArchiveUrl({if (asset.storageMode === "reference") {if (sharing && asset.recordType === "local-asset-reference") {const blob = await readLinkedAssetForShare(asset, entry.title);- const extension = packageMediaExtension(asset, blob);- const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;+ const portableFormat = resolvePortableAssetFormat(asset, blob);+ const assetPath = `${portableFormat.directory}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${portableFormat.extension}`;files.push({ name: assetPath, data: blob });- mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, portableFormat));continue;}mediaAssets.push(asset);@@ -364,14 +358,14 @@ export async function createArchiveUrl({}const blob = await getMediaBlob(asset.id);if (!blob) throw new Error(`“${entry.title || "未命名案例"}”的媒体文件缺失,请从完整备份恢复后再导出`);- const extension = packageMediaExtension(asset, blob);- const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;+ const portableFormat = resolvePortableAssetFormat(asset, blob);+ const assetPath = `${portableFormat.directory}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${portableFormat.extension}`;files.push({ name: assetPath, data: blob });if (asset.kind === "image") {imagePaths.set(asset.id, assetPath);imageCount += 1;}- mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, portableFormat));}resolvedEntries.push({ ...normalized, mediaAssets });}@@ -479,10 +473,10 @@ async function createCuratedSubmissionUrls({if (asset.storageMode !== "managed") throw new Error(`“${entry.title || "未命名案例"}”包含未保存到本地的媒体`);const blob = await getMediaBlob(asset.id);if (!blob) throw new Error(`“${entry.title || "未命名案例"}”的媒体文件缺失`);- const extension = packageMediaExtension(asset, blob);- const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;+ const portableFormat = resolvePortableAssetFormat(asset, blob);+ const assetPath = `${portableFormat.directory}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${portableFormat.extension}`;files.push({ name: assetPath, data: blob });- mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, portableFormat));mediaCount += 1;}resolvedEntries.push({ ...normalized, mediaAssets });@@ -602,66 +596,19 @@ function imageExtension(mimeType) {throw new Error(`不支持的截图格式:${mimeType || "未知"}`);}-function mediaDirectory(kind) {- const directories = {- image: "images",- video: "videos",- audio: "audio",- document: "documents",- attachment: "attachments"- };- const directory = directories[kind];- if (!directory) throw new Error(`不支持的媒体类型:${kind || "未知"}`);- return directory;-}--export function packageMediaExtension(asset, blob) {- const candidates = [- cleanExtension(asset?.sourceFormat),- fileExtension(asset?.sourceTitle),- ...assetFormatsForMimeType(blob?.type).filter((item) => item.kind === asset?.kind).flatMap((item) => item.extensions),- ...assetFormatsForMimeType(asset?.mimeType).filter((item) => item.kind === asset?.kind).flatMap((item) => item.extensions)- ].filter(Boolean);- for (const extension of candidates) {- const format = assetFormatForExtension(extension);- if (format?.kind === asset?.kind && isReportedMimeCompatible(format, blob?.type || asset?.mimeType)) return extension;- if (!format && asset?.kind === "attachment" && /^[a-z0-9]+$/u.test(extension)) return extension;- }- const known = {- "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp",- "video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov",- "video/x-matroska": "mkv", "video/x-msvideo": "avi",- "audio/mpeg": "mp3", "audio/wav": "wav", "audio/mp4": "m4a", "audio/aac": "aac",- "audio/flac": "flac", "audio/ogg": "ogg", "audio/opus": "opus",- "application/pdf": "pdf", "application/rtf": "rtf", "text/rtf": "rtf",- "text/plain": "txt", "text/markdown": "md", "text/html": "html", "text/vtt": "vtt"- };- const extension = known[blob?.type] || known[asset?.mimeType];- if (extension) return extension;- throw new Error(`“${asset?.sourceTitle || asset?.id || "未命名媒体"}”缺少可安全识别的文件扩展名`);-}--export function portableManagedAsset(asset, blob, assetPath, extension) {+export function portableManagedAsset(asset, blob, assetPath, portableFormat) {const next = { ...asset };for (const field of ["recordType", "linkStatus", "importFailure", "sourceLastModified", "linkedAt","localPath", "absolutePath", "fileHandle", "handle", "reference"]) delete next[field];- const format = assetFormatForExtension(extension);- const reportedMimeType = String(blob?.type || asset?.mimeType || "").trim().toLocaleLowerCase("en-US");- const compatibleMimeType = [blob?.type, asset?.mimeType]- .map((value) => String(value ?? "").trim().toLocaleLowerCase("en-US"))- .find((value) => value && !["application/octet-stream", "application/x-unknown"].includes(value) &&- (!format || isReportedMimeCompatible(format, value)));next.storageMode = "managed";next.assetPath = assetPath;next.byteSize = blob.size;- next.mimeType = format- ? canonicalMimeType(format, compatibleMimeType || "")- : compatibleMimeType || reportedMimeType || "application/octet-stream";- next.sourceFormat = extension;- next.formatCategory = format?.category || "other-source";- next.playbackCapability = ["image", "video", "audio"].includes(asset.kind) ? "native" : "unknown";+ next.mimeType = portableFormat.mimeType;+ next.sourceFormat = portableFormat.extension;+ next.formatCategory = portableFormat.formatCategory;+ next.playbackCapability = portableFormat.playbackCapability;return next;}@@ -687,10 +634,6 @@ export async function readLinkedAssetForShare(asset, entryTitle, dependencies =return inspection.file;}-function cleanExtension(value) {- return String(value ?? "").trim().toLocaleLowerCase("en-US").replace(/^\./u, "");-}-function loadImage(dataUrl) {return new Promise((resolve, reject) => {const image = new Image();diff --git a/organizer.js b/organizer.jsindex bd50f14..3954173 100644--- a/organizer.js+++ b/organizer.js@@ -265,6 +265,9 @@ export function mergeOrganizerStateWithMap(currentValue, importedValue, entryIdMconst receiverCreatedAt = normalizeTimestamp(options.createdAt);const collectionIdMap = new Map();+ const preferredCollectionIds = options.collectionIdMap && typeof options.collectionIdMap === "object"+ ? options.collectionIdMap+ : {};for (const source of imported.collections) {const parentId = source.parentId ? collectionIdMap.get(source.parentId) ?? null : null;const existing = current.collections.find((item) => item.parentId === parentId && canonical(item.name) === canonical(source.name));@@ -273,8 +276,11 @@ export function mergeOrganizerStateWithMap(currentValue, importedValue, entryIdMcollectionIdMap.set(source.id, existing.id);continue;}+ const preferredId = cleanId(preferredCollectionIds[source.id]);const id = current.collections.some((item) => item.id === source.id)- ? `collection:${globalThis.crypto.randomUUID()}`+ ? preferredId && !current.collections.some((item) => item.id === preferredId)+ ? preferredId+ : `collection:${globalThis.crypto.randomUUID()}`: source.id;current.collections.push({...source,diff --git a/package-lock.json b/package-lock.jsonindex 6535f6e..52942d5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "prompt-case-collector",- "version": "1.19.2",+ "version": "1.19.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "prompt-case-collector",- "version": "1.19.2",+ "version": "1.19.3","license": "Apache-2.0","dependencies": {"@jonahschulte/rtf-toolkit": "0.5.0",diff --git a/package.json b/package.jsonindex 5cce8b5..b572082 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "prompt-case-collector",- "version": "1.19.2",+ "version": "1.19.3","private": false,"license": "Apache-2.0","repository": "https://github.com/wchao6891/PromptDirector",diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.mdindex 3b45446..f45218a 100644--- a/store/CHROME_WEB_STORE_SUBMISSION.md+++ b/store/CHROME_WEB_STORE_SUBMISSION.md@@ -6,9 +6,9 @@ This file is the source-of-truth worksheet for the current PromptDirector manife- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.-- Current release candidate: `dist/PromptDirector-1.19.2.zip`.-- Candidate size: `8,742,944` bytes.-- Candidate SHA-256: `4f1f6be2fb40a01d35773293cdaa506e5806105e88aba08a917535d6adcd1a1b`.+- Current release candidate: `dist/PromptDirector-1.19.3.zip`.+- Candidate size: `8,822,765` bytes.+- Candidate SHA-256: `6c3e8767b9fe206950969c9e23b46a9588ecb586b927727b8f23d90a83639b25`.- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest.## Store listingdiff --git a/sync-model.js b/sync-model.jsindex 65e76e3..81e4a0e 100644--- a/sync-model.js+++ b/sync-model.js@@ -1,6 +1,7 @@import { sha256Hex } from "./sync-crypto.js";import { SCHEMA_VERSION, createDefaultTaxonomy, normalizeTaxonomy } from "./taxonomy.js";import { createDefaultTrashState } from "./trash.js";+import { libraryStoredAssets, storedAssetId } from "./library-asset-inventory.js";export const SYNC_SNAPSHOT_FORMAT = "prompt-director-sync-state";export const SYNC_SNAPSHOT_VERSION = 2;@@ -70,7 +71,10 @@ export function normalizeSyncMeta(value = {}) {assetRefs,localDirty: value?.localDirty === true,dirtyAssetIds: [...new Set((Array.isArray(value?.dirtyAssetIds) ? value.dirtyAssetIds : [])- .map(cleanId).filter(Boolean))]+ .map(cleanId).filter(Boolean))],+ pendingCleanupAssetIds: [...new Set((Array.isArray(value?.pendingCleanupAssetIds)+ ? value.pendingCleanupAssetIds+ : []).map(cleanId).filter(Boolean))].sort()};}@@ -104,7 +108,7 @@ export function syncErrorDetails(value) {export function collectSyncImageReferences(stateValue = {}) {const references = {};- for (const asset of stateStoredAssets(stateValue)) {+ for (const asset of libraryStoredAssets(stateValue)) {const id = storedAssetId(asset);if (!id || !validSyncObjectId(asset?.syncObjectId)) continue;references[id] = {@@ -118,7 +122,7 @@ export function collectSyncImageReferences(stateValue = {}) {export function collectSyncAssets(stateValue = {}) {const assets = [];const seen = new Set();- for (const asset of stateStoredAssets(stateValue)) {+ for (const asset of libraryStoredAssets(stateValue)) {const id = storedAssetId(asset);if (!id || seen.has(id)) continue;seen.add(id);@@ -179,7 +183,7 @@ export function summarizeRevisionChanges(beforeRecords = {}, afterRecords = {},export function attachSyncImageReferences(stateValue = {}, references = {}) {const state = structuredClone(stateValue);- for (const asset of stateStoredAssets(state)) {+ for (const asset of libraryStoredAssets(state)) {const reference = references?.[storedAssetId(asset)];if (!validSyncObjectId(reference?.objectId)) continue;asset.syncObjectId = reference.objectId;@@ -395,7 +399,7 @@ function restoreState(records) {for (const [key, record] of Object.entries(records)) {if (record.deletedAt || record.payload === null) continue;const [type] = splitKey(key);- const payload = stripSyncImageRefs(structuredClone(record.payload), imageRefs);+ const payload = structuredClone(record.payload);if (type === "entry") state.entries.push(payload);else if (type === "content_type") state.taxonomy.nodes.push(payload);else if (type === "compound_case") state.compoundCases.push(payload);@@ -425,93 +429,17 @@ function restoreState(records) {String(left.deletedAt ?? "").localeCompare(String(right.deletedAt ?? "")) ||String(left.id).localeCompare(String(right.id)));- return { state, imageRefs };-}--function stripSyncImageRefs(payload, imageRefs) {- for (const visual of payload?.mediaAssets ?? payload?.visuals ?? []) {- if (visual.syncObjectId) {- imageRefs[visual.id] = {- objectId: visual.syncObjectId,- contentType: visual.syncContentType || "application/octet-stream"- };- delete visual.syncObjectId;- delete visual.syncContentType;- }- }- for (const output of payload?.outputs ?? []) {- const visual = output?.visual;- if (visual?.syncObjectId) {- imageRefs[visual.id] = {- objectId: visual.syncObjectId,- contentType: visual.syncContentType || "application/octet-stream"- };- delete visual.syncObjectId;- delete visual.syncContentType;- }- }- for (const file of payload?.packageFiles ?? []) {- if (file?.syncObjectId) {- imageRefs[file.assetId] = {- objectId: file.syncObjectId,- contentType: file.syncContentType || file.mimeType || "application/octet-stream"- };- delete file.syncObjectId;- delete file.syncContentType;- }- }- for (const reference of payload?.referenceSnapshots ?? []) {- if (reference?.sourceType !== "temporary") continue;- for (const asset of reference.assetRefs ?? []) {- if (!asset?.syncObjectId) continue;- imageRefs[asset.assetId] = {- objectId: asset.syncObjectId,- contentType: asset.syncContentType || asset.mimeType || "application/octet-stream"- };- delete asset.syncObjectId;- delete asset.syncContentType;- }- }- for (const asset of trashItemStoredAssets(payload)) {+ for (const asset of libraryStoredAssets(state)) {const assetId = storedAssetId(asset);- if (!assetId || !asset?.syncObjectId) continue;+ if (!assetId || !validSyncObjectId(asset?.syncObjectId)) continue;imageRefs[assetId] = {objectId: asset.syncObjectId,- contentType: asset.syncContentType || asset.mimeType || "application/octet-stream"+ contentType: cleanText(asset.syncContentType) || cleanText(asset.mimeType) || "application/octet-stream"};delete asset.syncObjectId;delete asset.syncContentType;}- return payload;-}--function stateStoredAssets(stateValue) {- return [- ...(Array.isArray(stateValue?.entries) ? stateValue.entries : [])- .flatMap((entry) => Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : Array.isArray(entry?.visuals) ? entry.visuals : []),- ...(Array.isArray(stateValue?.creativeRuns) ? stateValue.creativeRuns : [])- .flatMap((run) => Array.isArray(run?.outputs) ? run.outputs.map((output) => output?.visual) : []),- ...(Array.isArray(stateValue?.creativeSkills?.items) ? stateValue.creativeSkills.items : [])- .flatMap((skill) => Array.isArray(skill?.packageFiles) ? skill.packageFiles : []),- ...(Array.isArray(stateValue?.composerSessions) ? stateValue.composerSessions : [])- .flatMap((session) => (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : [])- .filter((reference) => reference?.sourceType === "temporary")- .flatMap((reference) => Array.isArray(reference?.assetRefs) ? reference.assetRefs : [])),- ...(Array.isArray(stateValue?.trashState?.items) ? stateValue.trashState.items : [])- .flatMap(trashItemStoredAssets)- ].filter(Boolean);-}--function trashItemStoredAssets(item) {- if (!item || !["entry", "media"].includes(item.kind)) return [];- const snapshot = item.snapshot;- if (!snapshot || typeof snapshot !== "object") return [];- if (Array.isArray(snapshot.mediaAssets)) return snapshot.mediaAssets;- return Array.isArray(snapshot.visuals) ? snapshot.visuals : [];-}--function storedAssetId(asset) {- return cleanId(asset?.id ?? asset?.assetId);+ return { state, imageRefs };}function validSyncObjectId(value) {diff --git a/test/asset-formats.test.js b/test/asset-formats.test.jsindex 571d0e7..6a5ca87 100644--- a/test/asset-formats.test.js+++ b/test/asset-formats.test.js@@ -8,7 +8,8 @@ import {assetFormatForExtension,assetKindFromFileMetadata,extensionsForAssetKind,- isReportedMimeCompatible+ isReportedMimeCompatible,+ resolvePortableAssetFormat} from "../asset-formats.js";test("asset format registry is the unique source for supported kinds extensions and picker values", () => {@@ -50,3 +51,44 @@ test("generic browser MIME values are allowed only when a registered extension eassert.equal(assetKindFromFileMetadata({ name: "source.psd", type: "application/octet-stream" }), "attachment");assert.equal(assetKindFromFileMetadata({ name: "unknown.bin", type: "application/octet-stream" }), "");});++test("portable asset format resolves registered audio extensions for full backup and ZIP export", () => {+ for (const [mimeType, extension] of [+ ["audio/wav", "wav"],+ ["audio/mpeg", "mp3"],+ ["audio/mp4", "m4a"]+ ]) {+ const resolved = resolvePortableAssetFormat(+ { id: `audio:${extension}`, kind: "audio", mimeType },+ new Blob([extension], { type: mimeType })+ );+ assert.deepEqual(+ { directory: resolved.directory, extension: resolved.extension, mimeType: resolved.mimeType },+ { directory: "audio", extension, mimeType }+ );+ }+});++test("portable asset format round-trips every registered kind without a second format table", () => {+ const expectedDirectories = {+ image: "images",+ video: "videos",+ audio: "audio",+ document: "documents",+ attachment: "attachments"+ };+ for (const definition of ASSET_FORMAT_REGISTRY) {+ const extension = definition.extensions[0];+ const mimeType = definition.mimeTypes[0];+ const resolved = resolvePortableAssetFormat({+ id: `asset:${definition.id}`,+ kind: definition.kind,+ sourceFormat: extension,+ mimeType+ }, new Blob([definition.id], { type: mimeType }));+ assert.equal(resolved.directory, expectedDirectories[definition.kind], definition.id);+ assert.equal(resolved.extension, extension, definition.id);+ assert.equal(assetFormatForExtension(resolved.extension)?.id, definition.id, definition.id);+ assert.equal(isReportedMimeCompatible(definition, resolved.mimeType), true, definition.id);+ }+});diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.jsindex dfd2efa..6db129d 100644--- a/test/data-safety-ui.test.js+++ b/test/data-safety-ui.test.js@@ -70,8 +70,12 @@ test("share-package import is separate from the two backup actions while sync stassert.match(panel, /<details id="sync-settings"/);assert.match(panel, /<summary[^>]*data-i18n="跨设备同步"/);assert.equal((panel.match(/class="data-safety-primary-actions"/g) ?? []).length, 1);- const primaryActions = panel.slice(panel.indexOf('class="data-safety-primary-actions"'), panel.indexOf('<details id="sync-settings"'));+ const primaryActions = panel.slice(+ panel.indexOf('class="data-safety-primary-actions"'),+ panel.indexOf("</div>", panel.indexOf('class="data-safety-primary-actions"'))+ );assert.equal((primaryActions.match(/<button\b/g) ?? []).length, 2, "资料库备份与恢复只能保留两个常驻动作");+ assert.match(panel, /id="restore-library-replacement-point"[^>]*hidden/);});test("share-package import preserves local configuration and accepts historical package versions", async () => {@@ -85,7 +89,8 @@ test("share-package import preserves local configuration and accepts historical);assert.match(action, /PREVIEW_LIBRARY_IMPORT/);assert.match(action, /APPLY_LIBRARY_IMPORT/);- assert.equal((action.match(/preserveLibraryConfiguration:\s*true/g) ?? []).length, 2);+ assert.equal((action.match(/preserveLibraryConfiguration:\s*true/g) ?? []).length, 1);+ assert.match(action, /plan:\s*preview\.plan/);assert.match(parser, /prepareLibraryPackageDraft\(value\)/);assert.match(migrations, /isSupportedLibraryPackageVersion\(value\.version\)/);assert.match(format, /SUPPORTED_LIBRARY_PACKAGE_VERSIONS\s*=\s*Object\.freeze\(\[1, 2, 3, 4, 5\]\)/);@@ -113,3 +118,23 @@ test("folder backup self-check covers project and media trash snapshots plus theassert.match(roundtrip, /expected\.kind === "media"/);assert.match(roundtrip, /expected\.relationships/);});++test("folder restore exposes safe merge and exact replace with aggregate capacity and a reversible recovery point", async () => {+ const html = await readFile(new URL("../library.html", import.meta.url), "utf8");+ const library = await readFile(new URL("../library.js", import.meta.url), "utf8");+ const restore = library.slice(+ library.indexOf("async function restoreCompleteFolderBackup"),+ library.indexOf("async function importSharedLibraryPackage")+ );++ assert.match(restore, /LIBRARY_TRANSFER_MODES\.SAFE_MERGE/);+ assert.match(restore, /LIBRARY_TRANSFER_MODES\.EXACT_REPLACE/);+ assert.match(restore, /libraryTransferWriteBytes\(/);+ assert.match(restore, /navigator\.storage\.estimate\(\)/);+ assert.match(restore, /assertStorageCapacity\(/);+ assert.match(restore, /conflictResolutions/);+ assert.match(restore, /showAppDialog\(/);+ assert.match(html, /id="restore-library-replacement-point"/);+ assert.match(library, /RESTORE_LIBRARY_REPLACEMENT_POINT/);+ assert.match(library, /canRestoreReplacementPoint/);+});diff --git a/test/import-staging.test.js b/test/import-staging.test.jsindex 979133e..7019ec5 100644--- a/test/import-staging.test.js+++ b/test/import-staging.test.js@@ -141,6 +141,7 @@ test("unsupported local link moves from staging to a case media record without atest("orphan cleanup retains assets referenced by sessions jobs cases and staging", () => {const retained = collectRetainedLocalAssetIds({entries: [{ mediaAssets: [{ id: "case:asset" }] }],+ trashState: { items: [{ snapshot: { mediaAssets: [{ id: "trash:asset" }] } }] },creativeRuns: [{ outputs: [{ visual: { id: "result:asset" } }] }],creativeSkills: { items: [{ packageFiles: [{ assetId: "skill:asset" }] }] },composerSessions: [{ referenceSnapshots: [{@@ -158,7 +159,7 @@ test("orphan cleanup retains assets referenced by sessions jobs cases and stagin});assert.deepEqual([...retained].sort(), [- "case:asset", "job:asset", "result:asset", "session:asset", "skill:asset", "staged:asset"+ "case:asset", "job:asset", "result:asset", "session:asset", "skill:asset", "staged:asset", "trash:asset"]);});diff --git a/test/import-ui.test.js b/test/import-ui.test.jsindex da25e70..aaf79b9 100644--- a/test/import-ui.test.js+++ b/test/import-ui.test.js@@ -164,14 +164,16 @@ test("folder restore and ZIP import retry one response loss with the same operatassert.match(js, /await chrome\.runtime\.sendMessage\(message\)[\s\S]*await chrome\.runtime\.sendMessage\(message\)/);});-test("shared ZIP import salvages individual media failures while complete folder restore stays strict", () => {+test("shared ZIP and degraded folders salvage individual failures while verified folders stay strict", () => {const sharedImport = js.slice(js.indexOf("async function importSharedLibraryPackage"), js.indexOf("function createLibraryImportOperationId"));const folderRestore = js.slice(js.indexOf("async function restoreCompleteFolderBackup"), js.indexOf("async function importSharedLibraryPackage"));- assert.match(sharedImport, /salvageInvalidMedia:\s*true/);- assert.match(sharedImport, /findInvalidImportedImageIds/);- assert.match(sharedImport, /filesWithoutInvalidEntryMedia/);- assert.match(sharedImport, /parseLibraryPackage\(library,\s*salvageFiles/);- assert.doesNotMatch(folderRestore, /salvageInvalidMedia:\s*true/);+ assert.match(sharedImport, /inspectLibraryTransfer\(\{[\s\S]*?sourceType:\s*LIBRARY_TRANSFER_SOURCES\.SHARE_PACKAGE/);+ assert.match(folderRestore, /sourceType:\s*envelope\.mode === "complete"[\s\S]*LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP[\s\S]*LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP/);+ assert.match(folderRestore, /inspectFolderBackupEnvelope\(files\)/);+ assert.match(folderRestore, /sourceReport:\s*envelope\.report/);+ assert.match(sharedImport, /validateImage:\s*validateImportedImage/);+ assert.match(folderRestore, /validateImage:\s*validateImportedImage/);+ assert.doesNotMatch(sharedImport, /parseLibraryPackage|findInvalidImportedImageIds|filesWithoutInvalidEntryMedia/);});test("a committed import never deletes restored non-case media during later UI refresh failure", () => {diff --git a/test/library-asset-inventory.test.js b/test/library-asset-inventory.test.jsnew file mode 100644index 0000000..24cf355--- /dev/null+++ b/test/library-asset-inventory.test.js@@ -0,0 +1,59 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ libraryStoredAssetIds,+ libraryStoredAssets+} from "../library-asset-inventory.js";++test("one library asset inventory covers every durable synced resource without duplicating shared ids", () => {+ const shared = { id: "asset:shared", storageMode: "managed" };+ const state = {+ entries: [{ mediaAssets: [shared, { id: "asset:entry", storageMode: "managed" }] }],+ trashState: { items: [+ { kind: "entry", snapshot: { mediaAssets: [shared, { id: "asset:trash-entry" }] } },+ { kind: "media", snapshot: { mediaAssets: [{ id: "asset:trash-media" }] } }+ ] },+ creativeRuns: [{ outputs: [{ visual: { id: "asset:creative" } }] }],+ creativeSkills: { items: [{ packageFiles: [{ assetId: "asset:skill" }] }] },+ composerSessions: [{ referenceSnapshots: [+ { sourceType: "temporary", assetRefs: [{ assetId: "asset:temporary" }] },+ { sourceType: "case", assetRefs: [{ assetId: "asset:not-temporary" }] }+ ] }]+ };++ assert.deepEqual(libraryStoredAssetIds(state), new Set([+ "asset:shared",+ "asset:entry",+ "asset:trash-entry",+ "asset:trash-media",+ "asset:creative",+ "asset:skill",+ "asset:temporary"+ ]));+ assert.equal(libraryStoredAssets(state).filter((item) => item.id === "asset:shared").length, 2);+});++test("local-only jobs staging and recovery media are retained locally but never enter sync by default", () => {+ const state = {+ entries: [],+ creativeJobs: { items: [{ request: { session: { referenceSnapshots: [{+ sourceType: "temporary",+ assetRefs: [{ assetId: "asset:job" }]+ }] } } }] },+ importStaging: { assets: [{ assetId: "asset:staged", posterAssetId: "asset:poster" }] },+ libraryReplacementRecoveryPoint: {+ state: { entries: [{ mediaAssets: [{ id: "asset:recovery-state" }] }] },+ retainedAssetIds: ["asset:recovery-retained"]+ }+ };++ assert.deepEqual(libraryStoredAssetIds(state), new Set());+ assert.deepEqual(libraryStoredAssetIds(state, { includeLocalOnly: true }), new Set([+ "asset:job",+ "asset:staged",+ "asset:poster",+ "asset:recovery-state",+ "asset:recovery-retained"+ ]));+});diff --git a/test/library-asset-salvage.test.js b/test/library-asset-salvage.test.jsnew file mode 100644index 0000000..00d3bf0--- /dev/null+++ b/test/library-asset-salvage.test.js@@ -0,0 +1,66 @@+import test from "node:test";+import assert from "node:assert/strict";++import { salvageMissingLibraryAssets } from "../library-asset-salvage.js";++test("missing media is isolated across durable library owners while healthy content stays recoverable", () => {+ const state = {+ entries: [+ entry("case:text", "asset:missing", "保留正文"),+ entry("case:media-only", "asset:media-only", ""),+ entry("case:healthy", "asset:healthy", "健康正文")+ ],+ organizerState: { collections: [{ id: "project:one", entryIds: ["case:text", "case:media-only", "case:healthy"] }] },+ compoundCases: [{ id: "compound:one", memberEntryIds: ["case:text", "case:media-only", "case:healthy"], coverVisualId: "asset:missing" }],+ trashState: { items: [{+ id: "trash:media", kind: "media", targetId: "asset:trash-missing",+ snapshot: { mediaAssets: [{ id: "asset:trash-missing" }] },+ relationships: { entryId: "case:healthy", positions: [{ id: "asset:trash-missing", index: 0 }] }+ }] },+ creativeRuns: [{ id: "run:one", outputs: [+ { visual: { id: "asset:run-missing" } },+ { visual: { id: "asset:run-healthy" } }+ ], events: [{ visualId: "asset:run-missing" }, { visualId: "asset:run-healthy" }] }],+ creativeSkills: { items: [{ id: "skill:one", packageFiles: [+ { assetId: "asset:skill-missing" }, { assetId: "asset:skill-healthy" }+ ] }] },+ composerSessions: [{ id: "session:one", referenceSnapshots: [{+ sourceType: "temporary", entryId: "temporary:one", referenceText: "仍有文字",+ assetId: "asset:temp-missing",+ assetRefs: [{ assetId: "asset:temp-missing" }, { assetId: "asset:temp-healthy" }],+ imageRefs: [{ visualId: "asset:temp-missing" }, { visualId: "asset:temp-healthy" }],+ assets: [{ assetId: "asset:temp-missing" }, { assetId: "asset:temp-healthy" }]+ }] }]+ };+ const missing = new Set([+ "asset:missing", "asset:media-only", "asset:trash-missing", "asset:run-missing",+ "asset:skill-missing", "asset:temp-missing"+ ]);++ const result = salvageMissingLibraryAssets(state, missing);++ assert.deepEqual(result.state.entries.map((item) => item.id), ["case:text", "case:healthy"]);+ assert.deepEqual(result.state.entries[0].mediaAssets, []);+ assert.deepEqual(result.state.entries[0].facetAssignments, []);+ assert.deepEqual(result.state.organizerState.collections[0].entryIds, ["case:text", "case:healthy"]);+ assert.deepEqual(result.state.compoundCases[0].memberEntryIds, ["case:text", "case:healthy"]);+ assert.equal(result.state.compoundCases[0].coverVisualId, "");+ assert.deepEqual(result.state.trashState.items, []);+ assert.deepEqual(result.state.creativeRuns[0].outputs.map((output) => output.visual.id), ["asset:run-healthy"]);+ assert.deepEqual(result.state.creativeRuns[0].events.map((event) => event.visualId), ["asset:run-healthy"]);+ assert.deepEqual(result.state.creativeSkills.items[0].packageFiles.map((file) => file.assetId), ["asset:skill-healthy"]);+ assert.deepEqual(result.state.composerSessions[0].referenceSnapshots[0].assetRefs.map((asset) => asset.assetId), ["asset:temp-healthy"]);+ assert.equal(result.state.composerSessions[0].referenceSnapshots[0].assetId, "");+ assert.equal(result.issues.length, missing.size);+});++function entry(id, assetId, text) {+ return {+ id,+ title: text ? id : "",+ text,+ mediaAssets: [{ id: assetId, storageMode: "managed" }],+ primaryMediaId: assetId,+ facetAssignments: [{ source: "vision_model", visualId: assetId }]+ };+}diff --git a/test/library-export-plan.test.js b/test/library-export-plan.test.jsindex e9fcd86..9232490 100644--- a/test/library-export-plan.test.js+++ b/test/library-export-plan.test.js@@ -3,7 +3,11 @@ import assert from "node:assert/strict";import {buildFolderBackupCompletion,- verifyFolderBackupCompletion+ buildFolderBackupWritePlan,+ buildFolderRescueCompletion,+ inspectFolderBackupEnvelope,+ verifyFolderBackupCompletion,+ verifyFolderRescueCompletion} from "../library-export-plan.js";test("folder completion is written from actual files and rejects later byte changes", async () => {@@ -32,3 +36,126 @@ test("folder completion is written from actual files and rejects later byte chanchanged.set("images/case/image.webp", new Blob(["changed-bytes"], { type: "image/webp" }));await assert.rejects(() => verifyFolderBackupCompletion(completion, changed), /完整性校验失败/);});++test("complete backup verification ignores and reports files outside its manifest", async () => {+ const files = new Map([+ ["library.json", new Blob(["{\"entries\":[]}"], { type: "application/json" })]+ ]);+ const completion = await buildFolderBackupCompletion(files);+ const withExtra = new Map(files);+ withExtra.set("readme-from-user.txt", new Blob(["do not import"], { type: "text/plain" }));++ assert.deepEqual(await verifyFolderBackupCompletion(completion, withExtra), {+ extraPaths: ["readme-from-user.txt"]+ });+});++test("rescue backup has a distinct marker and never impersonates a complete backup", async () => {+ const files = new Map([+ ["library.json", new Blob(["{\"entries\":[]}"], { type: "application/json" })]+ ]);+ const rescue = await buildFolderRescueCompletion(files, {+ createdAt: "2026-08-27T00:00:00.000Z",+ issues: [{ code: "media_file_dropped", assetId: "image:broken", reason: "missing_file" }]+ });++ assert.equal(rescue.format, "prompt-director-folder-rescue");+ assert.equal(rescue.version, 1);+ assert.equal(rescue.status, "rescue");+ assert.equal(rescue.issues.length, 1);+ assert.notEqual(rescue.format, "prompt-director-folder-backup");+ await assert.doesNotReject(() => verifyFolderRescueCompletion(rescue, files));+ await assert.rejects(() => verifyFolderBackupCompletion(rescue, files), /完整备份标记无效/);+});++test("folder envelope keeps a valid complete backup complete while reporting extra files", async () => {+ const files = new Map([+ ["library.json", new Blob(["{\"format\":\"prompt-case-library\",\"version\":5,\"entries\":[]}"], { type: "application/json" })]+ ]);+ const completion = await buildFolderBackupCompletion(files);+ files.set("complete.json", new Blob([JSON.stringify(completion)], { type: "application/json" }));+ files.set("unlisted/private-note.txt", new Blob(["ignore me"], { type: "text/plain" }));++ const envelope = await inspectFolderBackupEnvelope(files);++ assert.equal(envelope.mode, "complete");+ assert.equal(envelope.report.status, "partial");+ assert.deepEqual(envelope.report.diagnostics, [{+ code: "extra_file_ignored",+ severity: "file",+ action: "ignored",+ path: "unlisted/private-note.txt",+ reason: "not_in_manifest"+ }]);+});++test("missing or damaged complete markers enter rescue without guessing library JSON", async () => {+ const libraryFile = new Blob(["{\"format\":\"prompt-case-library\",\"version\":5,\"entries\":[]}"], { type: "application/json" });+ const missing = await inspectFolderBackupEnvelope(new Map([["library.json", libraryFile]]));+ assert.equal(missing.mode, "rescue");+ assert.equal(missing.report.diagnostics[0].reason, "missing_complete_marker");++ const files = new Map([["library.json", libraryFile]]);+ const completion = await buildFolderBackupCompletion(files);+ completion.files[0].sha256 = "0".repeat(64);+ files.set("complete.json", new Blob([JSON.stringify(completion)], { type: "application/json" }));+ const damaged = await inspectFolderBackupEnvelope(files);+ assert.equal(damaged.mode, "rescue");+ assert.equal(damaged.report.diagnostics[0].reason, "complete_integrity_failure");+ await assert.rejects(+ () => inspectFolderBackupEnvelope(new Map([["complete.json", files.get("complete.json")]])),+ /缺少 library.json/+ );+});++test("a future folder marker asks for an application update instead of entering rescue", async () => {+ const files = new Map([+ ["library.json", new Blob(["{\"format\":\"prompt-case-library\",\"version\":5,\"entries\":[]}"], { type: "application/json" })],+ ["complete.json", new Blob([JSON.stringify({+ format: "prompt-director-folder-backup",+ version: 99,+ files: []+ })], { type: "application/json" })]+ ]);++ await assert.rejects(() => inspectFolderBackupEnvelope(files), /更新 PromptDirector/);+});++test("write plan chooses exactly one honest marker after preflight", async () => {+ const files = new Map([+ ["library.json", new Blob(["{\"entries\":[]}"], { type: "application/json" })]+ ]);+ const metadata = {+ createdAt: "2026-08-27T00:00:00.000Z",+ caseCount: 0,+ mediaCount: 0,+ byteSize: 0+ };+ const complete = await buildFolderBackupWritePlan({+ files,+ report: { status: "ready", diagnostics: [], stats: {} },+ metadata+ });+ const issue = {+ code: "media_file_dropped",+ severity: "media",+ action: "dropped",+ assetId: "image:missing",+ reason: "missing_file"+ };+ const rescue = await buildFolderBackupWritePlan({+ files,+ report: { status: "partial", diagnostics: [issue], stats: { droppedMediaFiles: 1 } },+ metadata+ });++ assert.equal(complete.mode, "complete");+ assert.equal(complete.markerPath, "complete.json");+ assert.equal(complete.marker.format, "prompt-director-folder-backup");+ assert.equal(rescue.mode, "rescue");+ assert.equal(rescue.markerPath, "rescue.json");+ assert.equal(rescue.marker.format, "prompt-director-folder-rescue");+ assert.deepEqual(rescue.marker.issues, [issue]);+ assert.equal(complete.files.has("rescue.json"), false);+ assert.equal(rescue.files.has("complete.json"), false);+});diff --git a/test/library-import-background.test.js b/test/library-import-background.test.jsindex bdf964b..66c0616 100644--- a/test/library-import-background.test.js+++ b/test/library-import-background.test.js@@ -11,9 +11,13 @@ test("library import commits business data and its completed receipt atomically");assert.match(apply, /claimLibraryImportTransaction/);+ assert.match(apply, /planValue:\s*message\.plan/);+ assert.match(apply, /planLibraryTransfer\(/);+ assert.match(apply, /sourceType:\s*message\.plan\?\.sourceType/);+ assert.match(apply, /result\.planToken\s*!==\s*message\.planToken/);assert.match(apply, /IMPORT_TRANSACTION_PENDING/);assert.match(apply, /succeedLibraryImportTransaction/);assert.match(apply, /\[STORAGE_KEYS\.libraryImportTransactions\]:\s*completed\.state/);- assert.match(apply, /await commitLocalChanges\(\{[\s\S]*storagePayload\(result\.state\)[\s\S]*completed\.state/);+ assert.match(apply, /await commitLocalChanges\(\{[\s\S]*storagePayload\(result\.targetState\)[\s\S]*completed\.state/);assert.match(apply, /failLibraryImportTransaction/);});diff --git a/test/library-import-dedup.test.js b/test/library-import-dedup.test.jsindex cb87247..9a93722 100644--- a/test/library-import-dedup.test.js+++ b/test/library-import-dedup.test.js@@ -141,7 +141,7 @@ test("reimporting an already remapped source version reuses that copy instead ofassert.equal(third.entryIdMap["source-entry"], second.entryIdMap["source-entry"]);});-test("different source identities remain separate even when their content is identical", () => {+test("different source ids reuse one case when their complete semantic content is identical", () => {const first = mergeLibraryPackage(emptyLibrary(), portablePackage([portableEntry("source-a")]));@@ -149,10 +149,10 @@ test("different source identities remain separate even when their content is ideportableEntry("source-b")]));- assert.equal(second.state.entries.length, 2);- assert.equal(second.importedCount, 1);- assert.equal(second.skippedCount, 0);- assert.equal(second.entryIdMap["source-b"], "source-b");+ assert.equal(second.state.entries.length, 1);+ assert.equal(second.importedCount, 0);+ assert.equal(second.skippedCount, 1);+ assert.equal(second.entryIdMap["source-b"], "source-a");});test("identical managed media is reused by content hash even though archive paths are receiver-local", () => {diff --git a/test/library-import-dialog.test.js b/test/library-import-dialog.test.jsindex 403f659..8cf9892 100644--- a/test/library-import-dialog.test.js+++ b/test/library-import-dialog.test.js@@ -32,3 +32,20 @@ test("import report separates created, identical, repaired, and skipped results"]);assert.equal(report.autoAnalysisNotice, "导入不会自动启动 AI 分析");});++test("rescue report makes degraded integrity and ignored extra files visible before confirmation", () => {+ const report = buildLibraryImportReport({+ importedCount: 2,+ importDiagnostics: [+ { code: "backup_integrity_degraded", reason: "missing_complete_marker" },+ { code: "extra_file_ignored", path: "unlisted.txt" }+ ],+ importStats: {}+ });++ assert.equal(report.status, "partial");+ assert.deepEqual(report.lines, [+ "完整性标记异常,本次只能按救援方案恢复",+ "忽略清单外文件 1 项"+ ]);+});diff --git a/test/library-import-media.test.js b/test/library-import-media.test.jsindex 2de8433..cbcfa32 100644--- a/test/library-import-media.test.js+++ b/test/library-import-media.test.js@@ -2,7 +2,7 @@ import test from "node:test";import assert from "node:assert/strict";import {- filesWithoutInvalidEntryMedia,+ filesWithoutInvalidLibraryImages,findInvalidImportedImageIds} from "../library-import-media.js";@@ -46,10 +46,47 @@ test("shared ZIP salvage removes only archive files belonging to undecodable ent}]};- const salvageFiles = filesWithoutInvalidEntryMedia(library, files, new Set(["image:bad"]));+ const salvageFiles = filesWithoutInvalidLibraryImages(library, files, new Set(["image:bad"]));assert.equal(salvageFiles.has("images/bad.webp"), false);assert.equal(salvageFiles.get("images/good.webp"), files.get("images/good.webp"));assert.equal(salvageFiles.get("library.json"), files.get("library.json"));assert.equal(files.has("images/bad.webp"), true);});++test("rescue validation removes undecodable images from every private backup scope", () => {+ const paths = [+ "images/active.webp",+ "images/trash.webp",+ "creative-results/run/result.webp",+ "temp-references/session/temp.webp"+ ];+ const files = new Map(paths.map((path) => [path, new Blob([path], { type: "image/webp" })]));+ const library = {+ entries: [{ id: "case:active", mediaAssets: [{ id: "image:active", assetPath: paths[0] }] }],+ trashState: {+ items: [{+ kind: "entry",+ snapshot: { mediaAssets: [{ id: "image:trash", assetPath: paths[1] }] }+ }]+ },+ creativeRuns: [{+ outputs: [{ visual: { id: "image:creative", assetPath: paths[2] } }]+ }],+ composerSessions: [{+ referenceSnapshots: [{+ sourceType: "temporary",+ assetRefs: [{ assetId: "image:temporary", archivePath: paths[3] }]+ }]+ }]+ };++ const salvageFiles = filesWithoutInvalidLibraryImages(+ library,+ files,+ new Set(["image:active", "image:trash", "image:creative", "image:temporary"])+ );++ assert.deepEqual([...salvageFiles.keys()], []);+ assert.equal(files.size, 4);+});diff --git a/test/library-import-transaction.test.js b/test/library-import-transaction.test.jsindex 9db2d3b..9024bf0 100644--- a/test/library-import-transaction.test.js+++ b/test/library-import-transaction.test.js@@ -32,6 +32,36 @@ test("plan tokens ignore sync status, undo, and job noise but still react to liv});});+test("plan tokens bind the confirmed recovery choices and resource mappings", () => {+ const source = makeImportSource();+ const before = makeCurrentLibrary();+ const plan = {+ mode: "merge",+ preserveLibraryConfiguration: true,+ libraryAddedAt: "2026-08-27T08:00:00.000Z",+ importBatchId: "library-import:bound-plan",+ mappings: { entryIds: { source: "entry:copy" } },+ resourceWrites: [{ sourceId: "image:source", targetId: "image:copy", resourceType: "media" }]+ };+ const token = createLibraryImportPlanToken(before, source, plan);++ assert.doesNotThrow(() => assertLibraryImportPlanCurrent(token, before, source, plan));+ assert.throws(() => assertLibraryImportPlanCurrent(token, before, source, {+ ...plan,+ preserveLibraryConfiguration: false+ }), (error) => {+ assert.equal(error.code, "IMPORT_PLAN_STALE");+ return true;+ });+ assert.throws(() => assertLibraryImportPlanCurrent(token, before, source, {+ ...plan,+ resourceWrites: [{ sourceId: "image:source", targetId: "image:other", resourceType: "media" }]+ }), (error) => {+ assert.equal(error.code, "IMPORT_PLAN_STALE");+ return true;+ });+});+test("a completed apply is replayed for the same operationId and planToken without calling the writer again", () => {const source = makeImportSource();const before = makeCurrentLibrary();diff --git a/test/library-package-salvage.test.js b/test/library-package-salvage.test.jsindex 313725e..aff7034 100644--- a/test/library-package-salvage.test.js+++ b/test/library-package-salvage.test.js@@ -5,6 +5,7 @@ import { createDefaultFacetCatalog } from "../facets.js";import { mergeLibraryPackage, parseCompleteFolderBackup, parseLibraryPackage } from "../library-package.js";import { SCHEMA_VERSION, createDefaultTaxonomy } from "../taxonomy.js";import { restoreTrashItems } from "../trash.js";+import { createComposerSession } from "../composer.js";test("salvage mode drops one missing media file without blocking recoverable cases", () => {const source = packageValue([@@ -133,6 +134,110 @@ test("salvage mode skips a media-only case when its last recoverable file is bro});});+test("rescue mode isolates broken private resources without leaving placeholders", () => {+ const source = packageValue([entry("case:healthy")]);+ source.trashState = {+ version: 1,+ items: [{+ id: "trash:entry:case:trashed",+ kind: "entry",+ targetId: "case:trashed",+ deletedAt: "2026-08-27T00:00:00.000Z",+ snapshot: entry("case:trashed", {+ text: "仍可恢复的回收站正文",+ mediaAssets: [image("image:trash-missing")],+ primaryMediaId: "image:trash-missing"+ }),+ relationships: { collections: [] }+ }]+ };+ source.composerSessions = [createComposerSession({+ id: "session:rescue",+ referenceSnapshots: [{+ entryId: "temp-reference:rescue",+ alias: "@参考1",+ title: "缺失临时图片",+ sourceType: "temporary",+ referenceKind: "reference",+ referenceText: "仍保留的文字参考",+ imageRefs: [{ visualId: "temp-asset:missing", mimeType: "image/webp" }],+ assetRefs: [{+ assetId: "temp-asset:missing",+ kind: "image",+ mimeType: "image/webp",+ name: "missing.webp",+ byteSize: 5,+ archivePath: "temp-references/session-rescue/missing.webp"+ }]+ }]+ })];+ source.creativeRuns = [{+ id: "run:rescue",+ sessionId: "session:rescue",+ promptVersionId: "prompt:rescue",+ promptText: "仍保留的历史提示词",+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+ outputs: [{+ visual: {+ id: "creative:missing",+ kind: "image",+ mimeType: "image/webp",+ byteSize: 5,+ capturedAt: "2026-08-27T00:00:00.000Z",+ assetPath: "creative-results/run-rescue/missing.webp"+ },+ capturedAt: "2026-08-27T00:00:00.000Z",+ signals: [{ type: "captured", at: "2026-08-27T00:00:00.000Z" }]+ }]+ }];+ source.creativeSkills = {+ version: 1,+ items: [{+ id: "skill:rescue",+ callName: "救援方法",+ portableId: "rescue-method",+ description: "方法正文仍可恢复",+ currentVersionId: "skill-version:rescue",+ versions: [{+ id: "skill-version:rescue",+ createdAt: "2026-08-27T00:00:00.000Z",+ reason: "imported",+ source: "imported",+ skillMarkdown: "# 救援方法",+ references: [],+ provenanceMarkdown: ""+ }],+ packageFiles: [{+ path: "SKILL.md",+ assetId: "skill-file:missing",+ byteSize: 5,+ mimeType: "text/markdown",+ archivePath: "skills/rescue-method/skill-file-missing/SKILL.md"+ }],+ textModeConfirmed: false,+ runtimeDependencies: [],+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z"+ }]+ };++ const parsed = parseLibraryPackage(source, new Map(), { salvageInvalidMedia: true });++ assert.deepEqual(parsed.trashState.items[0].snapshot.mediaAssets, []);+ assert.equal(parsed.trashState.items[0].snapshot.text, "仍可恢复的回收站正文");+ assert.deepEqual(parsed.composerSessions[0].referenceSnapshots[0].assetRefs, []);+ assert.deepEqual(parsed.composerSessions[0].referenceSnapshots[0].imageRefs, []);+ assert.equal(parsed.composerSessions[0].referenceSnapshots[0].referenceText, "仍保留的文字参考");+ assert.deepEqual(parsed.creativeRuns[0].outputs, []);+ assert.equal(parsed.creativeRuns[0].promptText, "仍保留的历史提示词");+ assert.deepEqual(parsed.creativeSkills.items[0].packageFiles, []);+ assert.match(JSON.stringify(parsed.importDiagnostics), /trash_media_dropped/);+ assert.match(JSON.stringify(parsed.importDiagnostics), /temporary_asset_dropped/);+ assert.match(JSON.stringify(parsed.importDiagnostics), /creative_output_dropped/);+ assert.match(JSON.stringify(parsed.importDiagnostics), /skill_file_dropped/);+});+test("complete folder backup parsing stays strict even if a caller requests ZIP media salvage", async () => {const source = packageValue([entry("case:strict", {mediaAssets: [image("image:strict-missing")],diff --git a/test/library-recovery-point.test.js b/test/library-recovery-point.test.jsnew file mode 100644index 0000000..96b69ef--- /dev/null+++ b/test/library-recovery-point.test.js@@ -0,0 +1,71 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ createLibraryReplacementRecoveryPoint,+ normalizeLibraryReplacementRecoveryPoint,+ obsoleteRecoveryAssetIds,+ swapLibraryReplacementRecoveryPoint+} from "../library-recovery-point.js";++test("a replacement recovery point snapshots managed state and retained media without sharing references", () => {+ const current = managedState("local");+ const point = createLibraryReplacementRecoveryPoint(current, {+ id: "recovery:one",+ createdAt: "2026-08-28T00:10:00.000Z",+ retainedAssetIds: ["media:local", "media:local"]+ });+ current.entries[0].text = "后来修改";++ assert.equal(point.state.entries[0].text, "local");+ assert.deepEqual(point.retainedAssetIds, ["media:local"]);+ assert.deepEqual(normalizeLibraryReplacementRecoveryPoint(point), point);+});++test("rolling back swaps the saved state and keeps the replaced state as the next recovery point", () => {+ const current = managedState("after replace");+ const previous = createLibraryReplacementRecoveryPoint(managedState("before replace"), {+ id: "recovery:previous",+ createdAt: "2026-08-28T00:10:00.000Z",+ retainedAssetIds: ["media:before"]+ });++ const swapped = swapLibraryReplacementRecoveryPoint(current, previous, {+ id: "recovery:after",+ createdAt: "2026-08-28T00:20:00.000Z",+ retainedAssetIds: ["media:after"]+ });++ assert.equal(swapped.targetState.entries[0].text, "before replace");+ assert.equal(swapped.recoveryPoint.state.entries[0].text, "after replace");+ assert.deepEqual(swapped.recoveryPoint.retainedAssetIds, ["media:after"]);+});++test("a later exact replace cleans only assets no longer referenced by the live library or newest recovery point", () => {+ const previous = createLibraryReplacementRecoveryPoint(managedState("old"), {+ retainedAssetIds: ["media:old-only", "media:shared"]+ });+ const next = createLibraryReplacementRecoveryPoint(managedState("current"), {+ retainedAssetIds: ["media:current", "media:shared"]+ });++ assert.deepEqual(obsoleteRecoveryAssetIds(previous, ["media:new-live"], next), ["media:old-only"]);+});++function managedState(text) {+ return {+ entries: [{ id: `case:${text}`, text, mediaAssets: [], primaryMediaId: "" }],+ trashState: { version: 1, items: [] },+ organizerState: { version: 1, collections: [] },+ compoundCases: [],+ settings: {},+ taxonomy: { version: 1, nodes: [] },+ facetCatalog: { version: 1, facets: [], nodes: [] },+ classificationRules: [],+ composerSettings: {},+ composerSessions: [],+ creativeExperimentSettings: {},+ creativeRuns: [],+ creativeSkills: { version: 1, items: [] }+ };+}diff --git a/test/library-semantic-identity.test.js b/test/library-semantic-identity.test.jsnew file mode 100644index 0000000..05b3c9a--- /dev/null+++ b/test/library-semantic-identity.test.js@@ -0,0 +1,75 @@+import test from "node:test";+import assert from "node:assert/strict";++import { reconcileLibrarySemanticIdentity } from "../library-semantic-identity.js";++test("complete semantic duplicates converge to one stable case and keep every project relationship", () => {+ const first = semanticEntry("case:a", "asset:a", "a".repeat(64));+ const duplicate = semanticEntry("case:b", "asset:b", "a".repeat(64));+ first.creationMeta = { sourceEntryIds: ["case:a"] };+ duplicate.creationMeta = { sourceEntryIds: ["case:b"] };+ const distinct = semanticEntry("case:c", "asset:c", "c".repeat(64));+ distinct.title = "Distinct";+ distinct.text = "Distinct";+ const result = reconcileLibrarySemanticIdentity({+ entries: [duplicate, distinct, first],+ organizerState: { collections: [+ { id: "project:a", entryIds: ["case:a"] },+ { id: "project:b", entryIds: ["case:b"] }+ ] },+ compoundCases: [{+ id: "compound:one",+ memberEntryIds: ["case:b", "case:c"],+ coverVisualId: "asset:b"+ }],+ composerSessions: [{+ id: "session:one",+ referenceSnapshots: [{+ referenceId: "case:b:asset:b",+ entryId: "case:b",+ assetRefs: [{ assetId: "asset:b" }]+ }]+ }]+ });++ assert.equal(result.changed, true);+ assert.deepEqual(result.state.entries.map((entry) => entry.id), ["case:a", "case:c"]);+ assert.deepEqual(result.state.organizerState.collections.map((project) => project.entryIds), [+ ["case:a"],+ ["case:a"]+ ]);+ assert.deepEqual(result.state.compoundCases[0].memberEntryIds, ["case:a", "case:c"]);+ assert.equal(result.state.compoundCases[0].coverVisualId, "asset:a");+ assert.equal(result.state.composerSessions[0].referenceSnapshots[0].entryId, "case:a");+ assert.equal(result.state.composerSessions[0].referenceSnapshots[0].referenceId, "case:a:asset:a");+ assert.equal(result.state.composerSessions[0].referenceSnapshots[0].assetRefs[0].assetId, "asset:a");+ assert.deepEqual(result.entryIdMap, { "case:b": "case:a" });+ assert.deepEqual(result.assetIdMap, { "asset:b": "asset:a" });+});++test("uncertain cases without complete managed-media hashes are never deduplicated", () => {+ const result = reconcileLibrarySemanticIdentity({+ entries: [semanticEntry("case:a", "asset:a", ""), semanticEntry("case:b", "asset:b", "")]+ });++ assert.equal(result.changed, false);+ assert.deepEqual(result.state.entries.map((entry) => entry.id), ["case:a", "case:b"]);+});++function semanticEntry(id, assetId, contentHash) {+ return {+ id,+ title: "Same",+ text: "Same",+ mediaAssets: [{+ id: assetId,+ kind: "image",+ usage: "content",+ storageMode: "managed",+ mimeType: "image/webp",+ byteSize: 1,+ ...(contentHash ? { contentHash } : {})+ }],+ primaryMediaId: assetId+ };+}diff --git a/test/library-transfer.test.js b/test/library-transfer.test.jsnew file mode 100644index 0000000..86eefa7--- /dev/null+++ b/test/library-transfer.test.js@@ -0,0 +1,757 @@+import test from "node:test";+import assert from "node:assert/strict";++import { createDefaultFacetCatalog } from "../facets.js";+import { createDefaultTaxonomy, SCHEMA_VERSION } from "../taxonomy.js";+import {+ LIBRARY_TRANSFER_MODES,+ LIBRARY_TRANSFER_SOURCES,+ inspectLibraryTransfer,+ libraryTransferWriteBytes,+ planLibraryTransfer+} from "../library-transfer.js";++test("ZIP and complete-folder adapters produce one canonical inspected transfer", async () => {+ const source = portablePackage([portableEntry("case:one", "image:one")]);+ const files = new Map([[+ "images/case-one/image-one.webp",+ new Blob(["good"], { type: "image/webp" })+ ]]);++ const shared = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library: source,+ files+ });+ const complete = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files+ });++ assert.deepEqual(shared.state, complete.state);+ assert.deepEqual(shared.report, complete.report);+ assert.deepEqual([...shared.resources.assets.keys()], ["image:one"]);+ assert.deepEqual([...complete.resources.assets.keys()], ["image:one"]);+ assert.equal("assets" in shared.state, false);+ assert.equal("images" in shared.state, false);+ assert.equal("skillAssets" in shared.state, false);+ assert.deepEqual(shared.report.stats, {+ inputCases: 1,+ keptCases: 1,+ skippedCases: 0,+ droppedAiAssignments: 0,+ droppedMediaDescriptors: 0,+ droppedMediaFiles: 0,+ droppedTrashMedia: 0,+ droppedTemporaryAssets: 0,+ droppedCreativeOutputs: 0,+ droppedSkillFiles: 0+ });+});++test("shared inspection isolates an undecodable image without blocking healthy cases", async () => {+ const good = new Blob(["good"], { type: "image/webp" });+ const broken = new Blob(["bad!"], { type: "image/webp" });+ const source = portablePackage([+ portableEntry("case:good", "image:good"),+ portableEntry("case:broken", "image:broken")+ ]);+ const files = new Map([+ ["images/case-good/image-good.webp", good],+ ["images/case-broken/image-broken.webp", broken]+ ]);++ const inspected = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library: source,+ files,+ validateImage: async (blob) => {+ if (blob === broken) throw new Error("decoder rejected bytes");+ }+ });++ assert.deepEqual(inspected.state.entries.map((entry) => entry.id), ["case:good", "case:broken"]);+ assert.deepEqual(inspected.state.entries[0].mediaAssets.map((asset) => asset.id), ["image:good"]);+ assert.deepEqual(inspected.state.entries[1].mediaAssets, []);+ assert.equal(inspected.state.entries[1].text, "正文");+ assert.deepEqual([...inspected.resources.assets.keys()], ["image:good"]);+ assert.equal(inspected.report.stats.droppedMediaFiles, 1);+ assert.deepEqual(inspected.report.diagnostics.filter(({ code }) => code === "media_file_dropped"), [{+ code: "media_file_dropped",+ severity: "media",+ action: "dropped",+ entryId: "case:broken",+ assetId: "image:broken",+ path: "images/case-broken/image-broken.webp",+ reason: "decode_failure"+ }]);+});++test("complete-backup inspection degrades to rescue and isolates an undecodable core image", async () => {+ const source = portablePackage([portableEntry("case:broken", "image:broken")]);+ const broken = new Blob(["bad!"], { type: "image/webp" });++ const inspected = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files: new Map([["images/case-broken/image-broken.webp", broken]]),+ validateImage: async () => {+ throw new Error("decoder rejected bytes");+ }+ });++ assert.equal(inspected.sourceType, LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP);+ assert.equal(inspected.report.status, "partial");+ assert.deepEqual(inspected.state.entries.map((entry) => entry.id), ["case:broken"]);+ assert.deepEqual(inspected.state.entries[0].mediaAssets, []);+ assert.equal(inspected.state.entries[0].text, "正文");+ assert.deepEqual(inspected.report.diagnostics.map((item) => item.code), [+ "backup_integrity_degraded",+ "media_file_dropped"+ ]);+ assert.throws(() => planLibraryTransfer({+ currentState: portablePackage([]),+ inspection: inspected,+ options: { mode: LIBRARY_TRANSFER_MODES.EXACT_REPLACE }+ }), /救援备份只能安全合并/);+});++test("complete-backup inspection drops one invalid descriptor and keeps the healthy case", async () => {+ const source = portablePackage([+ portableEntry("case:healthy", "image:healthy"),+ portableEntry("case:invalid", "image:invalid")+ ]);+ source.entries[1].mediaAssets[0].assetPath = "../unsafe/image-invalid.webp";+ const inspected = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files: new Map([["images/case-healthy/image-healthy.webp", new Blob(["good"], { type: "image/webp" })]])+ });++ assert.equal(inspected.sourceType, LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP);+ assert.deepEqual(inspected.state.entries.map((entry) => entry.id), ["case:healthy", "case:invalid"]);+ assert.deepEqual(inspected.state.entries[1].mediaAssets, []);+ assert.equal(inspected.report.stats.droppedMediaDescriptors, 1);+});++test("an unexpected strict parser fault is never disguised as rescue content loss", async () => {+ const source = portablePackage([portableEntry("case:healthy", "image:healthy")]);+ let faultInjected = false;+ const limits = new Proxy({}, {+ get() {+ if (!faultInjected) {+ faultInjected = true;+ throw new Error("unexpected parser fault");+ }+ return undefined;+ }+ });++ await assert.rejects(() => inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files: new Map([["images/case-healthy/image-healthy.webp", new Blob(["good"], { type: "image/webp" })]]),+ limits+ }), /unexpected parser fault/);+});++test("rescue-backup inspection keeps healthy content and merges envelope diagnostics", async () => {+ const source = portablePackage([+ portableEntry("case:good", "image:good"),+ portableEntry("case:missing", "image:missing")+ ]);+ const inspected = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP,+ library: source,+ files: new Map([[+ "images/case-good/image-good.webp",+ new Blob(["good"], { type: "image/webp" })+ ]]),+ sourceReport: {+ status: "partial",+ diagnostics: [{+ code: "backup_integrity_degraded",+ severity: "backup",+ action: "rescue",+ reason: "missing_complete_marker"+ }],+ stats: {}+ }+ });++ assert.deepEqual(inspected.state.entries.map((entry) => entry.id), ["case:good", "case:missing"]);+ assert.deepEqual(inspected.state.entries[1].mediaAssets, []);+ assert.deepEqual([...inspected.resources.assets.keys()], ["image:good"]);+ assert.deepEqual(inspected.report.diagnostics.map((item) => item.code), [+ "backup_integrity_degraded",+ "media_file_dropped"+ ]);+ assert.equal("importDiagnostics" in inspected.state, false);+ assert.equal("recoveryStatus" in inspected.state, false);+});++test("rescue image decoding isolates a broken private creative result", async () => {+ const source = portablePackage([portableEntry("case:good", "image:good")]);+ source.creativeRuns = [{+ id: "run:broken-image",+ sessionId: "session:broken-image",+ promptVersionId: "prompt:broken-image",+ promptText: "保留历史提示词",+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+ outputs: [{+ visual: {+ id: "creative:broken-image",+ kind: "image",+ mimeType: "image/webp",+ byteSize: 4,+ capturedAt: "2026-08-27T00:00:00.000Z",+ assetPath: "creative-results/run-broken/creative-broken.webp"+ },+ capturedAt: "2026-08-27T00:00:00.000Z",+ signals: [{ type: "captured", at: "2026-08-27T00:00:00.000Z" }]+ }]+ }];+ const good = new Blob(["good"], { type: "image/webp" });+ const broken = new Blob(["bad!"], { type: "image/webp" });++ const inspected = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP,+ library: source,+ files: new Map([+ ["images/case-good/image-good.webp", good],+ ["creative-results/run-broken/creative-broken.webp", broken]+ ]),+ validateImage: async (blob) => {+ if (blob === broken) throw new Error("decoder rejected bytes");+ }+ });++ assert.deepEqual(inspected.state.creativeRuns[0].outputs, []);+ assert.equal(inspected.state.creativeRuns[0].promptText, "保留历史提示词");+ assert.deepEqual(inspected.report.diagnostics.find((item) => item.assetId === "creative:broken-image"), {+ code: "creative_output_dropped",+ severity: "media",+ action: "dropped",+ assetId: "creative:broken-image",+ path: "creative-results/run-broken/creative-broken.webp",+ reason: "decode_failure"+ });+});++test("a transfer plan binds collision mappings resources and receiver-local metadata", async () => {+ const source = portablePackage([portableEntry("case:one", "image:one")]);+ source.organizerState.collections = [{+ id: "collection:one",+ name: "来源项目",+ parentId: null,+ order: 0,+ entryIds: ["case:one"]+ }];+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library: source,+ files: new Map([[+ "images/case-one/image-one.webp",+ new Blob(["good"], { type: "image/webp" })+ ]])+ });+ const current = portablePackage([{+ ...portableEntry("case:one", "image:local"),+ title: "本机已有的不同案例",+ text: "本机正文"+ }]);+ current.organizerState.collections = [{+ id: "collection:one",+ name: "本机项目",+ parentId: null,+ order: 0,+ entryIds: ["case:one"]+ }];++ const first = planLibraryTransfer({+ currentState: current,+ inspection,+ options: {+ preserveLibraryConfiguration: true,+ now: "2026-08-27T08:00:00.000Z",+ importBatchId: "library-import:test-plan",+ conflictResolutions: { "case:one": "keep-both" }+ }+ });+ const replay = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { preferredPlan: first.context }+ });++ assert.equal(first.targetState.entries.length, 2);+ assert.notEqual(first.mappings.entryIds["case:one"], "case:one");+ assert.notEqual(first.mappings.collectionIds["collection:one"], "collection:one");+ assert.deepEqual(first.resourceWrites, [{+ sourceId: "image:one",+ targetId: first.mappings.visualIds["image:one"],+ resourceType: "media"+ }]);+ assert.equal(first.context.libraryAddedAt, "2026-08-27T08:00:00.000Z");+ assert.equal(first.context.importBatchId, "library-import:test-plan");+ assert.deepEqual(replay.targetState, first.targetState);+ assert.equal(replay.planToken, first.planToken);+});++test("a confirmed plan reuses facet and tag collision mappings", async () => {+ const source = portablePackage([portableEntry("case:source", "image:source")]);+ source.facetCatalog = catalogWithCollision("来源维度", "来源标签");+ source.entries[0].facetAssignments = [{+ facetId: "facet:collision",+ nodeId: "tag:collision",+ status: "confirmed",+ source: "manual"+ }];+ const current = portablePackage([]);+ current.facetCatalog = catalogWithCollision("本机维度", "本机标签");+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library: source,+ files: new Map([[+ "images/case-source/image-source.webp",+ new Blob(["good"], { type: "image/webp" })+ ]])+ });++ const first = planLibraryTransfer({+ currentState: current,+ inspection,+ options: {+ preserveLibraryConfiguration: true,+ now: "2026-08-27T08:30:00.000Z",+ importBatchId: "library-import:facet-plan"+ }+ });+ const replay = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { preferredPlan: first.context }+ });++ assert.notEqual(first.mappings.facetIds["facet:collision"], "facet:collision");+ assert.notEqual(first.mappings.nodeIds["tag:collision"], "tag:collision");+ assert.deepEqual(replay.targetState, first.targetState);+ assert.equal(replay.planToken, first.planToken);+});++test("a confirmed plan reuses trash identity mappings", async () => {+ const source = portablePackage([portableEntry("case:source", "image:source")]);+ source.trashState.items = [trashedEntry("case:trash", "来源回收站案例")];+ const current = portablePackage([portableEntry("case:current", "image:current")]);+ current.trashState.items = [trashedEntry("case:trash", "本机回收站案例")];+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,+ library: source,+ files: new Map([[+ "images/case-source/image-source.webp",+ new Blob(["good"], { type: "image/webp" })+ ]])+ });++ const first = planLibraryTransfer({+ currentState: current,+ inspection,+ options: {+ preserveLibraryConfiguration: true,+ now: "2026-08-27T09:00:00.000Z",+ importBatchId: "library-import:trash-plan"+ }+ });+ const replay = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { preferredPlan: first.context }+ });++ assert.notEqual(first.mappings.trashEntryIds["case:trash"], "case:trash");+ assert.deepEqual(replay.targetState, first.targetState);+ assert.equal(replay.planToken, first.planToken);+});++test("a confirmed plan reuses Skill version mappings", async () => {+ const source = portablePackage([portableEntry("case:source", "image:source")]);+ source.creativeSkills = { version: 1, items: [portableSkill("skill:source", "skill-file:source", "来源方法")] };+ const appliedSkill = {+ skillId: "skill:source",+ versionId: "skill-version:collision",+ callName: "来源方法",+ portableId: "skill-source",+ description: "可恢复方法",+ skillMarkdown: "# 方法",+ references: [],+ source: "imported",+ textMode: false+ };+ source.composerSessions = [{+ id: "session:source",+ title: "使用来源方法的草稿",+ appliedSkills: [appliedSkill],+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z"+ }];+ source.creativeRuns = [{+ id: "run:source",+ sessionId: "session:source",+ promptVersionId: "prompt:source",+ promptText: "保留方法关系",+ appliedSkills: [appliedSkill],+ outputs: [],+ createdAt: "2026-08-27T00:01:00.000Z",+ updatedAt: "2026-08-27T00:01:00.000Z"+ }];+ const current = portablePackage([portableEntry("case:current", "image:current")]);+ current.creativeSkills = { version: 1, items: [portableSkill("skill:current", "skill-file:current", "本机方法")] };+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files: new Map([+ ["images/case-source/image-source.webp", new Blob(["good"], { type: "image/webp" })],+ ["skills/source/SKILL.md", new Blob(["skill"], { type: "text/markdown" })]+ ])+ });++ const first = planLibraryTransfer({+ currentState: current,+ inspection,+ options: {+ preserveLibraryConfiguration: true,+ now: "2026-08-27T09:30:00.000Z",+ importBatchId: "library-import:skill-plan"+ }+ });+ const replay = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { preferredPlan: first.context }+ });++ assert.notEqual(first.mappings.skillVersionIds["skill-version:collision"], "skill-version:collision");+ assert.equal(first.targetState.composerSessions[0].appliedSkills[0].skillId, first.mappings.skillIds["skill:source"]);+ assert.equal(first.targetState.composerSessions[0].appliedSkills[0].versionId, first.mappings.skillVersionIds["skill-version:collision"]);+ assert.equal(first.targetState.creativeRuns[0].appliedSkills[0].skillId, first.mappings.skillIds["skill:source"]);+ assert.equal(first.targetState.creativeRuns[0].appliedSkills[0].versionId, first.mappings.skillVersionIds["skill-version:collision"]);+ assert.deepEqual(replay.targetState, first.targetState);+ assert.equal(replay.planToken, first.planToken);+});++test("safe merge keeps the local version of a same-id conflict until the user chooses otherwise", async () => {+ const current = portablePackage([portableTextEntry("case:shared", "本机修改")]);+ const source = portablePackage([portableTextEntry("case:shared", "备份修改")]);+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source+ });++ const plan = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { mode: LIBRARY_TRANSFER_MODES.SAFE_MERGE }+ });++ assert.equal(plan.context.mode, LIBRARY_TRANSFER_MODES.SAFE_MERGE);+ assert.equal(plan.targetState.entries.length, 1);+ assert.equal(plan.targetState.entries[0].text, "本机修改");+ assert.deepEqual(plan.conflicts, [{+ entryId: "case:shared",+ localTitle: "可恢复案例",+ incomingTitle: "可恢复案例",+ resolution: "keep-local"+ }]);+});++test("safe merge can adopt the incoming conflict and move that case to the incoming project structure", async () => {+ const current = portablePackage([portableTextEntry("case:shared", "本机修改")]);+ current.organizerState.collections = [{+ id: "collection:local",+ name: "本机项目",+ parentId: null,+ order: 0,+ entryIds: ["case:shared"]+ }];+ const source = portablePackage([portableTextEntry("case:shared", "备份修改")]);+ source.organizerState.collections = [{+ id: "collection:incoming",+ name: "备份项目",+ parentId: null,+ order: 0,+ entryIds: ["case:shared"]+ }];+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source+ });++ const plan = planLibraryTransfer({+ currentState: current,+ inspection,+ options: {+ mode: LIBRARY_TRANSFER_MODES.SAFE_MERGE,+ conflictResolutions: { "case:shared": "use-incoming" }+ }+ });++ assert.equal(plan.targetState.entries.length, 1);+ assert.equal(plan.targetState.entries[0].text, "备份修改");+ assert.deepEqual(+ plan.targetState.organizerState.collections.map((collection) => [collection.name, collection.entryIds]),+ [["本机项目", []], ["备份项目", ["case:shared"]]]+ );+ assert.equal(plan.conflicts[0].resolution, "use-incoming");+});++test("safe merge deduplicates identical meaning across different ids and combines project membership", async () => {+ const currentInspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: portablePackage([portableTextEntry("case:local", "同一内容")])+ });+ const current = currentInspection.state;+ current.organizerState.collections = [{+ id: "collection:local",+ name: "本机项目",+ parentId: null,+ order: 0,+ entryIds: ["case:local"]+ }];+ const source = portablePackage([portableTextEntry("case:incoming", "同一内容")]);+ source.organizerState.collections = [{+ id: "collection:incoming",+ name: "备份项目",+ parentId: null,+ order: 0,+ entryIds: ["case:incoming"]+ }];+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source+ });++ const plan = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { mode: LIBRARY_TRANSFER_MODES.SAFE_MERGE }+ });++ assert.equal(plan.targetState.entries.length, 1);+ assert.equal(plan.mappings.entryIds["case:incoming"], "case:local");+ assert.deepEqual(+ plan.targetState.organizerState.collections.map((collection) => collection.entryIds),+ [["case:local"], ["case:local"]]+ );+});++test("exact replace uses only backup-managed data and stages every incoming resource under an isolated id", async () => {+ const current = portablePackage([portableEntry("case:local", "image:local")]);+ const source = portablePackage([portableEntry("case:backup", "image:backup")]);+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,+ library: source,+ files: new Map([[+ "images/case-backup/image-backup.webp",+ new Blob(["good"], { type: "image/webp" })+ ]])+ });++ const first = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { mode: LIBRARY_TRANSFER_MODES.EXACT_REPLACE }+ });+ const replay = planLibraryTransfer({+ currentState: current,+ inspection,+ options: { preferredPlan: first.context }+ });++ assert.equal(first.context.mode, LIBRARY_TRANSFER_MODES.EXACT_REPLACE);+ assert.equal(first.context.sourceType, LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP);+ assert.deepEqual(first.targetState.entries.map((entry) => entry.id), ["case:backup"]);+ assert.equal(first.targetState.entries.some((entry) => entry.id === "case:local"), false);+ assert.equal(first.rollback.required, true);+ assert.deepEqual(first.rollback.retainedAssetIds, ["image:local"]);+ assert.equal(first.resourceWrites.length, 1);+ assert.equal(first.resourceWrites[0].sourceId, "image:backup");+ assert.notEqual(first.resourceWrites[0].targetId, "image:backup");+ assert.notEqual(first.resourceWrites[0].targetId, "image:local");+ assert.equal(first.targetState.entries[0].mediaAssets[0].id, first.resourceWrites[0].targetId);+ assert.deepEqual(replay.targetState, first.targetState);+ assert.equal(replay.planToken, first.planToken);+});++test("a rescue backup cannot request exact replacement", async () => {+ const inspection = await inspectLibraryTransfer({+ sourceType: LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP,+ library: portablePackage([portableTextEntry("case:rescued", "可恢复正文")]),+ sourceReport: {+ status: "partial",+ diagnostics: [{ code: "backup_integrity_degraded", severity: "backup", action: "rescue" }],+ stats: {}+ }+ });++ assert.throws(() => planLibraryTransfer({+ currentState: portablePackage([]),+ inspection,+ options: { mode: LIBRARY_TRANSFER_MODES.EXACT_REPLACE }+ }), /救援备份只能安全合并/);+});++test("transfer capacity uses every planned media and Skill write and rejects a stale resource plan", () => {+ const resources = {+ assets: new Map([["media:one", new Blob(["1234"], { type: "image/webp" })]]),+ skillAssets: new Map([["skill-file:one", new Blob(["12345"], { type: "text/markdown" })]])+ };+ const writes = [+ { sourceId: "media:one", targetId: "restore:media", resourceType: "media" },+ { sourceId: "skill-file:one", targetId: "restore:skill", resourceType: "skill" }+ ];++ assert.equal(libraryTransferWriteBytes(writes, resources), 9);+ assert.throws(() => libraryTransferWriteBytes([+ ...writes,+ { sourceId: "media:missing", targetId: "restore:missing", resourceType: "media" }+ ], resources), /资源已经变化/);+});++function portablePackage(entries) {+ return {+ format: "prompt-case-library",+ version: 5,+ schemaVersion: SCHEMA_VERSION,+ entries,+ trashState: { version: 1, items: [] },+ settings: {},+ taxonomy: createDefaultTaxonomy(),+ facetCatalog: createDefaultFacetCatalog(),+ classificationRules: [],+ organizerState: { version: 1, collections: [] },+ compoundCases: [],+ composerSettings: {},+ composerSessions: [],+ creativeExperimentSettings: {},+ creativeRuns: [],+ creativeSkills: { version: 1, items: [] }+ };+}++function portableEntry(id, assetId) {+ const safeEntryId = id.replaceAll(":", "-");+ const safeAssetId = assetId.replaceAll(":", "-");+ return {+ id,+ title: "可恢复案例",+ text: "正文",+ mediaAssets: [{+ id: assetId,+ kind: "image",+ storageMode: "managed",+ sourceTitle: `${safeAssetId}.webp`,+ sourceFormat: "webp",+ mimeType: "image/webp",+ byteSize: 4,+ capturedAt: "2026-08-27T00:00:00.000Z",+ assetPath: `images/${safeEntryId}/${safeAssetId}.webp`+ }],+ primaryMediaId: assetId,+ customLabels: [],+ metadataLabels: [],+ facetAssignments: []+ };+}++function portableTextEntry(id, text) {+ return {+ id,+ title: "可恢复案例",+ text,+ mediaAssets: [],+ primaryMediaId: "",+ customLabels: [],+ metadataLabels: [],+ facetAssignments: []+ };+}++function catalogWithCollision(facetName, nodeName) {+ const catalog = createDefaultFacetCatalog();+ catalog.facets.push({+ id: "facet:collision",+ name: facetName,+ color: "#456789",+ order: catalog.facets.length,+ aliases: [],+ status: "active",+ kind: "facet",+ origin: "manual",+ fixed: false+ });+ catalog.nodes.push({+ id: "tag:collision",+ name: nodeName,+ facetId: "facet:collision",+ parentId: null,+ order: catalog.nodes.length,+ aliases: [],+ patterns: [],+ status: "active",+ kind: "group",+ origin: "manual",+ fixed: false,+ protected: false+ });+ return catalog;+}++function trashedEntry(id, title) {+ return {+ id: `trash:entry:${id}`,+ kind: "entry",+ targetId: id,+ deletedAt: "2026-08-27T00:00:00.000Z",+ snapshot: {+ id,+ title,+ text: "回收站正文",+ mediaAssets: [],+ primaryMediaId: "",+ facetAssignments: []+ },+ relationships: { collections: [], compoundCases: [] }+ };+}++function portableSkill(id, assetId, callName) {+ return {+ id,+ callName,+ portableId: id.replaceAll(":", "-"),+ description: "可恢复方法",+ currentVersionId: "skill-version:collision",+ versions: [{+ id: "skill-version:collision",+ createdAt: "2026-08-27T00:00:00.000Z",+ reason: "imported",+ source: "imported",+ skillMarkdown: "# 方法",+ references: [],+ provenanceMarkdown: ""+ }],+ packageFiles: [{+ path: "SKILL.md",+ assetId,+ byteSize: 5,+ mimeType: "text/markdown",+ archivePath: "skills/source/SKILL.md"+ }],+ textModeConfirmed: false,+ runtimeDependencies: [],+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z"+ };+}diff --git a/test/manual-sync.test.js b/test/manual-sync.test.jsindex 828478f..c63e800 100644--- a/test/manual-sync.test.js+++ b/test/manual-sync.test.js@@ -195,6 +195,172 @@ test("cancel is rejected after the atomic commit point has started", async () =>assert.equal(fixture.controller.status().state, "success");});+test("remote deletion removes an orphaned local blob only after the business commit succeeds", async () => {+ const fixture = await syncedTwoEntryFixture();+ await addRemoteDeletionOfFirstEntry(fixture);+ fixture.failCommit = true;+ fixture.resetCounts();++ await assert.rejects(+ fixture.controller.start({ vault: fixture.vault, settings: fixture.settings }),+ /commit failed/+ );+ assert.equal(fixture.media.has("asset:one"), true);+ assert.equal(fixture.counts().mediaDeletes, 0);+});++test("failed orphan cleanup is persisted and retried by the next unchanged manual sync", async () => {+ const fixture = await syncedTwoEntryFixture();+ await addRemoteDeletionOfFirstEntry(fixture);+ fixture.failDeleteIds = new Set(["asset:one"]);+ fixture.resetCounts();++ const first = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ assert.equal(first.ok, true);+ assert.equal(fixture.state.entries.some((item) => item.id === "one"), false);+ assert.equal(fixture.media.has("asset:one"), true);+ assert.deepEqual(fixture.meta.pendingCleanupAssetIds, ["asset:one"]);++ fixture.failDeleteIds = new Set();+ fixture.resetCounts();+ const retry = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ assert.equal(retry.upToDate, true);+ assert.equal(fixture.media.has("asset:one"), false);+ assert.deepEqual(fixture.meta.pendingCleanupAssetIds, []);+ assert.equal(fixture.counts().mediaDeletes, 1);+ assert.equal(fixture.counts().snapshotWrites, 0);+});++test("replacement recovery media is protected from sync orphan cleanup", async () => {+ const fixture = await syncedTwoEntryFixture();+ fixture.state.libraryReplacementRecoveryPoint = {+ version: 1,+ id: "recovery:one",+ createdAt: "2026-08-23T00:00:00.000Z",+ state: state([entry("one", "asset:one")]),+ retainedAssetIds: ["asset:one"]+ };+ await addRemoteDeletionOfFirstEntry(fixture);+ fixture.resetCounts();++ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ assert.equal(result.ok, true);+ assert.equal(fixture.state.entries.some((item) => item.id === "one"), false);+ assert.equal(fixture.media.has("asset:one"), true);+ assert.deepEqual(fixture.meta.pendingCleanupAssetIds, []);+ assert.equal(fixture.counts().mediaDeletes, 0);+});++test("different device ids with complete identical meaning converge to one case and keep both projects", async () => {+ const fixture = await createFixture();+ fixture.state.entries[0].title = "Same";+ fixture.state.entries[0].text = "Same";+ fixture.state.entries[0].mediaAssets[0].contentHash = "d".repeat(64);+ fixture.state.organizerState.collections.push({ id: "project:local", name: "Local", entryIds: ["one"] });+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ const remoteDuplicate = entry("remote", "asset:remote");+ remoteDuplicate.title = "Same";+ remoteDuplicate.text = "Same";+ remoteDuplicate.mediaAssets[0].contentHash = "d".repeat(64);+ const remotePrepared = state([structuredClone(fixture.state.entries[0]), remoteDuplicate]);+ remotePrepared.organizerState.collections = [+ { id: "project:local", name: "Local", entryIds: ["one"] },+ { id: "project:remote", name: "Remote", entryIds: ["remote"] }+ ];+ remotePrepared.entries[0].mediaAssets[0].syncObjectId = fixture.meta.assetRefs["asset:one"].objectId;+ remotePrepared.entries[0].mediaAssets[0].syncContentType = "image/webp";+ remotePrepared.entries[1].mediaAssets[0].syncObjectId = "b".repeat(64);+ remotePrepared.entries[1].mediaAssets[0].syncContentType = "image/webp";+ fixture.remoteSnapshots.push(await createRevisionSnapshot(remotePrepared, {+ deviceId: "device-b",+ logicalClock: fixture.meta.logicalClock + 1,+ baseSnapshot: {+ format: "prompt-director-sync-state",+ version: 2,+ records: fixture.meta.records+ }+ }));+ fixture.resetCounts();++ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ assert.equal(result.ok, true);+ assert.deepEqual(fixture.state.entries.map((item) => item.id), ["one"]);+ assert.deepEqual(fixture.state.organizerState.collections.map((project) => project.entryIds), [["one"], ["one"]]);+ assert.equal(fixture.counts().objectReads, 0);+ assert.equal(fixture.media.has("asset:remote"), false);+});++test("one missing unsynced media item is reported and removed without blocking healthy cases", async () => {+ const fixture = await createFixture();+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });+ fixture.state.entries.push(entry("broken", "asset:broken"), entry("healthy", "asset:healthy"));+ fixture.media.set("asset:healthy", new Blob(["healthy"], { type: "image/webp" }));+ fixture.meta.localDirty = true;+ fixture.meta.dirtyAssetIds = ["asset:broken", "asset:healthy"];+ fixture.resetCounts();++ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });++ assert.equal(result.ok, true);+ assert.equal(result.skippedMediaCount, 1);+ assert.deepEqual(result.skippedMedia.map((item) => item.assetId), ["asset:broken"]);+ assert.equal(fixture.state.entries.find((item) => item.id === "broken").text, "broken");+ assert.deepEqual(fixture.state.entries.find((item) => item.id === "broken").mediaAssets, []);+ assert.deepEqual(fixture.state.entries.find((item) => item.id === "healthy").mediaAssets.map((asset) => asset.id), ["asset:healthy"]);+ assert.equal(fixture.counts().objectWrites, 1);+ assert.equal(fixture.counts().snapshotWrites, 1);+});++test("a media storage read error still stops sync without committing partial salvage", async () => {+ const fixture = await createFixture();+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });+ fixture.state.entries.push(entry("io-error", "asset:io-error"));+ fixture.media.set("asset:io-error", new Blob(["still-present"], { type: "image/webp" }));+ fixture.meta.localDirty = true;+ fixture.meta.dirtyAssetIds = ["asset:io-error"];+ fixture.failReadIds = new Set(["asset:io-error"]);+ fixture.resetCounts();++ await assert.rejects(+ fixture.controller.start({ vault: fixture.vault, settings: fixture.settings }),+ /media read failed/+ );++ assert.equal(fixture.state.entries.some((item) => item.id === "io-error"), true);+ assert.equal(fixture.counts().snapshotWrites, 0);+ assert.equal(fixture.counts().metadataWrites, 0);+});++async function syncedTwoEntryFixture() {+ const fixture = await createFixture();+ fixture.state.entries.push(entry("two", "asset:two"));+ fixture.media.set("asset:two", new Blob(["two"], { type: "image/webp" }));+ fixture.meta.localDirty = true;+ fixture.meta.dirtyAssetIds = ["asset:two"];+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });+ return fixture;+}++async function addRemoteDeletionOfFirstEntry(fixture) {+ const remotePrepared = state([entry("two", "asset:two")]);+ remotePrepared.entries[0].mediaAssets[0].syncObjectId = fixture.meta.assetRefs["asset:two"].objectId;+ remotePrepared.entries[0].mediaAssets[0].syncContentType = "image/webp";+ fixture.remoteSnapshots.push(await createRevisionSnapshot(remotePrepared, {+ deviceId: "device-b",+ logicalClock: fixture.meta.logicalClock + 1,+ baseSnapshot: {+ format: "prompt-director-sync-state",+ version: 2,+ records: fixture.meta.records+ }+ }));+}+async function createFixture() {let count = emptyCounts();let stateValue = state([entry("one", "asset:one")]);@@ -215,6 +381,9 @@ async function createFixture() {let resumeCommit;let commitStartedResolve;let commitStarted = new Promise((resolve) => { commitStartedResolve = resolve; });+ let failCommit = false;+ let failDeleteIds = new Set();+ let failReadIds = new Set();const controller = createManualSyncController({readState: async () => {@@ -233,6 +402,7 @@ async function createFixture() {},readMedia: async (id) => {count.mediaReads += 1;+ if (failReadIds.has(id)) throw new Error("media read failed");return media.get(id) ?? null;},writeMedia: async (id, blob) => {@@ -241,6 +411,7 @@ async function createFixture() {},deleteMedia: async (id) => {count.mediaDeletes += 1;+ if (failDeleteIds.has(id)) throw new Error("delete failed");media.delete(id);},writeObject: async (_vault, blob, { signal } = {}) => {@@ -268,6 +439,7 @@ async function createFixture() {commitStartedResolve();await new Promise((resolve) => { resumeCommit = resolve; });}+ if (failCommit) throw new Error("commit failed");count.metadataWrites += 1;stateValue = structuredClone(nextState);metaValue = structuredClone(meta);@@ -295,6 +467,9 @@ async function createFixture() {Object.defineProperty(fixture, "pauseObjectRead", { set(value) { pauseObjectRead = value; } });Object.defineProperty(fixture, "pauseSnapshotList", { set(value) { pauseSnapshotList = value; } });Object.defineProperty(fixture, "pauseCommit", { set(value) { pauseCommit = value; } });+ Object.defineProperty(fixture, "failCommit", { set(value) { failCommit = value; } });+ Object.defineProperty(fixture, "failDeleteIds", { set(value) { failDeleteIds = value; } });+ Object.defineProperty(fixture, "failReadIds", { set(value) { failReadIds = value; } });Object.defineProperty(fixture, "commitStarted", { get() { return commitStarted; } });fixture.resumeCommit = () => resumeCommit?.();return fixture;diff --git a/test/manual_sync_e2e.py b/test/manual_sync_e2e.pyindex ae21a5f..23e07c7 100644--- a/test/manual_sync_e2e.py+++ b/test/manual_sync_e2e.py@@ -93,6 +93,42 @@ def main() -> None:assert after_noop["snapshotCount"] == after_edit_sync["snapshotCount"], after_noopassert after_noop["meta"] == after_edit_sync["meta"], after_noop+ # One missing local media item is isolated, named to the user, and does not block healthy data.+ setup.evaluate(+ """async () => {+ const stored = await chrome.storage.local.get(['entries', 'syncMeta']);+ const missing = {+ ...stored.entries[0],+ id: 'sync-missing-case',+ title: '缺图同步案例',+ text: '正文必须继续同步。',+ mediaAssets: [{+ id: 'sync-missing-asset', kind: 'image', usage: 'content', storageMode: 'managed',+ mimeType: 'image/webp', byteSize: 10, sourceTitle: 'missing.webp'+ }],+ primaryMediaId: 'sync-missing-asset'+ };+ await chrome.storage.local.set({+ entries: [...stored.entries, missing],+ syncMeta: {+ ...stored.syncMeta,+ localDirty: true,+ dirtyAssetIds: [...new Set([...(stored.syncMeta?.dirtyAssetIds || []), 'sync-missing-asset'])]+ }+ });+ }"""+ )+ salvaged = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'SYNC_NOW'})")+ assert salvaged["ok"] is True and salvaged["upToDate"] is False, salvaged+ assert salvaged["skippedMediaCount"] == 1, salvaged+ assert salvaged["skippedMedia"][0]["ownerTitle"] == "缺图同步案例", salvaged+ assert "缺图同步案例 / missing.webp" in salvaged["message"], salvaged+ salvaged_state = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")+ missing_case = next(item for item in salvaged_state["entries"] if item["id"] == "sync-missing-case")+ assert missing_case["text"] == "正文必须继续同步。" and missing_case["mediaAssets"] == [], missing_case+ after_salvage = setup.evaluate("async () => window.__manualSyncProbe()")+ assert after_salvage["snapshotCount"] == after_noop["snapshotCount"] + 1, after_salvage+# A damaged formal snapshot blocks success; an atomic .partial is never treated as state.setup.evaluate("""async () => {@@ -114,7 +150,7 @@ def main() -> None:assert damaged["ok"] is False and "损坏" in damaged["message"], damageddamaged_state = setup.evaluate("async () => window.__manualSyncProbe()")assert damaged_state["settings"]["lastErrorCode"] == "sync_snapshot_corrupt", damaged_state- assert damaged_state["snapshotCount"] == after_noop["snapshotCount"] + 1, damaged_state+ assert damaged_state["snapshotCount"] == after_salvage["snapshotCount"] + 1, damaged_stateassert damaged_state["status"]["state"] == "error", damaged_stateassert damaged_state["status"]["runningCount"] == 0, damaged_stateassert damaged_state["status"]["pendingCount"] == 0, damaged_state@@ -123,9 +159,10 @@ def main() -> None:"manual_only": True,"no_op_zero_snapshot": True,"pending_local_changes": True,+ "missing_media_isolated_and_named": True,"damaged_snapshot_blocked": True,"terminal_quiet": True,- "snapshot_count": after_noop["snapshotCount"],+ "snapshot_count": after_salvage["snapshotCount"],})diff --git a/test/media-archive-ui.test.js b/test/media-archive-ui.test.jsindex 3bc8e9a..74a181b 100644--- a/test/media-archive-ui.test.js+++ b/test/media-archive-ui.test.js@@ -73,17 +73,21 @@ test("share package import sizes only this user-selected package by its real filassert.match(imported, /maxFileBytes:\s*file\.size/);assert.match(imported, /maxImageBytes:\s*file\.size/);assert.match(imported, /readZipBlob\(file, packageLimits\)/);- assert.match(imported, /salvageOptions = \{ \.\.\.packageLimits, salvageInvalidMedia: true \}/);- assert.match(imported, /parseLibraryPackage\(library, files, salvageOptions\)/);+ assert.match(imported, /sourceType:\s*LIBRARY_TRANSFER_SOURCES\.SHARE_PACKAGE/);+ assert.match(imported, /limits:\s*packageLimits/);+ assert.match(imported, /validateImage:\s*validateImportedImage/);});-test("complete folder restore derives its media budget from the selected verified backup", () => {+test("folder restore derives its media budget before strict or rescue inspection", () => {const restore = js.slice(js.indexOf("async function restoreCompleteFolderBackup"), js.indexOf("async function importSharedLibraryPackage"));assert.match(restore, /largestMediaBytes = Math\.max\(1, \.\.\.backupMediaSizes\)/);assert.match(restore, /maxFileBytes: largestMediaBytes/);assert.match(restore, /maxImageBytes: largestMediaBytes/);assert.match(restore, /maxVideoBytes: largestMediaBytes/);- assert.match(restore, /parseCompleteFolderBackup\(library, files, restoreLimits\)/);+ assert.match(restore, /inspectFolderBackupEnvelope\(files\)/);+ assert.match(restore, /sourceType:\s*envelope\.mode === "complete"[\s\S]*LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP[\s\S]*LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP/);+ assert.match(restore, /limits:\s*restoreLimits/);+ assert.match(restore, /validateImage:\s*validateImportedImage/);assert.doesNotMatch(restore, /maxFileBytes: Number\.MAX_SAFE_INTEGER/);});diff --git a/test/media-ui.test.js b/test/media-ui.test.jsindex 0542608..db28c70 100644--- a/test/media-ui.test.js+++ b/test/media-ui.test.js@@ -121,22 +121,28 @@ test("fixed-ratio gallery covers crop mismatched source images inside the card",assert.match(css, /\.case-image-wrap-fixed \.case-shot\s*\{[^}]*height:\s*100%;[^}]*object-fit:\s*cover/);});-test("complete folder backup writes a completion marker after library metadata", () => {+test("folder backup preflights every resource before choosing a folder and writes its marker last", () => {const backup = source.slice(source.indexOf("async function createCompleteFolderBackup"), source.indexOf("async function restoreCompleteFolderBackup"));- assert.ok(backup.indexOf('"library.json"') < backup.indexOf('"complete.json"'));- assert.match(backup, /await writeDirectoryFile\(directory, assetPath, blob\)/);- assert.match(backup, /portableManagedBackupAsset\(asset, blob, assetPath, await sha256Blob\(blob\)\)/);+ const pickerCall = backup.indexOf("const parent = await window.showDirectoryPicker");+ assert.ok(backup.indexOf("GET_FOLDER_BACKUP_STATE") < pickerCall);+ assert.ok(backup.indexOf("inspectLibraryTransfer({") < pickerCall);+ assert.match(backup, /plannedFiles\.set\(assetPath, blob\)/);+ assert.match(backup, /portableManagedBackupAsset\(asset, blob, assetPath, await sha256Blob\(blob\), portableFormat\)/);assert.match(backup, /materializeEntry\(item\.snapshot, `trash-entry-/);- assert.match(backup, /buildFolderBackupCompletion\(writtenFiles/);- assert.match(backup, /verifyFolderBackupCompletion\(completion, writtenFiles\)/);- assert.ok(backup.indexOf("parseCompleteFolderBackup(writtenLibrary, writtenFiles") < backup.indexOf('"complete.json"'));- assert.match(source, /"application\/rtf":\s*"rtf"/);+ assert.match(backup, /buildFolderBackupWritePlan\(\{/);+ assert.match(backup, /for \(const \[path, blob\] of writePlan\.files\)/);+ assert.match(backup, /verifyFolderBackupCompletion\(writePlan\.marker, writtenFiles\)/);+ assert.ok(backup.indexOf("for (const [path, blob] of writePlan.files)") < backup.indexOf("writePlan.markerPath"));+ assert.match(backup, /inspectPlannedBackup\(LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP\)/);+ assert.match(backup, /inspectPlannedBackup\(LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP,/);+ assert.match(backup, /resolvePortableAssetFormat\(/);+ assert.doesNotMatch(source, /function folderExtension\(|const known = \{[\s\S]*?"image\/png"/);});test("complete folder restore validates aggregate and real per-media sizes before preview", () => {const restore = source.slice(source.indexOf("async function restoreCompleteFolderBackup"), source.indexOf("function backupMediaPaths"));const aggregateValidation = restore.indexOf("completion.mediaCount !== backupPaths.size");- const packageParsing = restore.indexOf("parseCompleteFolderBackup(library, files");+ const packageParsing = restore.indexOf("inspectLibraryTransfer({");assert.ok(aggregateValidation >= 0 && aggregateValidation < packageParsing);assert.match(restore, /PREVIEW_LIBRARY_IMPORT[^}]*library:\s*restoredLibrary/);assert.match(restore, /APPLY_LIBRARY_IMPORT[^}]*library:\s*restoredLibrary/);diff --git a/test/offscreen-share-package.test.js b/test/offscreen-share-package.test.jsindex 5799c3a..bd890b1 100644--- a/test/offscreen-share-package.test.js+++ b/test/offscreen-share-package.test.js@@ -2,10 +2,10 @@ import test from "node:test";import assert from "node:assert/strict";import {- packageMediaExtension,portableManagedAsset,readLinkedAssetForShare} from "../offscreen.js";+import { resolvePortableAssetFormat } from "../asset-formats.js";const linkedAsset = Object.freeze({id: "source:psd",@@ -58,10 +58,10 @@ test("share export reports missing permission changed and missing local sourcestest("linked source becomes a portable managed copy with accurate format and no machine state", () => {const blob = new Blob(["psd-source"], { type: "image/vnd.adobe.photoshop" });- const extension = packageMediaExtension(linkedAsset, blob);- const packaged = portableManagedAsset(linkedAsset, blob, "attachments/case/source.psd", extension);+ const portableFormat = resolvePortableAssetFormat(linkedAsset, blob);+ const packaged = portableManagedAsset(linkedAsset, blob, "attachments/case/source.psd", portableFormat);- assert.equal(extension, "psd");+ assert.equal(portableFormat.extension, "psd");assert.equal(packaged.storageMode, "managed");assert.equal(packaged.assetPath, "attachments/case/source.psd");assert.equal(packaged.byteSize, blob.size);@@ -81,10 +81,10 @@ test("unknown linked source stays an inert downloadable attachment in the packagsourceFormat: "customsource",mimeType: "application/octet-stream"};- const extension = packageMediaExtension(asset, blob);- const packaged = portableManagedAsset(asset, blob, `attachments/case/source.${extension}`, extension);+ const portableFormat = resolvePortableAssetFormat(asset, blob);+ const packaged = portableManagedAsset(asset, blob, `attachments/case/source.${portableFormat.extension}`, portableFormat);- assert.equal(extension, "customsource");+ assert.equal(portableFormat.extension, "customsource");assert.equal(packaged.kind, "attachment");assert.equal(packaged.storageMode, "managed");assert.equal(packaged.formatCategory, "other-source");diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.pyindex 1a17875..3c8206d 100644--- a/test/sharing_and_data_safety_e2e.py+++ b/test/sharing_and_data_safety_e2e.py@@ -246,7 +246,10 @@ def main() -> None:async createWritable() {let pending = this.blob;return {- write: async (value) => { pending = value instanceof Blob ? value : new Blob([value]); },+ write: async (value) => {+ if (window.__backupWriteFailureName === this.name) throw new Error('simulated write failure');+ pending = value instanceof Blob ? value : new Blob([value]);+ },close: async () => { this.blob = pending; },abort: async () => undefined};@@ -311,21 +314,90 @@ def main() -> None:library.evaluate("""async () => {window.__portableBackupFolder = [...window.__backupRoot.directories.values()][0];- const media = await import(chrome.runtime.getURL('media-store.js'));- for (const id of ['share-image-one', 'share-image-two', 'share-poster', 'share-video', 'share-document', 'trash-image', 'linked-local-image']) {- await media.deleteMediaBlob(id);- }- const {deleteLocalAssetHandle} = await import(chrome.runtime.getURL('local-asset-store.js'));- await deleteLocalAssetHandle('linked-local-image');- await chrome.storage.local.set({- entries: [],- trashState: {version: 1, items: []},- organizerState: {version: 7, collections: []},- compoundCases: [],- composerSessions: [],- creativeRuns: [],- creativeSkills: {version: 1, items: []}+ const cloneDirectory = async (source) => {+ const target = new source.constructor(source.name + '-degraded');+ for await (const [name, handle] of source.entries()) {+ if (handle.kind === 'directory') target.directories.set(name, await cloneDirectory(handle));+ else {+ const file = await handle.getFile();+ const copy = new handle.constructor(name);+ copy.blob = new Blob([await file.arrayBuffer()], {type: file.type});+ target.files.set(name, copy);+ }+ }+ return target;+ };+ const fileHandleAt = async (root, path) => {+ const parts = path.split('/');+ const name = parts.pop();+ let directory = root;+ for (const part of parts) directory = await directory.getDirectoryHandle(part);+ return directory.getFileHandle(name);+ };+ window.__degradedBackupFolder = await cloneDirectory(window.__portableBackupFolder);+ const completeHandle = await window.__degradedBackupFolder.getFileHandle('complete.json');+ const completion = JSON.parse(await (await completeHandle.getFile()).text());+ const brokenDescriptor = completion.files.find((item) => item.path.includes('images/share-two/'));+ const brokenHandle = await fileHandleAt(window.__degradedBackupFolder, brokenDescriptor.path);+ const previousSize = brokenDescriptor.byteSize;+ brokenHandle.blob = new Blob(['not-a-decodable-image'], {type: 'image/png'});+ brokenDescriptor.byteSize = brokenHandle.blob.size;+ const digest = await crypto.subtle.digest('SHA-256', await brokenHandle.blob.arrayBuffer());+ brokenDescriptor.sha256 = [...new Uint8Array(digest)]+ .map((value) => value.toString(16).padStart(2, '0')).join('');+ completion.byteSize += brokenDescriptor.byteSize - previousSize;+ completeHandle.blob = new Blob([JSON.stringify(completion, null, 2)], {type: 'application/json'});+ window.__clearPortableLibrary = async () => {+ const media = await import(chrome.runtime.getURL('media-store.js'));+ for (const id of ['share-image-one', 'share-image-two', 'share-poster', 'share-video', 'share-document', 'trash-image', 'linked-local-image']) {+ await media.deleteMediaBlob(id);+ }+ const {deleteLocalAssetHandle} = await import(chrome.runtime.getURL('local-asset-store.js'));+ await deleteLocalAssetHandle('linked-local-image');+ await chrome.storage.local.set({+ entries: [], trashState: {version: 1, items: []},+ organizerState: {version: 7, collections: []}, compoundCases: [],+ composerSessions: [], creativeRuns: [], creativeSkills: {version: 1, items: []}+ });+ };+ await window.__clearPortableLibrary();+ Object.defineProperty(window, 'showDirectoryPicker', {+ value: async () => window.__degradedBackupFolder,+ configurable: true});+ }"""+ )+ library.locator("#restore-folder-backup").click()+ degraded_dialog = library.locator("#promptdirector-app-dialog")+ expect(degraded_dialog).to_be_visible(timeout=15_000)+ expect(degraded_dialog).to_contain_text("检查救援恢复方案")+ assert degraded_dialog.locator("#promptdirector-app-dialog-mode").count() == 0+ degraded_dialog.locator("button[type='submit']").click()+ expect(degraded_dialog).to_contain_text("按救援方案恢复资料库")+ expect(degraded_dialog).to_contain_text("丢弃损坏或缺失的媒体 1 项")+ degraded_dialog.locator("button[type='submit']").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("救援恢复已按预检方案完成", timeout=15_000)+ degraded_state = library.evaluate(+ """async () => {+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});+ const media = await import(chrome.runtime.getURL('media-store.js'));+ const healthy = state.entries.find((entry) => entry.id === 'share-one');+ const damaged = state.entries.find((entry) => entry.id === 'share-two');+ return {+ entryIds: state.entries.map((entry) => entry.id).sort(),+ healthyMediaBytes: (await media.getMediaBlob(healthy?.mediaAssets?.[0]?.id))?.size || 0,+ damagedText: damaged?.text || '',+ damagedMediaCount: damaged?.mediaAssets?.length ?? -1+ };+ }"""+ )+ assert degraded_state["entryIds"] == ["linked-one", "share-one", "share-two"], degraded_state+ assert degraded_state["healthyMediaBytes"] > 0, degraded_state+ assert degraded_state["damagedText"] and degraded_state["damagedMediaCount"] == 0, degraded_state++ library.evaluate(+ """async () => {+ await window.__clearPortableLibrary();Object.defineProperty(window, 'showDirectoryPicker', {value: async () => window.__portableBackupFolder,configurable: true@@ -335,9 +407,11 @@ def main() -> None:library.locator("#restore-folder-backup").click()restore_dialog = library.locator("#promptdirector-app-dialog")expect(restore_dialog).to_be_visible(timeout=15_000)- expect(restore_dialog).to_contain_text("恢复资料库备份")+ expect(restore_dialog).to_contain_text("选择资料库恢复方式")+ restore_dialog.locator("button[type='submit']").click()+ expect(restore_dialog).to_contain_text("安全合并资料库备份")restore_dialog.locator("button[type='submit']").click()- expect(library.locator("#data-safety-feedback")).to_contain_text("媒体文件校验并恢复完成", timeout=15_000)+ expect(library.locator("#data-safety-feedback")).to_contain_text("完整恢复已按预检方案完成", timeout=15_000)restored_state = library.evaluate("""async () => {const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});@@ -357,6 +431,112 @@ def main() -> None:assert restored_state["activeImageBytes"] > 0 and restored_state["trashImageBytes"] > 0, restored_stateassert restored_state["linkedImageBytes"] > 0 and restored_state["linkedStorageMode"] == "managed", restored_state+ library.evaluate(+ """async () => {+ const stored = await chrome.storage.local.get(['entries', 'settings']);+ const localOnly = {+ ...stored.entries[0],+ id: 'local-before-exact',+ title: '精确恢复前的本机案例',+ text: '空间不足或取消时必须保留。',+ mediaAssets: [],+ primaryMediaId: ''+ };+ const {normalizeAiProviderRegistry} = await import(chrome.runtime.getURL('ai-provider-registry.js'));+ const aiProviderRegistry = normalizeAiProviderRegistry({+ providers: {deepseek: {apiKey: 'fixture-private-key', consent: true}}+ });+ await chrome.storage.local.set({+ entries: [...stored.entries, localOnly],+ settings: {...stored.settings, libraryTitle: '本机精确恢复前'},+ aiProviderRegistry,+ syncSettings: {sentinel: 'keep-local-sync'},+ uiPreferences: {sentinel: 'keep-local-ui'}+ });+ window.__originalStorageEstimate = navigator.storage.estimate.bind(navigator.storage);+ Object.defineProperty(navigator.storage, 'estimate', {+ value: async () => ({quota: 1, usage: 1}),+ configurable: true+ });+ }"""+ )+ library.locator("#restore-folder-backup").click()+ capacity_dialog = library.locator("#promptdirector-app-dialog")+ expect(capacity_dialog).to_be_visible(timeout=15_000)+ capacity_dialog.locator("#promptdirector-app-dialog-mode").select_option("exact-replace")+ capacity_dialog.locator("button[type='submit']").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("本机可用空间不足", timeout=15_000)+ capacity_state = library.evaluate(+ """async () => {+ const stored = await chrome.storage.local.get(['entries', 'libraryReplacementRecoveryPoint']);+ return {+ entryIds: stored.entries.map((entry) => entry.id),+ hasRecoveryPoint: Boolean(stored.libraryReplacementRecoveryPoint)+ };+ }"""+ )+ assert "local-before-exact" in capacity_state["entryIds"], capacity_state+ assert capacity_state["hasRecoveryPoint"] is False, capacity_state++ library.evaluate(+ """() => {+ Object.defineProperty(navigator.storage, 'estimate', {+ value: window.__originalStorageEstimate,+ configurable: true+ });+ }"""+ )+ library.locator("#restore-folder-backup").click()+ exact_choice = library.locator("#promptdirector-app-dialog")+ expect(exact_choice).to_be_visible(timeout=15_000)+ exact_choice.locator("#promptdirector-app-dialog-mode").select_option("exact-replace")+ exact_choice.locator("button[type='submit']").click()+ exact_confirm = library.locator("#promptdirector-app-dialog")+ expect(exact_confirm).to_contain_text("将资料库恢复成备份当时状态")+ expect(exact_confirm).to_contain_text("自动建立回退点")+ exact_confirm.locator("button[type='submit']").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("完整恢复已按预检方案完成", timeout=15_000)+ expect(library.locator("#restore-library-replacement-point")).to_be_visible(timeout=15_000)+ exact_state = library.evaluate(+ """async () => {+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});+ const stored = await chrome.storage.local.get([+ 'aiProviderRegistry', 'syncSettings', 'uiPreferences', 'libraryReplacementRecoveryPoint'+ ]);+ return {+ entryIds: state.entries.map((entry) => entry.id).sort(),+ activeImageId: state.entries.find((entry) => entry.id === 'share-one')?.mediaAssets?.[0]?.id || '',+ aiCredentialPreserved: stored.aiProviderRegistry?.providers?.deepseek?.apiKey === 'fixture-private-key',+ syncSentinel: stored.syncSettings?.sentinel || '',+ uiSentinel: stored.uiPreferences?.sentinel || '',+ hasRecoveryPoint: Boolean(stored.libraryReplacementRecoveryPoint)+ };+ }"""+ )+ assert exact_state["entryIds"] == ["linked-one", "share-one", "share-two"], exact_state+ assert exact_state["activeImageId"] != "share-image-one", exact_state+ assert exact_state["aiCredentialPreserved"] is True, exact_state+ assert exact_state["syncSentinel"] == "keep-local-sync", exact_state+ assert exact_state["uiSentinel"] == "keep-local-ui", exact_state+ assert exact_state["hasRecoveryPoint"] is True, exact_state++ library.locator("#restore-library-replacement-point").click()+ rollback_dialog = library.locator("#promptdirector-app-dialog")+ expect(rollback_dialog).to_contain_text("回退上次精确恢复")+ rollback_dialog.locator("button[type='submit']").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("已回退到上一次精确替换前的资料库", timeout=15_000)+ rollback_state = library.evaluate(+ """async () => {+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});+ return {+ entryIds: state.entries.map((entry) => entry.id).sort(),+ activeImageId: state.entries.find((entry) => entry.id === 'share-one')?.mediaAssets?.[0]?.id || ''+ };+ }"""+ )+ assert "local-before-exact" in rollback_state["entryIds"], rollback_state+ assert rollback_state["activeImageId"] == "share-image-one", rollback_state+library.evaluate("""async () => {const stored = await chrome.storage.local.get('entries');@@ -384,20 +564,83 @@ def main() -> None:}],primaryMediaId: 'unreadable-linked-asset'};- await chrome.storage.local.set({entries: [...stored.entries, linked]});+ const linkedTwo = {+ ...linked,+ id: 'unreadable-linked-case-two',+ title: '第二个失效本机链接',+ mediaAssets: [{+ ...linked.mediaAssets[0],+ id: 'unreadable-linked-asset-two',+ sourceTitle: 'missing-two.zzz',+ relativePath: 'missing-two.zzz'+ }],+ primaryMediaId: 'unreadable-linked-asset-two'+ };+ await chrome.storage.local.set({entries: [...stored.entries, linked, linkedTwo]});+ window.__installBackupRoot();+ }"""+ )+ library.locator("#create-folder-backup").click()+ rescue_dialog = library.locator("#promptdirector-app-dialog")+ expect(rescue_dialog).to_be_visible(timeout=15_000)+ expect(rescue_dialog).to_contain_text("生成救援备份")+ expect(rescue_dialog).to_contain_text("2 项无法完整写入")+ assert library.evaluate("() => window.__backupRoot.directories.size") == 0+ rescue_dialog.locator("button.button-secondary").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("没有创建任何资料夹", timeout=15_000)+ assert library.evaluate("() => window.__backupRoot.directories.size") == 0++ library.locator("#create-folder-backup").click()+ rescue_dialog = library.locator("#promptdirector-app-dialog")+ expect(rescue_dialog).to_be_visible(timeout=15_000)+ rescue_dialog.locator("button[type='submit']").click()+ expect(library.locator("#data-safety-feedback")).to_contain_text("救援备份已完成", timeout=15_000)+ rescue_backup = library.evaluate(+ """async () => {+ const folder = [...window.__backupRoot.directories.values()][0];+ const marker = JSON.parse(await (await folder.files.get('rescue.json').getFile()).text());+ const data = JSON.parse(await (await folder.files.get('library.json').getFile()).text());+ const rescued = data.entries.find((entry) => entry.id === 'unreadable-linked-case');+ return {+ created: Boolean(folder),+ completeExists: Boolean(folder?.files.has('complete.json')),+ rescueExists: Boolean(folder?.files.has('rescue.json')),+ markerFormat: marker.format,+ issueCount: marker.issues.length,+ rescuedMediaCount: rescued?.mediaAssets?.length ?? -1,+ rescuedText: rescued?.text || ''+ };+ }"""+ )+ assert rescue_backup["created"] is True, rescue_backup+ assert rescue_backup["completeExists"] is False and rescue_backup["rescueExists"] is True, rescue_backup+ assert rescue_backup["markerFormat"] == "prompt-director-folder-rescue", rescue_backup+ assert rescue_backup["issueCount"] >= 2, rescue_backup+ assert rescue_backup["rescuedMediaCount"] == 0 and rescue_backup["rescuedText"], rescue_backup++ library.evaluate(+ """() => {window.__installBackupRoot();+ window.__backupWriteFailureName = 'library.json';}""")library.locator("#create-folder-backup").click()+ rescue_dialog = library.locator("#promptdirector-app-dialog")+ expect(rescue_dialog).to_be_visible(timeout=15_000)+ rescue_dialog.locator("button[type='submit']").click()expect(library.locator("#data-safety-feedback")).to_contain_text("未写入完成标记", timeout=15_000)- failed_backup = library.evaluate(+ interrupted_backup = library.evaluate("""() => {const folder = [...window.__backupRoot.directories.values()][0];- return {created: Boolean(folder), completeExists: Boolean(folder?.files.has('complete.json'))};+ return {+ created: Boolean(folder),+ completeExists: Boolean(folder?.files.has('complete.json')),+ rescueExists: Boolean(folder?.files.has('rescue.json'))+ };}""")- assert failed_backup == {"created": True, "completeExists": False}, failed_backup- print({"shared_entries": 2, "curated_submission": True, "private_drafts_removed": True, "data_safety": True, "folder_backup": backup_result, "cross_machine_restore": restored_state, "unreadable_source_no_marker": failed_backup, "offline_preview": True, "mobile_width": 390, "screenshots": str(screenshots)})+ assert interrupted_backup == {"created": True, "completeExists": False, "rescueExists": False}, interrupted_backup+ print({"shared_entries": 2, "curated_submission": True, "private_drafts_removed": True, "data_safety": True, "folder_backup": backup_result, "degraded_complete_rescue": degraded_state, "cross_machine_restore": restored_state, "capacity_guard": capacity_state, "exact_restore": exact_state, "rollback": rollback_state, "rescue_backup": rescue_backup, "interrupted_backup": interrupted_backup, "offline_preview": True, "mobile_width": 390, "screenshots": str(screenshots)})if __name__ == "__main__":diff --git a/test/sync-model.test.js b/test/sync-model.test.jsindex 04a5091..0ada75e 100644--- a/test/sync-model.test.js+++ b/test/sync-model.test.js@@ -19,11 +19,13 @@ test("sync metadata keeps a durable local pending flag separate from changed medlogicalClock: 2,localDirty: true,dirtyAssetIds: ["asset:one", "asset:one", ""],+ pendingCleanupAssetIds: ["asset:old", "asset:old", ""],assetRefs: { "asset:one": { objectId: "a".repeat(64), contentType: "image/webp" } }});assert.equal(value.localDirty, true);assert.deepEqual(value.dirtyAssetIds, ["asset:one"]);+ assert.deepEqual(value.pendingCleanupAssetIds, ["asset:old"]);assert.equal(value.assetRefs["asset:one"].objectId, "a".repeat(64));});