1+ import CryptoKit
12import Foundation
23import OSLog
34
45enum FileStorage {
6+ private struct NoteFileCandidate {
7+ let url : URL
8+ let folder : String
9+ let relativePath : String
10+ let data : Data
11+ let contentHash : String
12+
13+ var contentByteCount : Int {
14+ data . count
15+ }
16+ }
17+
18+ private struct FingerprintKey : Hashable {
19+ let contentHash : String
20+ let contentByteCount : Int
21+ }
22+
523 /// Storage root — reads from ShortcutSettings so the user can configure a custom directory.
624 static var rootURL : URL {
725 StorageSettings . shared . resolvedStorageDirectory
@@ -104,17 +122,23 @@ enum FileStorage {
104122 /// Reloads a note's content + tags from disk after an external change is detected.
105123 static func reloadContent ( for note : Note ) -> ( content : String , modifiedAt : Date , savedAt : Date , tags : [ TagColor ] ) ? {
106124 let url = rootURL . appendingPathComponent ( diskRelativePath ( for : note ) )
107- guard let text = try? String ( contentsOf : url , encoding : . utf8 ) else { return nil }
125+ guard let data = try? Data ( contentsOf : url ) ,
126+ let text = String ( data : data , encoding : . utf8 )
127+ else { return nil }
108128 let diskDate = ( ( try? FileManager . default . attributesOfItem ( atPath : url . path ) ) ? [ . modificationDate ] as? Date ) ?? Date ( )
109129
110130 // Body may still have YAML if this note wasn't migrated yet — strip it.
111131 let ( metadata , body ) = parseFrontMatter ( text )
112132 let content = metadata . isEmpty ? text : body
113133
114- let tags : [ TagColor ] = if let entry = SidecarStore . shared . noteEntry ( for : note . id ) {
115- entry . tags . compactMap { TagColor ( rawValue : $0 ) }
134+ let tags : [ TagColor ]
135+ if var entry = SidecarStore . shared . noteEntry ( for : note . id ) {
136+ entry . contentHash = contentHash ( for : data )
137+ entry . contentByteCount = data . count
138+ SidecarStore . shared . upsertNote ( entry , for : note . id )
139+ tags = entry . tags . compactMap { TagColor ( rawValue : $0 ) }
116140 } else {
117- parseTagList ( metadata [ " tags " ] ?? " " )
141+ tags = parseTagList ( metadata [ " tags " ] ?? " " )
118142 }
119143 // After an external edit, savedAt should advance to the new disk date so the
120144 // watcher doesn't fire again for the same change.
@@ -354,11 +378,26 @@ enum FileStorage {
354378
355379 static func loadAllNotes ( ) throws -> [ Note ] {
356380 try ensureRootExists ( )
357- var notes = try loadNotes ( in : rootURL , folder : " " )
358- for folderName in try discoverFolders ( ) {
359- let folderURL = rootURL . appendingPathComponent ( folderName , isDirectory : true )
360- notes += try loadNotes ( in : folderURL , folder : folderName )
381+ let candidates = try loadActiveNoteCandidates ( )
382+ var entriesByPath = SidecarStore . shared . noteEntriesByPath ( )
383+ reconcileExternalRenames ( candidates : candidates , entriesByPath : & entriesByPath )
384+
385+ let notes = candidates . compactMap { candidate in
386+ readNote (
387+ at : candidate . url ,
388+ folder : candidate . folder ,
389+ preloadedData : candidate . data ,
390+ activeEntriesByPath : entriesByPath ,
391+ saveSidecarImmediately : false ,
392+ )
361393 }
394+
395+ do {
396+ try SidecarStore . shared . save ( )
397+ } catch {
398+ Log . storage . error ( " [NoteMetadata] reconcile failure source=load reason=sidecar " )
399+ }
400+
362401 let migrated = notes . map { note in
363402 do {
364403 return try migrateReservedRootAssetsIfNeeded ( for : note )
@@ -373,6 +412,76 @@ enum FileStorage {
373412 return migrated
374413 }
375414
415+ private static func loadActiveNoteCandidates ( ) throws -> [ NoteFileCandidate ] {
416+ var locations : [ ( url : URL , folder : String ) ] = [ ( rootURL , " " ) ]
417+ locations += try discoverFolders ( ) . map { folder in
418+ ( rootURL . appendingPathComponent ( folder , isDirectory : true ) , folder )
419+ }
420+
421+ var candidates : [ NoteFileCandidate ] = [ ]
422+ for location in locations {
423+ let contents = try FileManager . default . contentsOfDirectory (
424+ at : location . url ,
425+ includingPropertiesForKeys : nil ,
426+ options : [ . skipsHiddenFiles ] ,
427+ )
428+ for url in contents where url . pathExtension . lowercased ( ) == " md " && ! url . hasDirectoryPath {
429+ guard let data = try? Data ( contentsOf : url ) , String ( data : data , encoding : . utf8 ) != nil else {
430+ continue
431+ }
432+ let filename = url . lastPathComponent
433+ let relativePath = location . folder . isEmpty ? filename : " \( location . folder ) / \( filename ) "
434+ candidates . append ( NoteFileCandidate (
435+ url : url ,
436+ folder : location . folder ,
437+ relativePath : relativePath ,
438+ data : data ,
439+ contentHash : contentHash ( for : data ) ,
440+ ) )
441+ }
442+ }
443+ return candidates
444+ }
445+
446+ private static func reconcileExternalRenames (
447+ candidates : [ NoteFileCandidate ] ,
448+ entriesByPath : inout [ String : ( id : UUID , entry : SidecarStore . NoteEntry ) ] ,
449+ ) {
450+ let diskPaths = Set ( candidates . map ( \. relativePath ) )
451+ let missingEntries = entriesByPath . filter { ! diskPaths . contains ( $0 . key ) }
452+ let unmatchedFiles = candidates . filter { entriesByPath [ $0 . relativePath ] == nil }
453+
454+ let missingByFingerprint = Dictionary ( grouping : missingEntries . compactMap { path , indexed -> ( FingerprintKey , String , UUID , SidecarStore . NoteEntry ) ? in
455+ guard let hash = indexed . entry . contentHash ,
456+ let byteCount = indexed . entry . contentByteCount
457+ else { return nil }
458+ return ( FingerprintKey ( contentHash : hash , contentByteCount : byteCount ) , path , indexed . id , indexed . entry )
459+ } , by : \. 0 )
460+
461+ let filesByFingerprint = Dictionary ( grouping : unmatchedFiles , by : {
462+ FingerprintKey ( contentHash : $0 . contentHash , contentByteCount : $0 . contentByteCount )
463+ } )
464+
465+ for ( fingerprint , missing ) in missingByFingerprint where missing . count == 1 {
466+ guard let discovered = filesByFingerprint [ fingerprint ] , discovered . count == 1 ,
467+ let old = missing . first , let candidate = discovered . first
468+ else { continue }
469+
470+ var entry = old . 3
471+ entry . path = candidate . relativePath
472+ entry . contentHash = candidate . contentHash
473+ entry . contentByteCount = candidate . contentByteCount
474+ SidecarStore . shared . upsertNote ( entry , for : old . 2 )
475+ entriesByPath . removeValue ( forKey : old . 1 )
476+ entriesByPath [ candidate . relativePath ] = ( old . 2 , entry )
477+ Log . storage . info ( " [NoteMetadata] reconcile success source=fingerprint noteID= \( old . 2 . uuidString , privacy : . public ) " )
478+ }
479+ }
480+
481+ private static func contentHash ( for data : Data ) -> String {
482+ SHA256 . hash ( data : data ) . map { String ( format : " %02x " , $0 ) } . joined ( )
483+ }
484+
376485 /// Writes the note to disk. If the title changed since last save, renames the old file
377486 /// to preserve macOS file metadata (creation date, Finder tags, extended attributes).
378487 /// Also renames the co-located asset directory and rewrites image paths in the body.
@@ -466,6 +575,7 @@ enum FileStorage {
466575 /// Update (or insert) the sidecar entry for a note after writing its file.
467576 private static func upsertSidecarEntry ( for note : Note , filename : String ) -> Bool {
468577 let relativePath = note . folder . isEmpty ? filename : " \( note . folder ) / \( filename ) "
578+ let persistedData = Data ( note . content . utf8 )
469579 let savedAt = ( try? FileManager . default . attributesOfItem (
470580 atPath : rootURL . appendingPathComponent ( relativePath ) . path ,
471581 ) ) ? [ . modificationDate ] as? Date ?? Date ( )
@@ -477,6 +587,8 @@ enum FileStorage {
477587 modifiedAt : note . modifiedAt ,
478588 savedAt : savedAt ,
479589 tags : note . tags . map ( \. rawValue ) ,
590+ contentHash : contentHash ( for : persistedData ) ,
591+ contentByteCount : persistedData . count ,
480592 ) ,
481593 for : note . id ,
482594 )
@@ -600,9 +712,10 @@ enum FileStorage {
600712 try ensureTrashExists ( )
601713 let trashFilename = " \( note . id . uuidString ) _ \( sanitizeForFilename ( note . title ) ) .md "
602714 let destURL = trashURL . appendingPathComponent ( trashFilename )
715+ let persistedData = Data ( note . content . utf8 )
603716
604717 // Write body only to .trash/
605- try Data ( note . content . utf8 ) . write ( to : destURL , options : . atomic )
718+ try persistedData . write ( to : destURL , options : . atomic )
606719
607720 // Remove original file
608721 let actualFilename = note . savedFilename ?? note . filename
@@ -620,6 +733,8 @@ enum FileStorage {
620733 createdAt : note . createdAt ,
621734 modifiedAt : note . modifiedAt ,
622735 tags : note . tags . map ( \. rawValue ) ,
736+ contentHash : contentHash ( for : persistedData ) ,
737+ contentByteCount : persistedData . count ,
623738 ) ,
624739 for : note . id ,
625740 )
@@ -702,13 +817,16 @@ enum FileStorage {
702817 // Move sidecar entry from trash → notes
703818 SidecarStore . shared . removeTrash ( id : note . id )
704819 let savedAt = ( try? FileManager . default . attributesOfItem ( atPath : destURL . path ) ) ? [ . modificationDate ] as? Date ?? Date ( )
820+ let persistedData = Data ( restored . content . utf8 )
705821 SidecarStore . shared . upsertNote (
706822 SidecarStore . NoteEntry (
707823 path : destRelative ,
708824 createdAt : note . createdAt ,
709825 modifiedAt : note . modifiedAt ,
710826 savedAt : savedAt ,
711827 tags : note . tags . map ( \. rawValue ) ,
828+ contentHash : contentHash ( for : persistedData ) ,
829+ contentByteCount : persistedData . count ,
712830 ) ,
713831 for : note . id ,
714832 )
@@ -795,6 +913,8 @@ enum FileStorage {
795913 createdAt : entry . createdAt ,
796914 modifiedAt : entry . modifiedAt ,
797915 tags : entry . tags ,
916+ contentHash : entry . contentHash ,
917+ contentByteCount : entry . contentByteCount ,
798918 ) , for : noteID )
799919 }
800920 }
@@ -851,6 +971,8 @@ enum FileStorage {
851971 modifiedAt : entry . modifiedAt ,
852972 savedAt : actualMtime ,
853973 tags : entry . tags ,
974+ contentHash : entry . contentHash ,
975+ contentByteCount : entry . contentByteCount ,
854976 ) , for : noteID )
855977 }
856978 }
@@ -973,9 +1095,19 @@ enum FileStorage {
9731095 }
9741096 }
9751097
976- private static func readNote ( at url : URL , folder : String ) -> Note ? {
977- guard let text = try? String ( contentsOf : url , encoding : . utf8 ) else { return nil }
1098+ private static func readNote (
1099+ at url : URL ,
1100+ folder : String ,
1101+ preloadedData : Data ? = nil ,
1102+ activeEntriesByPath : [ String : ( id : UUID , entry : SidecarStore . NoteEntry ) ] ? = nil ,
1103+ saveSidecarImmediately : Bool = true ,
1104+ ) -> Note ? {
1105+ guard let data = preloadedData ?? ( try? Data ( contentsOf : url ) ) ,
1106+ let text = String ( data : data , encoding : . utf8 )
1107+ else { return nil }
9781108 let filename = url . lastPathComponent
1109+ let hash = contentHash ( for : data )
1110+ let byteCount = data . count
9791111
9801112 // Determine relative path for sidecar lookup.
9811113 // Trash files live under trashURL, active notes under rootURL.
@@ -998,7 +1130,14 @@ enum FileStorage {
9981130
9991131 // --- Sidecar path (preferred) ---
10001132 if isTrash {
1001- if let ( id , entry ) = SidecarStore . shared . trashEntry ( forFilename : relativePath ) {
1133+ if let ( id , storedEntry ) = SidecarStore . shared . trashEntry ( forFilename : relativePath ) {
1134+ var entry = storedEntry
1135+ entry . contentHash = hash
1136+ entry . contentByteCount = byteCount
1137+ SidecarStore . shared . upsertTrash ( entry , for : id )
1138+ if saveSidecarImmediately {
1139+ try? SidecarStore . shared . save ( )
1140+ }
10021141 let ( _, body ) = parseFrontMatter ( text ) // strip any residual YAML
10031142 let content = text . hasPrefix ( " --- " ) ? body : text
10041143 let tags = entry . tags . compactMap { TagColor ( rawValue : $0 ) }
@@ -1018,7 +1157,19 @@ enum FileStorage {
10181157 )
10191158 }
10201159 } else {
1021- if let ( id , entry ) = SidecarStore . shared . noteEntry ( forPath : relativePath ) {
1160+ let indexedEntry = if let activeEntriesByPath {
1161+ activeEntriesByPath [ relativePath ]
1162+ } else {
1163+ SidecarStore . shared . noteEntry ( forPath : relativePath )
1164+ }
1165+ if let ( id , storedEntry ) = indexedEntry {
1166+ var entry = storedEntry
1167+ entry . contentHash = hash
1168+ entry . contentByteCount = byteCount
1169+ SidecarStore . shared . upsertNote ( entry , for : id )
1170+ if saveSidecarImmediately {
1171+ try? SidecarStore . shared . save ( )
1172+ }
10221173 let ( _, body ) = parseFrontMatter ( text )
10231174 let content = text . hasPrefix ( " --- " ) ? body : text
10241175 let tags = entry . tags . compactMap { TagColor ( rawValue : $0 ) }
@@ -1057,6 +1208,8 @@ enum FileStorage {
10571208 createdAt : created ,
10581209 modifiedAt : modified ,
10591210 tags : tags . map ( \. rawValue ) ,
1211+ contentHash : hash ,
1212+ contentByteCount : byteCount ,
10601213 ) , for : id )
10611214 } else {
10621215 SidecarStore . shared . upsertNote ( SidecarStore . NoteEntry (
@@ -1065,13 +1218,17 @@ enum FileStorage {
10651218 modifiedAt : modified ,
10661219 savedAt : modified ,
10671220 tags : tags . map ( \. rawValue ) ,
1221+ contentHash : hash ,
1222+ contentByteCount : byteCount ,
10681223 ) , for : id )
10691224 }
1070- do {
1071- try SidecarStore . shared . save ( )
1072- Log . storage . info ( " [NoteMetadata] reconcile success source=yaml noteID= \( id . uuidString , privacy : . public ) " )
1073- } catch {
1074- Log . storage . error ( " [NoteMetadata] reconcile failure source=yaml noteID= \( id . uuidString , privacy : . public ) reason=sidecar " )
1225+ if saveSidecarImmediately {
1226+ do {
1227+ try SidecarStore . shared . save ( )
1228+ Log . storage . info ( " [NoteMetadata] reconcile success source=yaml noteID= \( id . uuidString , privacy : . public ) " )
1229+ } catch {
1230+ Log . storage . error ( " [NoteMetadata] reconcile failure source=yaml noteID= \( id . uuidString , privacy : . public ) reason=sidecar " )
1231+ }
10751232 }
10761233
10771234 return Note (
@@ -1102,6 +1259,8 @@ enum FileStorage {
11021259 createdAt : created ,
11031260 modifiedAt : modified ,
11041261 tags : [ ] ,
1262+ contentHash : hash ,
1263+ contentByteCount : byteCount ,
11051264 ) , for : id )
11061265 } else {
11071266 SidecarStore . shared . upsertNote ( SidecarStore . NoteEntry (
@@ -1110,13 +1269,17 @@ enum FileStorage {
11101269 modifiedAt : modified ,
11111270 savedAt : modified ,
11121271 tags : [ ] ,
1272+ contentHash : hash ,
1273+ contentByteCount : byteCount ,
11131274 ) , for : id )
11141275 }
1115- do {
1116- try SidecarStore . shared . save ( )
1117- Log . storage . info ( " [NoteMetadata] reconcile success source=external noteID= \( id . uuidString , privacy : . public ) " )
1118- } catch {
1119- Log . storage . error ( " [NoteMetadata] reconcile failure source=external noteID= \( id . uuidString , privacy : . public ) reason=sidecar " )
1276+ if saveSidecarImmediately {
1277+ do {
1278+ try SidecarStore . shared . save ( )
1279+ Log . storage . info ( " [NoteMetadata] reconcile success source=external noteID= \( id . uuidString , privacy : . public ) " )
1280+ } catch {
1281+ Log . storage . error ( " [NoteMetadata] reconcile failure source=external noteID= \( id . uuidString , privacy : . public ) reason=sidecar " )
1282+ }
11201283 }
11211284
11221285 return Note (
0 commit comments