Skip to content
Merged
125 changes: 106 additions & 19 deletions Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ 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 {
Expand Down Expand Up @@ -92,7 +106,7 @@ extension WorkspaceStore {
}
}

private func renameNotebookNoteInTransaction(
func renameNotebookNoteInTransaction(
itemID: String,
to rawTitle: String
) async {
Expand Down Expand Up @@ -214,7 +228,17 @@ extension WorkspaceStore {
Data(retitledMarkdown.utf8)
)
if willRewriteMarkdown {
try notebookMarkdownWriter(retitledMarkdown, newURL)
// 写闸门:以移动后磁盘现况为基线;不符即中止并走统一回滚。
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
let writtenDigest = Self.noteContentDigest(at: newURL)
guard writtenDigest == expectedOutputDigest else {
throw NSError(
Expand Down Expand Up @@ -581,10 +605,13 @@ extension WorkspaceStore {
continue
}
do {
try notebookMarkdownWriter(draft, plan.url)
let writtenDigest = Self.noteContentDigest(Data(draft.utf8))
noteBackingContentDigestsByItemID[itemID] = writtenDigest
lastSelfWrittenNoteDigestsByItemID[itemID] = writtenDigest
// 写闸门:以刚备份的磁盘现况为基线;不符则拒绝写回(草稿保留)。
try writeNotebookMarkdownThroughGate(
draft,
itemID: itemID,
url: plan.url,
expectedBaseline: Self.noteContentDigest(at: plan.url)
)
setNoteDraft(nil, for: itemID)
setNoteFileError(nil, for: itemID)
if let refreshed = refreshImportedFileTracking(
Expand Down Expand Up @@ -691,10 +718,9 @@ extension WorkspaceStore {
pendingNotePersistenceTasks[itemID] = nil
}

/// S2 三件套:备份(外部改动)→ 原子写 → 失败留草稿。
/// 全仓唯一底层笔记写盘函数;阶段1 写闸门在此内置比对(计划 §5 阶段1),
/// 所有写路径必须经此函数,禁止绕过。
/// 返回是否成功写回磁盘。永不因 digest 冲突拒绝写回。
/// S2 三件套:备份(外部改动)→ 闸门比对 → 原子写 → 失败留草稿。
/// 阶段1 写闸门:比对下沉到唯一底层入口,模板守卫此阶段并存(计划 §5 阶段1)。
/// 返回是否成功写回磁盘。
@discardableResult
func writeNoteMarkdownTriple(
_ markdown: String,
Expand Down Expand Up @@ -739,16 +765,23 @@ extension WorkspaceStore {
rootURL: noteBackupRootURL
)
}
if noteBackingContentDigestsByItemID[itemID] == nil,
let digest = importedItems.first(where: { $0.id == itemID })?.contentDigest {
noteBackingContentDigestsByItemID[itemID] = digest
}
do {
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
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
} catch {
setNoteDraft(markdown, for: itemID)
pendingNoteWritesByItemID.removeValue(forKey: itemID)
Expand All @@ -760,6 +793,60 @@ 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
}

/// 文件不可达时静默保留草稿(无冲突横幅)。
Expand Down
2 changes: 1 addition & 1 deletion Sources/WeiBei/Stores/WorkspaceStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ final class WorkspaceStore: ObservableObject {
/// 只有基线==当前文件名时才跟随抬头改名;对不上说明文件名被外部动过,
/// 先登记、不动文件。内存态即可:重启丢基线只少一次自动改名,方向安全。
var headingSyncedNoteStemByItemID: [String: String] = [:]
private var loadedCourseNoteTextByItemID: [String: String] = [:]
var loadedCourseNoteTextByItemID: [String: String] = [:]
var courseNoteLoadTasksByItemID: [String: Task<Void, Never>] = [:]
private var courseNoteLoadGenerationByItemID: [String: UInt64] = [:]
private var courseNoteWritesInFlight = Set<String>()
Expand Down
21 changes: 21 additions & 0 deletions Sources/WeiBeiSelfCheck/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2280,6 +2280,27 @@ 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.
Expand Down
Loading