diff --git a/Docs/plans/2026-08-22-file-model-convergence-and-library-relocation.md b/Docs/plans/2026-08-22-file-model-convergence-and-library-relocation.md deleted file mode 100644 index d12f9a206..000000000 --- a/Docs/plans/2026-08-22-file-model-convergence-and-library-relocation.md +++ /dev/null @@ -1,254 +0,0 @@ -# 魏碑文件模型收敛与资料库迁移入口 总体实施计划 - -**版本:** 2.0(细化执行步骤) -**日期:** 2026-08-22 -**文档性质:** 任务一(资料库迁移入口)与任务二(文件模型收敛)的产品与工程执行计划 -**状态:** 已经三份独立对抗性审查修正 + 零体验回退约束;不代表授权合并、打标签、发布 - ---- - -# 0. 一句话本质 - -> **文件就是文件,文件夹就是文件夹。App 只是访问它们:外部爱怎么改就怎么改,App 都采用;App 自己要写回时,先比一次再动笔;任何销毁动作之前,先留副本。** - -## 0.1 第一约束:零体验回退 - -**任何阶段合入后,用户体验不允许有任何回退。** 六条可验收指标: - -1. **可见性不回退**:用户需要知道的状态(笔记不可用、写冲突、库不可用)仍能在使用现场明确看到——从"主动弹横幅"改为"条内状态",绝不静默消失; -2. **数据安全不回退**:防丢能力只升不降;新机制通过 8/12 事故全场景回归之前,旧锁一道不拆; -3. **编辑不回退**:光标下内容被换/被冲的可能性为零(现有 dirty 守卫全部保留); -4. **性能不回退**:比对只发生在写回与采用两个低频时点,不引入逐键/逐帧开销; -5. **功能不回退**:多机搬运、搜索索引、Agent 读写授权、崩溃恢复全部保功能; -6. **可逆**:每阶段独立可发布;任一阶段验收发现回退即该阶段回滚,不影响已合入部分。 - -每个阶段的 PR 必须附"回退自查表",逐条对照上述六条作答。 - ---- - -# 1. 背景与审查结论 - -## 1.1 病灶 - -8/12 诗歌笔记事故(读盘失败→模板被当正文写回)后层层补丁,形成互相矛盾的锁:启动检查"指纹对不上就切断链接"(`WorkspaceStore+LibraryRoot.swift:245-249`)与 3 秒对账"指纹对不上就以文件为准"判决相反;P0 降级、重命名哨兵、分叉修复、快照回放各自带独立判定。用户库在 iCloud 同步目录,瞬断周期性触发误报。 - -## 1.2 三份对抗性审查的硬性修正(全部并入设计) - -1. 写回比对必须下沉到**唯一底层写函数**,规则补齐:重读失败或无基线 ⇒ 拒写并保留待写内容;摘要不符 ⇒ 待写内容先入备份环再采用磁盘。rename 直写(`WorkspaceStore+NotesPersistence.swift:217`)、repair 直写(`:584`)、retry(`:476-500`)、agent 写笔记全部经此函数。 -2. **销毁前副本先行**:采用外部内容、删除条目、丢弃未落盘输入、冲突选边之前,将销毁内容先写入备份环(`NoteBackupRing.capture(content:)` 收内存字节)。同时修复审查发现的两个现状漏洞:外部删除正在编辑的笔记丢未落盘输入(`WorkspaceStore.swift:7797-7804`);冲突条选「使用磁盘版本」销毁 checkpoint(`WorkspaceStore+NoteEditing.swift:236-238`)。 -3. 崩溃恢复的 baseFileDigest 三态判别(`WorkspaceStore+NoteEditing.swift:296-309`)不得简化。 -4. 可携带快照 revision/payload 双校验(`CourseProjectRootSupport.swift:535-573`)维持不动——它本身就是防双机互盖的 compare-before-write。 -5. **iCloud 占位符必须新增识别**:扫描 `.skipsHiddenFiles`(`CourseProjectRootSupport.swift:2652`)看不见 `.名字.md.icloud` → 误判删除 → 条目连同草稿与元数据被清(`WorkspaceStore+GoneImportedItems.swift:29-34` → `WorkspaceStore.swift:7796-7821`),周期性丢数据。 -6. 三本 digest 账区分:`.common` 共享项 `contentDigest` 是可携带完整性闸(`CoursePortableState.swift:381-393`)必须保持刷新;`noteBackingContentDigestsByItemID` 是 Agent 落盘确认(`WorkspaceStore.swift:9602`)与崩溃恢复基线必须保留;弱化的只是"拿 digest 当信任判决去切断"。 -7. `importedFileIdentity` 必须持续刷新(Agent 授权 `WorkspaceStore.swift:13896-13906`、搜索索引 `CourseDocumentSearchIndex.swift:115-134`、Pi 扩展 `extension.ts:739-750,1516-1555` 强制要求),但只用于找回不用于拒绝。 -8. 资料项(PDF 等)"世代不同即断链"保留:删除重建的资料不得继承旧 itemID 的阅读位置/学习记忆(`ImportedIdentitySelfCheck.swift:3254-3261` 锁定)。 - -## 1.3 审查确认可安全拆除(修正落地后) - -模板形态启发与模板守卫、重命名哨兵、启动分叉修复例程(`WorkspaceStore+NotesPersistence.swift:502-639` + `Sources/WeiBeiCore/NoteDivergenceRepair.swift`)、启动指纹断链(笔记部分)、`PendingNoteWriteState.baselineContentDigest`(纯写无读账)。 - ---- - -# 2. 目标与非目标 - -**目标**:Finder 里增改删文件 App 都采用、可用、不报警;全 App 一种哲学"文件即真相";任何销毁前必有副本;iCloud/网盘瞬断零误报;代码净减少(拆多于增)。 - -**不做**:不碰笔记 Markdown 格式、Agent 能力、界面视觉;不删多机搬运能力;不做 iCloud 专用同步逻辑;不改变写回成功路径性能。 - ---- - -# 3. 设计原则(最高裁决) - -1. 文件即真相:外部增删改一律采用,无"记录为准"的判决点; -2. 不主动报警:一时读不到→静默重试;只在用户实际使用时显示状态;永不出现定时/启动横幅; -3. 一道锁:所有写盘共用一个底层写闸门; -4. 副本先行:任何销毁动作之前先写备份环; -5. 身份只用于找回不用于拒绝; -6. 笔记与资料区别对待。 - ---- - -# 4. 任务一:设置中的「资料库位置」迁移入口 - -分支:`codex/library-location-setting`(从最新 `origin/main` 拉,当天推送建草稿 PR)。 - -## 4.1 产品行为(逐屏) - -- 设置「通用」区新增一行「资料库位置」:左为标题,右为当前完整路径(截断显示,悬停见全)+「更改…」按钮; -- 点「更改…」→ `NSOpenPanel`(仅选目录)→ 选中后弹确认框:显示「从 X 迁移到 Y」、预计文件数与体积、警告"迁移期间请勿操作 App"; -- 确认 → 行内进度条(迁移中禁用一切设置交互)→ 成功:路径更新 + 短暂成功提示;失败:红色错误条 + 原路径不变; -- 目标位于 iCloud/网盘同步目录(判定:路径含 `Library/Mobile Documents` 或常见云盘目录名):确认框内多一句黄色提示,不阻止; -- 迁移期间:写回、3 秒对账、课程笔记加载全部挂起;正在编辑的笔记先正常落盘再开始搬。 - -## 4.2 实现步骤(按提交顺序) - -**第 1 步:`migrateLibrary(to:)` 核心方法**(新代码全部落在 `WorkspaceStore+LibraryRoot.swift`,不碰冻结文件): - -``` -func migrateLibrary(to destination: URL) async throws -> LibraryMigrationResult -``` - -1. 前置校验(任一不满足则抛出带用户文案的错误): - - destination 不在当前库内部、不是当前库的上级、不等于当前库; - - destination 存在且非空:若含合法魏碑课程清单(`.weibei/course.json`)→ 抛 `.destinationIsLibrary`(UI 改走「认领」流程并明确提示);否则抛 `.destinationNotEmpty`; -2. `flushPendingNotePersistence` 落盘当前编辑 → 置 `libraryMigrationInFlight = true`(写回/对账/课程笔记加载检查此标志挂起); -3. 同卷(`st_dev` 相同):`FileManager.moveItem(libraryRoot, destination)`,原子完成; - 跨卷:逐个顶层条目 `moveItem` 到临时目录 `destination-weibei-migrating`,全部成功后 `moveItem(临时目录, destination)`;任一失败 → 已搬的搬回 → 抛错; -4. `applyBoundLibraryRoot(destination, identity:, bookmark:)` 重绑 → `refreshRuntimeItemURLs()` 重扫 → 逐课程校验 `courseManifestCourseID` 全部匹配; -5. `libraryMigrationInFlight = false` → 持久化 → 记 `WeiBeiLog`(阶段码 + 结果码,不记路径隐私)。 - -**第 2 步:设置 UI**(`SettingsView.swift` 新增设置组,复用现有 `settingsGroup`/`compactMenu` 模式): - -- 路径显示行 +「更改…」按钮 + 确认对话框 + 进度/错误呈现; -- 迁移中状态绑定 `libraryMigrationInFlight`,禁用按钮与相关设置项; -- 「认领已存在的库」流程:同一面板,检测到目标是合法库时确认框文案改为「认领此位置的现有资料库?」,确认后走 `bindLibraryRootOnThisComputer` 同款校验 + `applyBoundLibraryRoot`,不做文件移动。 - -**第 3 步:测试**(`Tests/WeiBeiSafetyTests/` 新增 `LibraryMigrationSafetyTests.swift`): - -- `migrateLibraryMovesTreeAndRebinds`:临时双目录,迁移后全部课程/笔记/材料可打开、原目录消失、绑定指向新位置; -- `migrateLibraryRejectsNestedAndNonEmpty`:目标嵌套/非空拒绝且原库不动; -- `migrateLibraryAdoptsExistingLibrary`:目标是合法库走认领,无文件移动; -- `migrateLibraryFailureKeepsOriginal`:注入移动失败(只读目标),原库原绑定纹丝不动; -- `migrateLibrarySuspendsAndResumesServices`:迁移中写回挂起、完成后恢复; -- 迁移涉及文件移动/删除,以上即仓库完成定义要求的专项自动验证。 - -**第 4 步:验证与冒烟**: - -``` -swift build -swift run WeiBeiSelfCheck -swift test --filter LibraryMigrationSafetyTests(CI 执行,本机无 Xcode) -./script/check_file_growth.sh (确认冻结文件零增长) -``` - -CI 绿后打候选包,用户真实冒烟:设置里把库迁到 `~/魏碑资料库-迁移测试`,确认笔记全部可开后迁回。 - -## 4.3 共享核心面占用登记 - -预计 `SettingsView.swift`(接线)、`Tests/`(新测试文件)、可能 `WeiBeiSelfCheck/main.swift`(若加源码断言)——PR 中登记,合并即释放。 - ---- - -# 5. 任务二:文件模型收敛(五阶段,顺序推进,各自独立分支/PR/验收) - -## 阶段 0:行为基线冻结 - -分支 `codex/filemodel-phase0-baseline`。 - -1. 跑全量现有测试确认绿(记录基线清单); -2. 新增两个**当前必失败**的测试(标注为预期失败,不进 CI 门槛,阶段 2 转正式): - - `externalDeleteKeepsUnsavedInput`:编辑中外部删除文件,未落盘输入应可从备份环找回(现状:直接丢); - - `useDiskConflictKeepsUserVersion`:冲突条选「使用磁盘版本」后,用户版本应可从备份环找回(现状:checkpoint 被删); -3. 在 `WorkspaceStore.swift:17987-17992`(repair→retry 顺序锁)等关键约束处补注释引用本计划; -4. 验收:`swift build` + `swift run WeiBeiSelfCheck` 绿,零行为变化,回退自查表全 N/A。 - -## 阶段 1:底层写闸门(核心锁) - -分支 `codex/filemodel-phase1-write-gate`。 - -1. 在 `WorkspaceStore+NotesPersistence.swift` 的 `writeNotebookMarkdown`(:420-422,全仓唯一底层笔记写盘函数)内置比对: - - 入参增加 `expectedBaseline: String?`(调用方传入自己认为的磁盘基线 digest); - - 写前重读磁盘 digest:**重读失败或 baseline 缺失 ⇒ 抛 `.writeRefusedKeepContent`**(调用方保留待写内容到草稿/恢复仓); - - **重读 digest ≠ baseline ⇒ 先将待写内容 `NoteBackupRing.capture(content:)`,再抛 `.diskChangedAdoptDisk`**(调用方改为采用磁盘内容并刷新编辑器); - - 一致 ⇒ 原子写,写后刷新 `noteBackingContentDigestsByItemID` 与 `lastSelfWrittenNoteDigestsByItemID`; -2. 全部写路径强制经此函数并传基线: - - `persistNote`(现 `writeNoteMarkdownTriple` :692-759 改为薄封装,模板守卫此阶段保留并存); - - rename 标题改写(现直写点 :217 改走闸门;rename 的身份偷换回滚 :183-211 与写后校验 :218-230 保留); - - repair restoreDraft(:584)、`retryRestoredPendingNoteWrites`(:476-500)、`persistAgentActionNote`(`WorkspaceStore.swift:9586-9607`); -3. 源码断言(`WeiBeiSelfCheck/main.swift`,SAFETY 前缀):禁止出现绕过 `writeNotebookMarkdown` 的新笔记写盘点(对 `notebookMarkdownWriter(` 直接调用做白名单制); -4. 新测试 `WriteGateSafetyTests.swift`:无基线拒写、重读失败拒写、摘要不符副本先行且采用磁盘、四条写路径全覆盖、kill 模拟原子性; -5. 验收:CI 绿;用户冒烟:正常编辑一条笔记(应无感)、用外部编辑器改同一文件后在 App 里继续编辑(应看到磁盘内容被采用且自己的输入在备份中);回退自查表逐条作答。 - -## 阶段 2:副本先行与外部删除保护 - -分支 `codex/filemodel-phase2-backup-first`。 - -1. 采用外部内容前副本先行,接入点: - - 对账 `applyCourseFileObservations` 刷新条目时(`WorkspaceStore.swift:17899-17914`); - - `scheduleCourseNoteLoad` 静默采纳磁盘时(:18661-18674); - - `refreshActiveNoteFromBackingFile`(:18752-18807); - - 判定源统一为「存在未落盘内容」:`notesByItemID[id] != nil || pendingNotePersistenceByItemID[id] != nil || 编辑器 dirty checkpoint 存在`; -2. 外部删除保护: - - `applyCourseFileObservations` 的 gone 判定(:17866-17872)不再直接 `forgetGoneImportedItem`:文件缺席时条目置 `fileMissingSince = Date()` 灰态保留;连续两个对账周期(≈6 秒)仍缺席才走 `removeItemRegistration`,且移除前对未落盘内容副本先行(修 `WorkspaceStore.swift:7797-7804`); - - 灰态条目在列表显示「文件不存在」;期间文件重新出现 → 按相对路径认领回**同一 itemID**,关联/阅读位置/配对不丢(修"撤销变新条目"问题); -3. 冲突条修复:`resolveNoteEditorRecoveryConflict(useDisk: true)`(`WorkspaceStore+NoteEditing.swift:233-255`)执行前先把用户版本 `NoteBackupRing.capture(content:)`,按钮副标题注明「魏碑中的修改已存入备份」; -4. 阶段 0 的两个预期失败测试转正式(现在应通过);新增 `goneItemGraysAndReclaims`、`goneItemRemovalBacksUpDraft`; -5. 验收:CI 绿;用户冒烟:编辑中在 Finder 删除该笔记(输入不丢、条目灰态)、Cmd-Z 放回(原样回来)、制造一次冲突选「使用磁盘版本」(自己的版本可找回);回退自查表。 - -## 阶段 3:容断与 iCloud 占位符 - -分支 `codex/filemodel-phase3-transient-tolerance`。 - -1. 占位符识别(`CourseProjectRootSupport.swift` 扫描层,:2652 附近): - - 目录枚举不再一刀切 `.skipsHiddenFiles`;对 `^\..+\.(md|markdown|pdf|html)\.icloud$` 形态的项还原为逻辑路径 `名字.md`,标记 `isMaterialized = false`; - - `entryPresence` 对逻辑路径:实体不存在但占位符存在 ⇒ 新 case `.presentUnmaterialized`,**永不判 absent**; -2. 展示:占位符条目正常显示;用户点开 → `Data(contentsOf:)` 触发系统下载,期间编辑器空态显示「正在从 iCloud 下载…」;下载失败/超时 ⇒ 条内状态「当前不可用,iCloud 文件未下载」,不弹横幅; -3. 删除启动指纹断链(`WorkspaceStore+LibraryRoot.swift:245-249` 的笔记部分):digest 不符不再 `urlPath = nil`;资料项(非笔记)世代保护保留为:重建文件世代不同(identity 不匹配且 manifest 不符)→ 按新条目处理,不继承旧 itemID 进度; -4. `setNoteFileError` 的 `showImportantOperationError` 通道在笔记不可用场景降格为条内状态(阶段 2 灰态机制复用);`showImportantOperationError` 本身保留给其他真实重要错误; -5. 新测试 `TransientToleranceSafetyTests.swift`:占位符识别、占位符不被判删除、瞬断无横幅、资料世代保护、启动无断链; -6. 验收:CI 绿;用户冒烟:把库放在 iCloud 目录(本机现状)重启三次、强制驱逐一个文件后打开它;回退自查表。 - -## 阶段 4:冗余锁拆除与测试重构 - -分支 `codex/filemodel-phase4-guard-removal`。前置:阶段 1-3 全绿;显示层确认"读失败时 `noteText` 永不出现模板内容"。 - -1. 拆除(按序): - - 模板形态启发 `NoteTemplateShape` 与模板覆盖守卫(`WorkspaceStore+NotesPersistence.swift:703-729`,已被写闸门严格覆盖); - - 重命名哨兵(:137-152); - - 启动分叉修复例程(:502-639 + `Sources/WeiBeiCore/NoteDivergenceRepair.swift` + `main.swift:2098-2260` 自检);`retryRestoredPendingNoteWrites` 改走写闸门(消除 repair→retry 顺序依赖,删除 :17987-17992 顺序注释); - - `PendingNoteWriteState.baselineContentDigest`(`WorkspaceModels.swift:1883-1889` 及全部读写点); -2. 测试重写(清单见 §6);侧栏令牌剔除 digest 分量(`CourseSidebarModel.swift:31,49`,revision/byte/mtime 兜底);`canCoalesceDuplicateItem` 不动; -3. 8/12 事故全场景回归测试 `PoetryIncidentRegressionTests.swift`:读盘失败 → 降级显示 → 编辑 → 写回 / 改名 / 重启 retry,正文必不丢,逐通道断言; -4. 验收:CI 绿 + 事故场景复现冒烟;PR 附代码净减少量统计(预期净减 >1000 行);回退自查表。 - -## 阶段 5:身份语义对齐与收尾 - -分支 `codex/filemodel-phase5-identity-cleanup`。 - -1. 三处"身份用于拒绝"对齐为"只用于找回": - - `verifiedCourseOwnedNoteAccess`(`WorkspaceStore.swift:18039-18084`):身份不符改为刷新记录 + 记日志,与 :17158-17161 既有红线注释统一; - - 搜索索引身份闸门(`CourseDocumentSearchIndex.swift:121-130`):不符降级为日志并照索引(fd 级 TOCTOU 保护已有); - - `makeAgentFileGrant`(:13896-13906):同步对齐,Pi 扩展侧(`extension.ts:739-750,1516-1555`)协议不变仅放宽拒绝条件; -2. `.common` 共享项 digest 保持对账刷新(可携带完整性闸不动);courseOwned 笔记 digest 降格为写闸门比对专用; -3. 更新 AGENTS.md 与相关注释,把"文件即真相 + 一道锁 + 副本先行"写成仓库明文约定; -4. 全量回归(含 Pi 终止语义、编辑器自检、安全测试全量)+ 用户完整验收清单(约十二项普通使用场景)。 - ---- - -# 6. 测试影响清单(阶段 4 重写对象) - -- `Sources/WeiBeiSelfCheck/main.swift:2098-2279`(修复规划器全部 fixture + 顺序/模板/哨兵源码断言); -- `Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift:1436/1505-1506、1801/1884、2039、2725、2780/2832、2958/2999、3199-3261`; -- `Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift` 可携带/共享 digest 断言(:2262-2288、3062-3171、5500、6173-6224、6340、6451、6510)——仅改弱化语义部分,可携带校验本身不动; -- `SelfCheckNotes.swift:9-43`(`baselineContentDigest` 回环断言)。 - -明确不动:`LibraryRelativeOnlyTests.swift:114-135`、`SelfCheckImport.swift:52-59`、可携带快照双校验相关测试。 - ---- - -# 7. 风险登记 - -| 风险 | 等级 | 缓解 | -|---|---|---| -| 写闸门遗漏写路径,事故通道重开 | 高 | 全部写路径强制走底层函数 + 源码断言防新增绕过点;阶段 4 事故全场景回归 | -| 备份环 20 份/50MB 上限,高频覆写副本被逐出 | 中 | 如实标注为缓冲非保险;必要时调上限 | -| 占位符识别漏非 iCloud 云盘形态 | 中 | 通用后缀匹配 + 持续缺席灰态兜底,不绑死 iCloud | -| 行为变更导致老用户数据问题 | 中 | 每阶段独立验收;不改任何磁盘格式 | -| 阶段间半成品状态长期使用 | 低 | 每阶段独立可发布;写闸门与旧锁并存期无行为冲突 | - ---- - -# 8. 已拍板事项 - -1. 多机搬运能力:**保留,不动**(用户不依赖,但保留无成本;快照双校验不属于拆除对象); -2. 迁移目标在云同步目录:**提示但不阻止**; -3. 横幅最终形态:**条目灰态/条内状态,可见性不降,不主动弹**; -4. 零体验回退为第一约束,每阶段 PR 附回退自查表。 - ---- - -# 9. 执行顺序总览 - -1. 任务一(迁移入口):分支 `codex/library-location-setting`; -2. 任务二阶段 0-5:每阶段一个分支一个 PR,按顺序推进,不并行; -3. 全部合入后:从干净 main 打候选版,给用户一份约十二项的普通使用场景清单整体验收。 diff --git a/Sources/WeiBei/Editing/WorkspaceStore+NoteEditing.swift b/Sources/WeiBei/Editing/WorkspaceStore+NoteEditing.swift index f63e0d27d..6927c7f9f 100644 --- a/Sources/WeiBei/Editing/WorkspaceStore+NoteEditing.swift +++ b/Sources/WeiBei/Editing/WorkspaceStore+NoteEditing.swift @@ -235,12 +235,6 @@ extension WorkspaceStore { noteEditorRecoveryConflict = nil if useDisk { let documentID = conflict.checkpoint.metadata.documentID - // 副本先行(计划 §5 阶段2):选磁盘版本前,用户版本先入备份环。 - _ = try? NoteBackupRing.capture( - content: Data(conflict.checkpoint.markdown.utf8), - itemID: documentID, - rootURL: noteBackupRootURL - ) try? await noteRecoveryStore.remove(documentID: documentID) cancelPendingNotePersistence(for: documentID) pendingNotePersistenceByItemID.removeValue(forKey: documentID) diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index 1058732e5..5594609c4 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -5363,11 +5363,6 @@ enum CourseProjectRootError: LocalizedError { case metadataConflict case manifestMismatch case workspaceSaveFailed - case destinationInsideLibrary - case destinationContainsLibrary - case destinationIsLibrary - case destinationNotEmpty - case migrationFailed(String) var errorDescription: String? { switch self { @@ -5411,18 +5406,6 @@ enum CourseProjectRootError: LocalizedError { return "课程 manifest 与当前课程记录冲突。" case .workspaceSaveFailed: return "课程状态没有成功保存。魏碑只撤销能确认属于本次操作的内容;如果磁盘内容已经变化,会原样保留。" - case .destinationInsideLibrary: - return "所选位置在当前资料库内部,请选择资料库之外的位置。" - case .destinationContainsLibrary: - return "所选位置是当前资料库的上级目录,请选择其他位置。" - case .destinationIsLibrary: - return "所选位置已经是一个魏碑资料库,可以直接认领。" - case .destinationNotEmpty: - return "所选文件夹不是空的,迁移需要一个空文件夹。" - case .migrationFailed(let detail): - return detail.isEmpty - ? "资料库迁移未完成,原资料库保持不变。" - : "资料库迁移未完成:\(detail)。原资料库保持不变。" } } } diff --git a/Sources/WeiBei/Stores/WorkspaceStore+GoneImportedItems.swift b/Sources/WeiBei/Stores/WorkspaceStore+GoneImportedItems.swift index 07a6ff7da..004b4c0d0 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+GoneImportedItems.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+GoneImportedItems.swift @@ -3,19 +3,6 @@ import WeiBeiCore @MainActor extension WorkspaceStore { - /// 副本先行(计划 §5 阶段2):采用外部内容或销毁条目前,把未落盘内容存入备份环。 - func backUpUnsavedNoteContentBeforeAdopting(itemID: String) { - guard let unsaved = pendingNotePersistenceByItemID[itemID]?.markdown - ?? notesByItemID[itemID] else { - return - } - _ = try? NoteBackupRing.capture( - content: Data(unsaved.utf8), - itemID: itemID, - rootURL: noteBackupRootURL - ) - } - @discardableResult func forgetGoneImportedItem(at index: Int) -> (url: URL?, changed: Bool) { guard importedItems.indices.contains(index) else { return (nil, false) } @@ -36,7 +23,6 @@ extension WorkspaceStore { } switch CourseProjectFileWorker.entryPresence(at: candidate) { case .present: - fileMissingSinceByItemID.removeValue(forKey: item.id) return (candidate.standardizedFileURL, false) case .inaccessible: return keepUnavailableImportedItem(at: index) @@ -44,20 +30,8 @@ extension WorkspaceStore { let parent = candidate.deletingLastPathComponent() switch CourseProjectFileWorker.entryPresence(at: parent) { case .present: - // 灰态保护(计划 §5 阶段2):iCloud 瞬断/同步延迟期间文件缺席 - // 不立即销毁条目;连续两个对账周期(≈6 秒)仍缺席才移除, - // 移除前对未落盘内容副本先行。文件重新出现按相对路径认领回原条目。 - if let missingSince = fileMissingSinceByItemID[item.id] { - if Date().timeIntervalSince(missingSince) >= 6.0 { - backUpUnsavedNoteContentBeforeAdopting(itemID: item.id) - removeItemRegistration(item.id) - fileMissingSinceByItemID.removeValue(forKey: item.id) - return (nil, true) - } - } else { - fileMissingSinceByItemID[item.id] = Date() - } - return keepUnavailableImportedItem(at: index) + removeItemRegistration(item.id) + return (nil, true) case .absent, .inaccessible: return keepUnavailableImportedItem(at: index) } diff --git a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift index 7980bf95e..aef580e0e 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift @@ -262,151 +262,6 @@ extension WorkspaceStore { } } - struct LibraryMigrationResult { - let destination: URL - let movedItemCount: Int - } - - func migrateLibrary(to destination: URL) async throws -> LibraryMigrationResult { - guard let libraryRoot = courseLibraryRootURL else { - throw CourseProjectRootError.missingLibrary - } - try validateMigrationDestinationRelationship( - destination, - libraryRoot: libraryRoot - ) - let canonicalDestination: URL - if FileManager.default.fileExists(atPath: destination.path) { - canonicalDestination = try CourseProjectPathPolicy.existingDirectory(destination) - try validateMigrationDestinationContent(canonicalDestination) - } else { - let parent = try CourseProjectPathPolicy.existingDirectory( - destination.deletingLastPathComponent() - ) - canonicalDestination = parent.appendingPathComponent( - destination.lastPathComponent, - isDirectory: true - ) - } - - flushPendingNotePersistence() - libraryMigrationInFlight = true - defer { libraryMigrationInFlight = false } - - let fileManager = FileManager.default - let sameVolume = Self.volumeDeviceID(of: libraryRoot) - == Self.volumeDeviceID(of: canonicalDestination.deletingLastPathComponent()) - var movedBack: [URL] = [] - do { - if sameVolume { - if fileManager.fileExists(atPath: canonicalDestination.path) { - try fileManager.removeItem(at: canonicalDestination) - } - try fileManager.moveItem(at: libraryRoot, to: canonicalDestination) - } else { - let staging = canonicalDestination.deletingLastPathComponent() - .appendingPathComponent( - canonicalDestination.lastPathComponent + "-weibei-migrating", - isDirectory: true - ) - try? fileManager.removeItem(at: staging) - try fileManager.createDirectory(at: staging, withIntermediateDirectories: true) - let entries = try fileManager.contentsOfDirectory( - at: libraryRoot, - includingPropertiesForKeys: nil - ) - for entry in entries { - let target = staging.appendingPathComponent(entry.lastPathComponent) - try fileManager.moveItem(at: entry, to: target) - movedBack.append(target) - } - if fileManager.fileExists(atPath: canonicalDestination.path) { - try fileManager.removeItem(at: canonicalDestination) - } - try fileManager.moveItem(at: staging, to: canonicalDestination) - } - } catch { - for staged in movedBack.reversed() { - try? fileManager.moveItem( - at: staged, - to: libraryRoot.appendingPathComponent(staged.lastPathComponent) - ) - } - throw CourseProjectRootError.migrationFailed(error.localizedDescription) - } - - guard let identity = importedFileIdentityResolver(canonicalDestination), - let bookmark = courseRootBookmarkMaker(canonicalDestination) else { - applyBoundLibraryRoot(libraryRoot, identity: courseLibraryRootIdentity, bookmark: courseLibraryRootBookmarkData) - throw CourseProjectRootError.rootIdentityUnavailable - } - applyBoundLibraryRoot(canonicalDestination, identity: identity, bookmark: bookmark) - for course in courses { - guard let relativePath = course.sourceRootRelativePath, - let folder = CourseProjectPathPolicy.resolvedRelativePath( - relativePath, - inside: canonicalDestination - ) else { - continue - } - resolvedCourseRootURLs[course.id] = folder - courseRootUnavailableReasons.removeValue(forKey: course.id) - _ = resolveCourseOwnedItems(for: course.id) - } - refreshRuntimeItemURLs() - for course in courses { - guard let relativePath = course.sourceRootRelativePath, - let folder = CourseProjectPathPolicy.resolvedRelativePath( - relativePath, - inside: canonicalDestination - ), - courseManifestCourseID(at: folder) == course.id else { - throw CourseProjectRootError.migrationFailed( - ui("课程 \(course.title) 的清单校验未通过", "Course manifest check failed for \(course.title)") - ) - } - } - courseDocumentSearchIndex.synchronize(allItems) - invalidateAgentContext() - libraryMigrationInFlight = false - flushPendingNotePersistence(flushWorkspace: false) - _ = await persistWorkspaceNow() - WeiBeiLog.workspace.notice("library_migration_completed") - return LibraryMigrationResult( - destination: canonicalDestination, - movedItemCount: (try? fileManager.contentsOfDirectory(at: canonicalDestination, includingPropertiesForKeys: nil))?.count ?? 0 - ) - } - - private func validateMigrationDestinationRelationship(_ destination: URL, libraryRoot: URL) throws { - let rootPath = libraryRoot.standardizedFileURL.path - let destinationPath = destination.standardizedFileURL.path - if destinationPath == rootPath { - throw CourseProjectRootError.destinationIsLibrary - } - if destinationPath.hasPrefix(rootPath + "/") { - throw CourseProjectRootError.destinationInsideLibrary - } - if rootPath.hasPrefix(destinationPath + "/") { - throw CourseProjectRootError.destinationContainsLibrary - } - } - - private func validateMigrationDestinationContent(_ destination: URL) throws { - let entries = try FileManager.default.contentsOfDirectory(atPath: destination.path) - guard !entries.isEmpty else { return } - if courseManifestCourseID(at: destination) != nil { - throw CourseProjectRootError.destinationIsLibrary - } - throw CourseProjectRootError.destinationNotEmpty - } - - private static func volumeDeviceID(of url: URL) -> dev_t? { - var statBuffer = stat() - guard stat(url.path, &statBuffer) == 0 else { return nil } - return statBuffer.st_dev - } - /// Applies already-copied common-library files to the item model in one /// MainActor transaction after the background copy loop finishes. func applyImportedCommonFiles( diff --git a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift index a073967cb..1c3b00a66 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift @@ -3,20 +3,6 @@ import CryptoKit import Foundation import WeiBeiCore -enum NoteWriteGateError: LocalizedError { - case writeRefusedKeepContent - case diskChangedAdoptDisk - - var errorDescription: String? { - switch self { - case .writeRefusedKeepContent: - return "磁盘内容无法确认,写入已暂停以保护正文。" - case .diskChangedAdoptDisk: - return "笔记文件已被外部修改,已采用磁盘内容。" - } - } -} - @MainActor extension WorkspaceStore { func quotedReferenceBlock(text: String, sourceTitle: String) -> String { @@ -106,7 +92,7 @@ extension WorkspaceStore { } } - func renameNotebookNoteInTransaction( + private func renameNotebookNoteInTransaction( itemID: String, to rawTitle: String ) async { @@ -228,17 +214,7 @@ extension WorkspaceStore { Data(retitledMarkdown.utf8) ) if willRewriteMarkdown { - // 写闸门:以移动后磁盘现况为基线;不符即中止并走统一回滚。 - let priorBackingDigest = noteBackingContentDigestsByItemID[oldID] - let priorLastSelfDigest = lastSelfWrittenNoteDigestsByItemID[oldID] - try writeNotebookMarkdownThroughGate( - retitledMarkdown, - itemID: oldID, - url: newURL, - expectedBaseline: Self.noteContentDigest(at: newURL) - ) - noteBackingContentDigestsByItemID[oldID] = priorBackingDigest - lastSelfWrittenNoteDigestsByItemID[oldID] = priorLastSelfDigest + try notebookMarkdownWriter(retitledMarkdown, newURL) let writtenDigest = Self.noteContentDigest(at: newURL) guard writtenDigest == expectedOutputDigest else { throw NSError( @@ -605,13 +581,10 @@ extension WorkspaceStore { continue } do { - // 写闸门:以刚备份的磁盘现况为基线;不符则拒绝写回(草稿保留)。 - try writeNotebookMarkdownThroughGate( - draft, - itemID: itemID, - url: plan.url, - expectedBaseline: Self.noteContentDigest(at: plan.url) - ) + try notebookMarkdownWriter(draft, plan.url) + let writtenDigest = Self.noteContentDigest(Data(draft.utf8)) + noteBackingContentDigestsByItemID[itemID] = writtenDigest + lastSelfWrittenNoteDigestsByItemID[itemID] = writtenDigest setNoteDraft(nil, for: itemID) setNoteFileError(nil, for: itemID) if let refreshed = refreshImportedFileTracking( @@ -666,7 +639,6 @@ extension WorkspaceStore { } func persistCurrentNote() { - guard !libraryMigrationInFlight else { return } guard let item = activeNoteItem else { return } if pendingNotePersistenceByItemID[item.id] != nil { flushPendingNotePersistence(for: item.id) @@ -704,7 +676,6 @@ extension WorkspaceStore { } func flushPendingNotePersistence(for itemID: String) { - guard !libraryMigrationInFlight else { return } cancelPendingNotePersistence(for: itemID) guard let pending = pendingNotePersistenceByItemID.removeValue(forKey: itemID) else { return } WeiBeiPerf.measure("note.persist.flush", extra: "item=\(itemID)") { @@ -718,9 +689,8 @@ extension WorkspaceStore { pendingNotePersistenceTasks[itemID] = nil } - /// S2 三件套:备份(外部改动)→ 闸门比对 → 原子写 → 失败留草稿。 - /// 阶段1 写闸门:比对下沉到唯一底层入口,模板守卫此阶段并存(计划 §5 阶段1)。 - /// 返回是否成功写回磁盘。 + /// S2 三件套:备份(外部改动)→ 原子写 → 失败留草稿。 + /// 返回是否成功写回磁盘。永不因 digest 冲突拒绝写回。 @discardableResult func writeNoteMarkdownTriple( _ markdown: String, @@ -765,23 +735,16 @@ extension WorkspaceStore { rootURL: noteBackupRootURL ) } - if noteBackingContentDigestsByItemID[itemID] == nil, - let digest = importedItems.first(where: { $0.id == itemID })?.contentDigest { - noteBackingContentDigestsByItemID[itemID] = digest - } do { - try writeNotebookMarkdownThroughGate( - markdown, - itemID: itemID, - url: url, - expectedBaseline: noteBackingContentDigestsByItemID[itemID] - ) - } catch NoteWriteGateError.writeRefusedKeepContent { - retainUnreachableNoteDraft(markdown, itemID: itemID) - return false - } catch NoteWriteGateError.diskChangedAdoptDisk { - adoptExternalDiskNote(itemID: itemID, url: url) - return false + try notebookMarkdownWriter(markdown, url) + let writtenDigest = Self.noteContentDigest(Data(markdown.utf8)) + noteBackingContentDigestsByItemID[itemID] = writtenDigest + lastSelfWrittenNoteDigestsByItemID[itemID] = writtenDigest + setNoteDraft(nil, for: itemID) + pendingNoteWritesByItemID.removeValue(forKey: itemID) + setNoteFileError(nil, for: itemID) + noteEditorDidPersist(markdown, documentID: itemID) + return true } catch { setNoteDraft(markdown, for: itemID) pendingNoteWritesByItemID.removeValue(forKey: itemID) @@ -793,60 +756,6 @@ extension WorkspaceStore { ) return false } - setNoteDraft(nil, for: itemID) - pendingNoteWritesByItemID.removeValue(forKey: itemID) - setNoteFileError(nil, for: itemID) - noteEditorDidPersist(markdown, documentID: itemID) - return true - } - - /// 磁盘内容被外部修改时采用磁盘:待写内容已先入备份环,这里刷新编辑器状态。 - func adoptExternalDiskNote(itemID: String, url: URL) { - guard let diskMarkdown = try? String(contentsOf: url, encoding: .utf8) else { return } - let digest = Self.noteContentDigest(Data(diskMarkdown.utf8)) - noteBackingContentDigestsByItemID[itemID] = digest - lastSelfWrittenNoteDigestsByItemID[itemID] = digest - pendingNoteWritesByItemID.removeValue(forKey: itemID) - setNoteDraft(nil, for: itemID) - loadedCourseNoteTextByItemID[itemID] = diskMarkdown - if activeNoteItemID == itemID { - noteText = diskMarkdown - noteEditingSession.replaceDocument(with: itemID) - noteEditorCommand = NoteEditorCommand( - kind: .reloadDocument, - markdown: diskMarkdown - ) - } - } - - /// 全仓唯一笔记写盘闸门(计划 §5 阶段1):所有写路径必须经此函数。 - /// 文件在场时写前重读磁盘 digest:重读失败或无基线 ⇒ 拒写并保留待写内容; - /// 摘要不符 ⇒ 待写内容先入备份环再抛采用磁盘;一致才落盘并刷新双 digest。 - /// 禁止绕过本函数直接调用 notebookMarkdownWriter(SelfCheck SAFETY 断言白名单)。 - func writeNotebookMarkdownThroughGate( - _ markdown: String, - itemID: String, - url: URL, - expectedBaseline: String? - ) throws { - if FileManager.default.fileExists(atPath: url.path) { - guard let expectedBaseline, - let diskDigest = Self.noteContentDigest(at: url) else { - throw NoteWriteGateError.writeRefusedKeepContent - } - if diskDigest != expectedBaseline { - _ = try? NoteBackupRing.capture( - content: Data(markdown.utf8), - itemID: itemID, - rootURL: noteBackupRootURL - ) - throw NoteWriteGateError.diskChangedAdoptDisk - } - } - try notebookMarkdownWriter(markdown, url) - let writtenDigest = Self.noteContentDigest(Data(markdown.utf8)) - noteBackingContentDigestsByItemID[itemID] = writtenDigest - lastSelfWrittenNoteDigestsByItemID[itemID] = writtenDigest } /// 文件不可达时静默保留草稿(无冲突横幅)。 diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index a6b6ab043..fc1484a95 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -327,10 +327,6 @@ final class WorkspaceStore: ObservableObject { var courseLibraryRootBookmarkData: Data? var courseLibraryRootURL: URL? var courseLibraryUnavailableReason: String? - /// 资料库迁移进行中:写回、3 秒对账、课程笔记加载全部挂起(计划 §4.2)。 - @Published var libraryMigrationInFlight = false - /// 外部文件缺席灰态(计划 §5 阶段2):首缺席记时间,两个对账周期仍缺席才移除条目。 - var fileMissingSinceByItemID: [String: Date] = [:] @Published private(set) var courseItemMemberships: [CourseItemMembership] = [] { didSet { courseMembershipIndex = CourseItemMemberships(values: courseItemMemberships) @@ -633,7 +629,7 @@ final class WorkspaceStore: ObservableObject { /// 只有基线==当前文件名时才跟随抬头改名;对不上说明文件名被外部动过, /// 先登记、不动文件。内存态即可:重启丢基线只少一次自动改名,方向安全。 var headingSyncedNoteStemByItemID: [String: String] = [:] - var loadedCourseNoteTextByItemID: [String: String] = [:] + private var loadedCourseNoteTextByItemID: [String: String] = [:] var courseNoteLoadTasksByItemID: [String: Task] = [:] private var courseNoteLoadGenerationByItemID: [String: UInt64] = [:] private var courseNoteWritesInFlight = Set() @@ -750,8 +746,8 @@ final class WorkspaceStore: ObservableObject { #if DEBUG private var usesBackgroundWorkspacePersistenceForSelfCheck = false #endif - var resolvedCourseRootURLs: [UUID: URL] = [:] - var courseRootUnavailableReasons: [UUID: String] = [:] + private var resolvedCourseRootURLs: [UUID: URL] = [:] + private var courseRootUnavailableReasons: [UUID: String] = [:] private let courseProjectFileWorker = CourseProjectFileWorker() private var courseReconciliationTask: Task? private var courseReconciliationInFlight = false @@ -7796,7 +7792,6 @@ final class WorkspaceStore: ObservableObject { } func removeItemRegistration(_ itemID: String) { - fileMissingSinceByItemID.removeValue(forKey: itemID) pendingNotePersistenceTasks.removeValue(forKey: itemID)?.cancel() courseNoteLoadTasksByItemID.removeValue(forKey: itemID)?.cancel() courseNoteWriteTasksByItemID.removeValue(forKey: itemID)?.cancel() @@ -10075,10 +10070,7 @@ final class WorkspaceStore: ObservableObject { } func displaySubtitle(for item: StudyItem) -> String { - if fileMissingSinceByItemID[item.id] != nil { - return ui("文件不存在", "File missing") - } - return item.subtitle + item.subtitle } func displayTags(for item: StudyItem, limit: Int = 3) -> [String] { @@ -17159,7 +17151,7 @@ final class WorkspaceStore: ObservableObject { } @discardableResult - func resolveCourseOwnedItems(for courseID: UUID) -> Bool { + private func resolveCourseOwnedItems(for courseID: UUID) -> Bool { var changed = false let itemIDs = importedItems.compactMap { item -> String? in guard case .courseOwned(let ownerCourseID, _) = item.storage, @@ -17184,7 +17176,6 @@ final class WorkspaceStore: ObservableObject { func reconcileCourseFilesNow(courseID requestedCourseID: UUID? = nil) async { guard !courseReconciliationInFlight else { return } - guard !libraryMigrationInFlight else { return } courseReconciliationInFlight = true defer { courseReconciliationInFlight = false } if let libraryRoot = courseLibraryRootURL { @@ -17872,10 +17863,6 @@ final class WorkspaceStore: ObservableObject { } var nextItem = importedItems[itemIndex] - if nextDigest != item.contentDigest { - backUpUnsavedNoteContentBeforeAdopting(itemID: itemID) - } - fileMissingSinceByItemID.removeValue(forKey: itemID) nextItem.title = observation.url.deletingPathExtension().lastPathComponent nextItem.subtitle = observation.url.lastPathComponent nextItem.kind = StudyItemKind.detect(from: observation.url) @@ -17965,8 +17952,6 @@ final class WorkspaceStore: ObservableObject { guard !Task.isCancelled else { return } // P0:先跑分叉修复(会丢弃/写回草稿),再跑 retry——顺序不能反, // 否则 retry 会把「读盘失败回退的模板草稿」直接盖回磁盘。 - // 约束出处:Docs/plans/2026-08-22-file-model-convergence-and-library-relocation.md §5 阶段4 - // (阶段4 写闸门落地、repair 例程拆除后,此顺序锁随之删除)。 await self?.repairDivergedNotebookNotesIfNeeded() guard !Task.isCancelled else { return } await self?.retryRestoredPendingNoteWrites() @@ -18570,7 +18555,6 @@ final class WorkspaceStore: ObservableObject { } private func scheduleCourseNoteLoad(_ item: StudyItem) { - guard !libraryMigrationInFlight else { return } guard let access = verifiedCourseOwnedNoteAccess( item ) else { @@ -18610,10 +18594,8 @@ final class WorkspaceStore: ObservableObject { let markdown = cleanLegacyPlaceholder(result.markdown) loadedCourseNoteTextByItemID[itemID] = markdown let previousDigest = importedItems[currentIndex].contentDigest - fileMissingSinceByItemID.removeValue(forKey: itemID) if let previousDigest, previousDigest != result.snapshot.sha256 { - backUpUnsavedNoteContentBeforeAdopting(itemID: itemID) importedItems[currentIndex].contentRevision &+= 1 } importedItems[currentIndex].contentDigest = diff --git a/Sources/WeiBei/Views/Settings/SettingsView.swift b/Sources/WeiBei/Views/Settings/SettingsView.swift index f53ce4f3c..655bf4419 100644 --- a/Sources/WeiBei/Views/Settings/SettingsView.swift +++ b/Sources/WeiBei/Views/Settings/SettingsView.swift @@ -38,11 +38,6 @@ struct SettingsView: View { @State private var feedbackBody = "" @State private var feedbackBusy = false @State private var feedbackStatus: String? - // 资料库位置迁移(计划 §4.1)。 - @State private var pendingMigrationDestination: URL? - @State private var migrationErrorText: String? - @State private var migrationSuccessText: String? - @State private var isMigratingLibrary = false private var buildInfo: WeiBeiAppBuildInfo { .current() } @@ -301,137 +296,7 @@ struct SettingsView: View { ) } } - - libraryLocationSettings - } - } - - private var libraryLocationSettings: some View { - settingsGroup(store.ui("资料库", "Library")) { - settingsRow( - title: store.ui("资料库位置", "Library location"), - detail: store.courseLibraryRootPath ?? CourseLibraryLayout.defaultRootURL().path, - showsBottomDivider: false - ) { - Button(store.ui("更改…", "Change…")) { - pickMigrationDestination() - } - .disabled(isMigratingLibrary) - } - if let destination = pendingMigrationDestination { - migrationConfirmation(destination) - } - if isMigratingLibrary { - VStack(alignment: .leading, spacing: 6) { - ProgressView() - .progressViewStyle(.linear) - Text(store.ui( - "正在迁移资料库,请勿操作魏碑…", - "Migrating the library. Please do not use WeiBei during the move…" - )) - .font(SettingsType.detail) - .foregroundStyle(WeiBeiTheme.secondaryInk) - } - .padding(.horizontal, 14) - .padding(.bottom, 12) - } - if let migrationErrorText { - Text(migrationErrorText) - .font(SettingsType.detail) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) - .padding(.horizontal, 14) - .padding(.bottom, 12) - } - if let migrationSuccessText { - Text(migrationSuccessText) - .font(SettingsType.detail) - .foregroundStyle(WeiBeiTheme.cinnabar) - .padding(.horizontal, 14) - .padding(.bottom, 12) - } - } - .disabled(isMigratingLibrary) - } - - @ViewBuilder - private func migrationConfirmation(_ destination: URL) -> some View { - VStack(alignment: .leading, spacing: 8) { - Text(store.ui( - "从 \(store.courseLibraryRootPath ?? "—") 迁移到 \(destination.path)", - "Move from \(store.courseLibraryRootPath ?? "—") to \(destination.path)" - )) - .font(SettingsType.detail) - .foregroundStyle(WeiBeiTheme.ink) - .fixedSize(horizontal: false, vertical: true) - if Self.isCloudSyncPath(destination) { - Text(store.ui( - "目标位于 iCloud 或网盘同步目录,可能出现文件未下载或同步冲突。", - "The destination is inside an iCloud or cloud-sync folder; files may be evicted or conflict." - )) - .font(SettingsType.detail) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - } - HStack(spacing: 10) { - Button(store.ui("开始迁移", "Start Migration")) { - confirmMigration(to: destination) - } - .buttonStyle(.borderedProminent) - Button(store.ui("取消", "Cancel")) { - pendingMigrationDestination = nil - } - } - } - .padding(.horizontal, 14) - .padding(.vertical, 4) - .padding(.bottom, 8) - } - - private func pickMigrationDestination() { - migrationErrorText = nil - migrationSuccessText = nil - let panel = NSOpenPanel() - panel.canChooseFiles = false - panel.canChooseDirectories = true - panel.canCreateDirectories = true - panel.allowsMultipleSelection = false - panel.prompt = store.ui("选择", "Choose") - guard panel.runModal() == .OK, let url = panel.url else { return } - pendingMigrationDestination = url.standardizedFileURL - } - - private func confirmMigration(to destination: URL) { - pendingMigrationDestination = nil - isMigratingLibrary = true - migrationErrorText = nil - migrationSuccessText = nil - Task { @MainActor in - do { - let result = try await store.migrateLibrary(to: destination) - migrationSuccessText = store.ui( - "已迁移到 \(result.destination.path)", - "Moved to \(result.destination.path)" - ) - } catch CourseProjectRootError.destinationIsLibrary { - migrationErrorText = store.ui( - "所选位置已经是一个魏碑资料库,请在对话中打开它或选择其他空文件夹。", - "That location is already a WeiBei library. Open it instead, or choose an empty folder." - ) - } catch { - migrationErrorText = error.localizedDescription - } - isMigratingLibrary = false - } - } - - static func isCloudSyncPath(_ url: URL) -> Bool { - let path = url.path - if path.contains("Library/Mobile Documents") || path.contains("com~apple~CloudDocs") { - return true } - let cloudNames = ["Dropbox", "Google Drive", "OneDrive", "坚果云", "iCloud"] - return cloudNames.contains { path.contains($0) } } /// Theme gallery modeled on AionUI `ThemeLayoutPreview` cards: diff --git a/Sources/WeiBeiSelfCheck/main.swift b/Sources/WeiBeiSelfCheck/main.swift index c57c130d9..2171c1dfc 100644 --- a/Sources/WeiBeiSelfCheck/main.swift +++ b/Sources/WeiBeiSelfCheck/main.swift @@ -2281,27 +2281,6 @@ do { ) } -// MARK: - Phase 1 write gate: single writer choke point (source assertions) -do { - let directWriterCalls = notesPersistenceSource - .components(separatedBy: "notebookMarkdownWriter(") - .count - 1 - let storeDirectWriterCalls = workspaceStoreSource - .components(separatedBy: "notebookMarkdownWriter(") - .count - 1 - expect( - directWriterCalls == 1 && storeDirectWriterCalls == 0, - "SAFETY:write-gate-single-writer all note disk writes must route through writeNotebookMarkdownThroughGate; direct notebookMarkdownWriter( calls are whitelisted to exactly one inside the gate" - ) - expect( - notesPersistenceSource.contains("writeRefusedKeepContent") - && notesPersistenceSource.contains("diskChangedAdoptDisk") - && notesPersistenceSource.contains("content: Data(markdown.utf8)") - && notesPersistenceSource.contains("expectedBaseline"), - "SAFETY:write-gate-compare the gate must refuse writes without a trusted baseline or an unreadable disk, back up pending content before adopting external changes, and pass an explicit baseline at every write path" - ) -} - // MARK: - Performance Phase 1+2: workspace encode guardrail + off-main hop do { // Warm-up encode so first-run JSONEncoder overhead does not dominate. diff --git a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift index f2f7359e3..63dab4ea2 100644 --- a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift @@ -7082,11 +7082,6 @@ enum CourseProjectRootSelfCheck { let finderAdded = courseRoot.appendingPathComponent("资料/Finder 新增.pdf") try Data("%PDF-1.4\nFinder".utf8).write(to: finderAdded) try store.reconcileCourseFilesForSelfCheck(courseID: courseID) - // 灰态保护:首缺席保留条目;模拟两个对账周期后移除(计划 §5 阶段2)。 - if store.importedItems.contains(where: { $0.id == noteItem.id }) { - store.fileMissingSinceByItemID[noteItem.id] = Date().addingTimeInterval(-7) - try store.reconcileCourseFilesForSelfCheck(courseID: courseID) - } try check( store.importedItems.first { $0.id == materialItem.id }?.urlPath == movedMaterial.path, @@ -7128,15 +7123,9 @@ enum CourseProjectRootSelfCheck { let displacedURL = incoming.appendingPathComponent("暂时移走的原文稿.txt") try FileManager.default.moveItem(at: courseURL, to: displacedURL) try store.reconcileCourseFilesForSelfCheck(courseID: courseID) - // 灰态保护:首缺席保留条目;模拟两个对账周期后移除(计划 §5 阶段2)。 - if store.importedItems.contains(where: { $0.id == item.id }), - store.fileMissingSinceByItemID[item.id] != nil { - store.fileMissingSinceByItemID[item.id] = Date().addingTimeInterval(-7) - try store.reconcileCourseFilesForSelfCheck(courseID: courseID) - } try check( store.importedItems.first { $0.id == item.id } == nil, - "Finder 删除后课程里还留着这条笔记" + "移出课程文件夹后文稿还留在魏碑里" ) store.presentCourseWorkspace(.hub, courseID: courseID) diff --git a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift b/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift deleted file mode 100644 index 0db0c5738..000000000 --- a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift +++ /dev/null @@ -1,188 +0,0 @@ -import Foundation -@testable import WeiBei -import WeiBeiCore -import XCTest - -/// 阶段 0 行为基线 → 阶段 2「副本先行」落地后转正式(计划 §5 阶段0→阶段2)。 -@MainActor -final class FileModelPhase0BaselineTests: XCTestCase { - override class func setUp() { - super.setUp() - setenv("WEIBEI_SAFETY_TEST_MODE", "1", 1) - } - - private func makeTempRoot(_ name: String) -> URL { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("\(name)-\(UUID().uuidString)", isDirectory: true) - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - return root - } - - private func makeStore( - base: URL, - library: URL, - backupRoot: URL - ) throws -> WorkspaceStore { - try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) - let store = WorkspaceStore( - workspaceDirectory: base.appendingPathComponent("workspace", isDirectory: true), - noteBackupRootURL: backupRoot, - startsAtBlankEntries: true, - startsCourseFileMaintenance: false - ) - try store.configureCourseLibrary(at: library) - return store - } - - private func reconcile(_ store: WorkspaceStore) throws { - try store.waitForCourseFileOperation { - await store.reconcileCourseFilesNow() - } - } - - private func backupContents( - _ backupRoot: URL, - itemID: String - ) throws -> [String] { - try NoteBackupRing.list(itemID: itemID, rootURL: backupRoot) - .compactMap { try? String(contentsOf: $0.url, encoding: .utf8) } - } - - func testExternalDeleteKeepsUnsavedInput() throws { - let base = makeTempRoot("weibei-phase0-external-delete") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "外删课") - let source = base.appendingPathComponent("诗歌.md") - try "原始正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - - let unsavedInput = "用户正在输入、尚未落盘的新内容" - store.scheduleNotePersistence(unsavedInput, for: item) - - let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) - try FileManager.default.removeItem(at: backingURL) - try reconcile(store) - - XCTAssertEqual( - store.displaySubtitle(for: item), - store.ui("文件不存在", "File missing"), - "首缺席应进入灰态而不是立即移除" - ) - XCTAssertNotNil(store.importedItems.first { $0.id == item.id }) - - store.fileMissingSinceByItemID[item.id] = Date().addingTimeInterval(-7) - try reconcile(store) - - let recovered = try backupContents(backupRoot, itemID: item.id) - XCTAssertTrue( - recovered.contains(unsavedInput), - "外部删除后未落盘输入应已存入备份环;实际备份内容:\(recovered)" - ) - } - - func testUseDiskConflictKeepsUserVersion() throws { - let base = makeTempRoot("weibei-phase0-conflict-use-disk") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "冲突课") - let source = base.appendingPathComponent("笔记.md") - try "磁盘版本".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - - let userVersion = "用户的本地修改版本" - let checkpoint = NoteRecoveryCheckpoint( - metadata: NoteRecoveryMetadata( - documentID: item.id, - baseFileDigest: Self.digest(of: "原始正文"), - checkpointDigest: Self.digest(of: userVersion), - revision: 3, - updatedAt: Date(), - dialectVersion: 1 - ), - markdown: userVersion - ) - store.noteEditorRecoveryConflict = NoteEditorRecoveryConflict( - diskMarkdown: "磁盘版本", - checkpoint: checkpoint - ) - - try store.waitForCourseFileOperation { - await store.resolveNoteEditorRecoveryConflict(useDisk: true) - } - - let recovered = try backupContents(backupRoot, itemID: item.id) - XCTAssertTrue( - recovered.contains(userVersion), - "冲突选「使用磁盘版本」后用户版本应已存入备份环;实际备份内容:\(recovered)" - ) - } - - func testGoneItemGraysAndReclaims() throws { - let base = makeTempRoot("weibei-phase2-gray-reclaim") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "灰态课") - let source = base.appendingPathComponent("讲义.md") - try "讲义内容".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) - - try FileManager.default.removeItem(at: backingURL) - try reconcile(store) - - XCTAssertEqual(store.displaySubtitle(for: item), store.ui("文件不存在", "File missing")) - XCTAssertNotNil(store.importedItems.first { $0.id == item.id }, "灰态期间条目必须保留") - XCTAssertNotNil(store.fileMissingSinceByItemID[item.id]) - - try "讲义内容".write(to: backingURL, atomically: true, encoding: .utf8) - try reconcile(store) - - let reclaimed = try XCTUnwrap( - store.importedItems.first { $0.id == item.id }, - "文件重现后应认领回同一 itemID" - ) - XCTAssertTrue(reclaimed.urlPath?.hasSuffix("讲义.md") == true) - XCTAssertNil(store.fileMissingSinceByItemID[item.id]) - XCTAssertEqual(store.displaySubtitle(for: reclaimed), reclaimed.subtitle) - } - - func testGoneItemRemovalBacksUpDraft() throws { - let base = makeTempRoot("weibei-phase2-removal-backup") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "移除课") - let source = base.appendingPathComponent("草稿.md") - try "原稿".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) - - let draft = "未落盘草稿内容" - store.scheduleNotePersistence(draft, for: item) - - try FileManager.default.removeItem(at: backingURL) - try reconcile(store) - store.fileMissingSinceByItemID[item.id] = Date().addingTimeInterval(-7) - try reconcile(store) - - XCTAssertNil(store.importedItems.first { $0.id == item.id }, "两个周期仍缺席应移除条目") - let recovered = try backupContents(backupRoot, itemID: item.id) - XCTAssertTrue(recovered.contains(draft), "移除前草稿应入备份环;实际:\(recovered)") - } - - private static func digest(of text: String) -> String { - WorkspaceStore.noteContentDigest(Data(text.utf8)) - } -} diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index 8c00f377f..264a897c0 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -913,11 +913,6 @@ enum ImportedIdentitySelfCheck { ) try FileManager.default.removeItem(at: materialURL) reopened.presentCourseWorkspace(.hub, courseID: courseA.id) - // 灰态保护:模拟两个对账周期后再移除(计划 §5 阶段2)。 - if reopened.importedItems.contains(where: { $0.id == material.id }) { - reopened.fileMissingSinceByItemID[material.id] = Date().addingTimeInterval(-7) - try reopened.reconcileCourseFilesForSelfCheck(courseID: courseA.id) - } try check( !reopened.resumeCourseReading(courseA.id) && reopened.courseWorkspacePresented diff --git a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift b/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift deleted file mode 100644 index 78f701c11..000000000 --- a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift +++ /dev/null @@ -1,239 +0,0 @@ -import Foundation -@testable import WeiBei -import WeiBeiCore -import XCTest - -@MainActor -final class LibraryMigrationSafetyTests: XCTestCase { - override class func setUp() { - super.setUp() - setenv("WEIBEI_SAFETY_TEST_MODE", "1", 1) - } - - private func makeStore(workspace: URL, library: URL) throws -> WorkspaceStore { - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) - let store = WorkspaceStore( - workspaceDirectory: workspace, - courseRootBookmarkMaker: { Data($0.standardizedFileURL.path.utf8) }, - courseRootBookmarkResolver: { data in - guard let path = String(data: data, encoding: .utf8) else { return nil } - return CourseProjectResolvedBookmark( - url: URL(fileURLWithPath: path), - isStale: false - ) - }, - courseSecurityScopeStarter: { _ in true }, - courseSecurityScopeStopper: { _ in }, - startsAtBlankEntries: true, - startsCourseFileMaintenance: false - ) - try store.configureCourseLibrary(at: library) - return store - } - - private func makeTempRoot(_ name: String) -> URL { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("\(name)-\(UUID().uuidString)", isDirectory: true) - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - return root - } - - private func migrate(_ store: WorkspaceStore, to destination: URL) throws -> WorkspaceStore.LibraryMigrationResult { - try store.waitForCourseFileOperation { - try await store.migrateLibrary(to: destination) - } - } - - private func reconcile(_ store: WorkspaceStore) throws { - try store.waitForCourseFileOperation { - await store.reconcileCourseFilesNow() - } - } - - func testMigrateLibraryMovesTreeAndRebinds() throws { - let base = makeTempRoot("weibei-migration-move") - defer { try? FileManager.default.removeItem(at: base) } - let library = base.appendingPathComponent("旧资料库", isDirectory: true) - let destination = base.appendingPathComponent("新资料库", isDirectory: true) - let store = try makeStore( - workspace: base.appendingPathComponent("workspace", isDirectory: true), - library: library - ) - let courseID = try store.createCourseInLibrary(title: "迁移课") - let noteSource = base.appendingPathComponent("第一讲.md") - try "第一讲正文".write(to: noteSource, atomically: true, encoding: .utf8) - _ = try store.importFileIntoCourseForSelfCheck(noteSource, courseID: courseID, role: .material) - - let result = try migrate(store, to: destination) - - XCTAssertEqual(result.destination.standardizedFileURL, destination.standardizedFileURL) - let leftoverEntries = (try? FileManager.default.contentsOfDirectory(atPath: library.path)) ?? [] - XCTAssertTrue( - leftoverEntries.isEmpty, - "旧资料库目录残留:\(leftoverEntries),当前绑定=\(store.courseLibraryRootPath ?? "nil")" - ) - XCTAssertTrue(FileManager.default.fileExists( - atPath: destination.appendingPathComponent("迁移课/.weibei/course.json").path - )) - XCTAssertEqual(store.courseLibraryRootURL?.standardizedFileURL, destination.standardizedFileURL) - XCTAssertEqual(store.courseLibraryRootPath, destination.standardizedFileURL.path) - let movedCourseRoot = try XCTUnwrap(store.courseRootURL(for: courseID)) - XCTAssertTrue(movedCourseRoot.path.hasPrefix(destination.path)) - XCTAssertEqual(store.courseManifestCourseID(at: movedCourseRoot), courseID) - XCTAssertTrue(FileManager.default.fileExists(atPath: movedCourseRoot.appendingPathComponent(".weibei/course.json").path)) - let migratedItem = try XCTUnwrap(store.importedItems.first { item in - if case .courseOwned = item.storage { return true } - return false - }) - let itemURL = try XCTUnwrap(store.resolvedLibraryURL(for: migratedItem)) - XCTAssertTrue(itemURL.path.hasPrefix(destination.path)) - XCTAssertTrue(FileManager.default.fileExists(atPath: itemURL.path)) - XCTAssertEqual(try String(contentsOf: itemURL, encoding: .utf8), "第一讲正文") - } - - func testMigrateLibraryRejectsNestedAndNonEmpty() throws { - let base = makeTempRoot("weibei-migration-reject") - defer { try? FileManager.default.removeItem(at: base) } - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore( - workspace: base.appendingPathComponent("workspace", isDirectory: true), - library: library - ) - let courseID = try store.createCourseInLibrary(title: "课程甲") - - let nested = library.appendingPathComponent("嵌套目标", isDirectory: true) - do { - _ = try migrate(store, to: nested) - XCTFail("嵌套目标应被拒绝") - } catch let error as CourseProjectRootError { - guard case .destinationInsideLibrary = error else { - return XCTFail("期望 destinationInsideLibrary,实际 \(error)") - } - } - do { - _ = try migrate(store, to: library) - XCTFail("库自身应被拒绝") - } catch let error as CourseProjectRootError { - guard case .destinationIsLibrary = error else { - return XCTFail("期望 destinationIsLibrary,实际 \(error)") - } - } - - let nonEmpty = base.appendingPathComponent("非空目录", isDirectory: true) - try FileManager.default.createDirectory(at: nonEmpty, withIntermediateDirectories: true) - try "占位".write(to: nonEmpty.appendingPathComponent("其他文件.txt"), atomically: true, encoding: .utf8) - do { - _ = try migrate(store, to: nonEmpty) - XCTFail("非空目标应被拒绝") - } catch let error as CourseProjectRootError { - guard case .destinationNotEmpty = error else { - return XCTFail("期望 destinationNotEmpty,实际 \(error)") - } - } - - let courseRoot = try XCTUnwrap(store.courseRootURL(for: courseID)) - XCTAssertEqual(store.courseManifestCourseID(at: courseRoot), courseID) - XCTAssertEqual(store.courseLibraryRootURL?.standardizedFileURL, library.standardizedFileURL) - XCTAssertTrue(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent(".weibei/course.json").path)) - } - - func testMigrateLibraryAdoptsExistingLibrary() throws { - let base = makeTempRoot("weibei-migration-adopt") - defer { try? FileManager.default.removeItem(at: base) } - let library = base.appendingPathComponent("原资料库", isDirectory: true) - let store = try makeStore( - workspace: base.appendingPathComponent("workspace", isDirectory: true), - library: library - ) - let existingLibrary = base.appendingPathComponent("已有资料库", isDirectory: true) - try FileManager.default.createDirectory( - at: existingLibrary.appendingPathComponent(".weibei", isDirectory: true), - withIntermediateDirectories: true - ) - let manifest = CourseProjectManifest(courseID: UUID()) - let manifestData = try JSONEncoder().encode(manifest) - try manifestData.write(to: existingLibrary.appendingPathComponent(".weibei/course.json")) - - do { - _ = try migrate(store, to: existingLibrary) - XCTFail("合法库目标应改走认领而非迁移") - } catch let error as CourseProjectRootError { - guard case .destinationIsLibrary = error else { - return XCTFail("期望 destinationIsLibrary,实际 \(error)") - } - } - XCTAssertTrue(FileManager.default.fileExists(atPath: library.path)) - XCTAssertTrue(FileManager.default.fileExists( - atPath: existingLibrary.appendingPathComponent(".weibei/course.json").path - )) - try store.configureCourseLibrary(at: existingLibrary) - XCTAssertEqual(store.courseLibraryRootURL?.standardizedFileURL, existingLibrary.standardizedFileURL) - } - - func testMigrateLibraryFailureKeepsOriginal() throws { - let base = makeTempRoot("weibei-migration-failure") - defer { - try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: base.path) - try? FileManager.default.removeItem(at: base) - } - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore( - workspace: base.appendingPathComponent("workspace", isDirectory: true), - library: library - ) - let courseID = try store.createCourseInLibrary(title: "保留课") - let lockedParent = base.appendingPathComponent("只读父目录", isDirectory: true) - try FileManager.default.createDirectory(at: lockedParent, withIntermediateDirectories: true) - let destination = lockedParent.appendingPathComponent("目标", isDirectory: true) - try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) - try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: lockedParent.path) - - do { - _ = try migrate(store, to: destination) - XCTFail("只读目标应导致迁移失败") - } catch let error as CourseProjectRootError { - guard case .migrationFailed = error else { - return XCTFail("期望 migrationFailed,实际 \(error)") - } - } - XCTAssertFalse(store.libraryMigrationInFlight) - let courseRoot = try XCTUnwrap(store.courseRootURL(for: courseID)) - XCTAssertEqual(store.courseManifestCourseID(at: courseRoot), courseID) - XCTAssertEqual(store.courseLibraryRootURL?.standardizedFileURL, library.standardizedFileURL) - XCTAssertTrue(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent(".weibei/course.json").path)) - } - - func testMigrateLibrarySuspendsAndResumesServices() throws { - let base = makeTempRoot("weibei-migration-suspend") - defer { try? FileManager.default.removeItem(at: base) } - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore( - workspace: base.appendingPathComponent("workspace", isDirectory: true), - library: library - ) - let courseID = try store.createCourseInLibrary(title: "挂起课") - let source = base.appendingPathComponent("笔记.md") - try "原始内容".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) - - let commonNotes = library.appendingPathComponent("通用笔记", isDirectory: true) - XCTAssertTrue(FileManager.default.fileExists(atPath: commonNotes.path)) - - store.libraryMigrationInFlight = true - store.scheduleNotePersistence("迁移期间的新内容", for: item) - store.flushPendingNotePersistence(for: item.id) - XCTAssertEqual(try String(contentsOf: backingURL, encoding: .utf8), "原始内容") - try? FileManager.default.removeItem(at: commonNotes) - try reconcile(store) - XCTAssertFalse(FileManager.default.fileExists(atPath: commonNotes.path)) - - store.libraryMigrationInFlight = false - store.flushPendingNotePersistence(for: item.id) - XCTAssertEqual(try String(contentsOf: backingURL, encoding: .utf8), "迁移期间的新内容") - try reconcile(store) - XCTAssertTrue(FileManager.default.fileExists(atPath: commonNotes.path)) - } -} diff --git a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift index fc9671065..a817a7430 100644 --- a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift +++ b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift @@ -116,13 +116,6 @@ enum LibraryRelativeOnlyCheck { if let index = store.importedItems.firstIndex(where: { $0.id == itemID }) { _ = store.forgetGoneImportedItem(at: index) } - // 灰态保护:模拟两个对账周期后再判移除(计划 §5 阶段2)。 - if let index = store.importedItems.firstIndex(where: { $0.id == itemID }) { - if let missingSince = store.fileMissingSinceByItemID[itemID] { - store.fileMissingSinceByItemID[itemID] = missingSince.addingTimeInterval(-7) - } - _ = store.forgetGoneImportedItem(at: index) - } XCTAssertNil(store.importedItems.first(where: { $0.id == itemID })) XCTAssertTrue(store.studySessions.contains(where: { $0.id == chat.id && !$0.messages.isEmpty })) diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift deleted file mode 100644 index 426121543..000000000 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ /dev/null @@ -1,233 +0,0 @@ -import Foundation -@testable import WeiBei -import WeiBeiCore -import XCTest - -/// 阶段1 写闸门专项验证(计划 §5 阶段1 第4步)。 -@MainActor -final class WriteGateSafetyTests: XCTestCase { - override class func setUp() { - super.setUp() - setenv("WEIBEI_SAFETY_TEST_MODE", "1", 1) - } - - private func makeTempRoot(_ name: String) -> URL { - let root = FileManager.default.temporaryDirectory - .appendingPathComponent("\(name)-\(UUID().uuidString)", isDirectory: true) - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - return root - } - - private func makeStore( - base: URL, - library: URL, - backupRoot: URL - ) throws -> WorkspaceStore { - try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) - let store = WorkspaceStore( - workspaceDirectory: base.appendingPathComponent("workspace", isDirectory: true), - noteBackupRootURL: backupRoot, - startsAtBlankEntries: true, - startsCourseFileMaintenance: false - ) - try store.configureCourseLibrary(at: library) - return store - } - - private func importNote( - _ store: WorkspaceStore, - base: URL, - courseID: UUID, - content: String, - fileName: String? = nil - ) throws -> (item: StudyItem, url: URL) { - let source = base.appendingPathComponent("\(fileName ?? "笔记-\(UUID().uuidString)").md") - try content.write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck( - source, courseID: courseID, role: .material - ) - let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) - return (imported.item, url) - } - - private static func digest(of text: String) -> String { - WorkspaceStore.noteContentDigest(Data(text.utf8)) - } - - func testGateRefusesWriteWithoutBaseline() throws { - let base = makeTempRoot("weibei-gate-no-baseline") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "原始内容") - - XCTAssertThrowsError( - try store.writeNotebookMarkdownThroughGate( - "新内容", itemID: item.id, url: url, expectedBaseline: nil - ) - ) { error in - guard case NoteWriteGateError.writeRefusedKeepContent = error else { - return XCTFail("期望 writeRefusedKeepContent,实际 \(error)") - } - } - XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "原始内容") - } - - func testGateRefusesWhenRereadFails() throws { - let base = makeTempRoot("weibei-gate-unreadable") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "原始内容") - - try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: url.path) - defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path) } - XCTAssertThrowsError( - try store.writeNotebookMarkdownThroughGate( - "新内容", itemID: item.id, url: url, expectedBaseline: Self.digest(of: "任意") - ) - ) { error in - guard case NoteWriteGateError.writeRefusedKeepContent = error else { - return XCTFail("期望 writeRefusedKeepContent,实际 \(error)") - } - } - XCTAssertEqual(store.noteBackingContentDigestsByItemID[item.id] ?? "", "") - } - - func testGateBacksUpPendingContentAndAdoptsDiskOnMismatch() throws { - let base = makeTempRoot("weibei-gate-mismatch") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "基线内容") - store.noteBackingContentDigestsByItemID[item.id] = Self.digest(of: "基线内容") - - try "外部修改".write(to: url, atomically: true, encoding: .utf8) - - let pendingInput = "用户未落盘的编辑" - store.scheduleNotePersistence(pendingInput, for: item) - store.flushPendingNotePersistence(for: item.id) - - XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "外部修改") - XCTAssertEqual(store.loadedCourseNoteTextByItemID[item.id], "外部修改") - let backups = try NoteBackupRing.list(itemID: item.id, rootURL: backupRoot) - let recovered = backups.compactMap { entry in - try? String(contentsOf: entry.url, encoding: .utf8) - } - XCTAssertTrue(recovered.contains(pendingInput), "待写内容应先入备份环;实际:\(recovered)") - } - - func testPersistNoteWritesWhenBaselineMatches() throws { - let base = makeTempRoot("weibei-gate-normal-write") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "第一版") - - store.scheduleNotePersistence("第二版", for: item) - store.flushPendingNotePersistence(for: item.id) - - XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "第二版") - XCTAssertEqual(store.noteBackingContentDigestsByItemID[item.id], Self.digest(of: "第二版")) - XCTAssertEqual(store.lastSelfWrittenNoteDigestsByItemID[item.id], Self.digest(of: "第二版")) - } - - func testRenameRewriteRoutesThroughGate() throws { - let base = makeTempRoot("weibei-gate-rename") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote( - store, - base: base, - courseID: courseID, - content: "# 旧标题\n正文", - fileName: "旧标题" - ) - - try store.waitForCourseFileOperation { - await store.renameNotebookNoteInTransaction(itemID: item.id, to: "新标题") - } - let documentsDir = url.deletingLastPathComponent() - let renamedURL = documentsDir.appendingPathComponent("新标题.md") - XCTAssertTrue(FileManager.default.fileExists(atPath: renamedURL.path)) - XCTAssertFalse(FileManager.default.fileExists(atPath: url.path)) - let content = try String(contentsOf: renamedURL, encoding: .utf8) - XCTAssertTrue(content.contains("# 新标题"), "改名后正文抬头应更新:\(content)") - XCTAssertTrue(content.contains("正文")) - } - - func testRepairRestoreDraftRoutesThroughGate() throws { - let base = makeTempRoot("weibei-gate-repair") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "# 标题\n真实草稿") - - store.notesByItemID[item.id] = "磁盘上没有的草稿内容" - - store.repairDivergedNotebookNotesIfNeeded() - - XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "磁盘上没有的草稿内容") - XCTAssertEqual(store.notesByItemID[item.id], nil) - } - - func testRetryRestoredPendingWritesRoutesThroughGate() throws { - let base = makeTempRoot("weibei-gate-retry") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - let store = try makeStore(base: base, library: library, backupRoot: backupRoot) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let (item, url) = try importNote(store, base: base, courseID: courseID, content: "磁盘现况") - - store.notesByItemID[item.id] = "重启前未写完的草稿" - store.pendingNoteWritesByItemID[item.id] = PendingNoteWriteState(baselineContentDigest: nil) - store.retryRestoredPendingNoteWrites() - - XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "重启前未写完的草稿") - } - - func testWriterFailureKeepsDraftAndSkipsDigestRefresh() throws { - let base = makeTempRoot("weibei-gate-writer-failure") - defer { try? FileManager.default.removeItem(at: base) } - let backupRoot = base.appendingPathComponent("backups", isDirectory: true) - let library = base.appendingPathComponent("资料库", isDirectory: true) - try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) - struct ExplodingWriterError: Error {} - let store = WorkspaceStore( - workspaceDirectory: base.appendingPathComponent("workspace", isDirectory: true), - notebookMarkdownWriter: { markdown, url in - try "半截".write(to: url, atomically: true, encoding: .utf8) - throw ExplodingWriterError() - }, - noteBackupRootURL: backupRoot, - startsAtBlankEntries: true, - startsCourseFileMaintenance: false - ) - try store.configureCourseLibrary(at: library) - let courseID = try store.createCourseInLibrary(title: "闸门课") - let source = base.appendingPathComponent("笔记.md") - try "第一版".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) - let item = imported.item - - store.scheduleNotePersistence("第二版", for: item) - store.flushPendingNotePersistence(for: item.id) - - XCTAssertEqual(store.notesByItemID[item.id], "第二版") - XCTAssertNil(store.lastSelfWrittenNoteDigestsByItemID[item.id]) - } -}