-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsupertag-migration.el
More file actions
3123 lines (2940 loc) · 145 KB
/
Copy pathsupertag-migration.el
File metadata and controls
3123 lines (2940 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; supertag-migration.el --- Standalone data migration script -*- lexical-binding: t; -*-
;;; Commentary:
;; This file contains a self-contained function to migrate data from the
;; old `org-supertag-db.el` format to the new data-centric architecture.
;; It is broken into smaller helper functions to ensure correctness and readability.
;;; Code:
(require 'ht)
(require 'cl-lib)
(require 'org-id) ; For org-id-new
(require 'sha1) ; For secure-hash
(require 'org)
(require 'org-element)
(require 'subr-x)
(require 'supertag-core-store)
(require 'supertag-core-schema)
(require 'supertag-core-persistence)
(require 'supertag-ops-node)
(require 'supertag-ops-relation)
(require 'supertag-ops-schema)
(require 'supertag-ops-tag)
(require 'supertag-view-helper)
(require 'supertag-services-sync)
(require 'org-id)
(require 'org)
(require 'org-element)
(defvar supertag-query-saved nil)
(defvar supertag--view-configs (make-hash-table :test 'eq))
(declare-function supertag-tag-merge--plist-p
"supertag-ops-tag-merge" (value))
(declare-function supertag-tag-merge--string-mentions-source-p
"supertag-ops-tag-merge" (string source-ids))
(declare-function supertag-tag-path-rename--rewrite-structured
"supertag-ops-tag-merge" (form mapping))
(declare-function supertag-tag-path-rename--rewrite-values
"supertag-ops-tag-merge" (value mapping))
(declare-function supertag-tag-merge--snapshot-files
"supertag-ops-tag-merge" (files))
(declare-function supertag-tag-merge--restore-files
"supertag-ops-tag-merge" (snapshot))
(declare-function supertag-tag-merge--delete-snapshot
"supertag-ops-tag-merge" (snapshot))
;;; --- Helper Functions ---
(defun supertag-migrate--sanitize-tag-name (name)
"Sanitize a string into a valid tag name.
Removes leading/trailing whitespace, a leading '#', and converts
internal whitespace to single underscores."
(if (or (null name) (string-empty-p name))
(error "Tag name cannot be empty")
(let* ((clean-name (substring-no-properties name))
(trimmed (string-trim clean-name))
(no-hash (if (string-prefix-p "#" trimmed)
(substring trimmed 1)
trimmed))
(sanitized (replace-regexp-in-string "\\s-+" "_" no-hash)))
(if (string-empty-p sanitized)
(error "Invalid tag name: %s" name)
sanitized))))
(defun supertag-migrate--generate-relation-id (from-id to-id type)
"Generate a deterministic relation ID using SHA1.
Uses the same format as the current system."
(format "rel-%s" (secure-hash 'sha1 (format "%s|%s|%s" from-id to-id type))))
(defun supertag-migrate--unescape-string (str)
"Convert escaped octal sequences back to UTF-8 characters.
Input like '\\346\\265\\201\\351\\207\\217' becomes '流量'."
(when (stringp str)
(with-temp-buffer
(insert str)
(goto-char (point-min))
;; Replace octal escape sequences
(while (re-search-forward "\\\\\\([0-7]\\{3\\}\\)" nil t)
(let* ((octal-str (match-string 1))
(char-code (string-to-number octal-str 8))
(char (if (and (>= char-code 32) (<= char-code 126))
;; ASCII range
(char-to-string char-code)
;; For non-ASCII, we need to handle as bytes and decode
(char-to-string char-code))))
(replace-match char)))
;; Try to decode the result as UTF-8 if it contains high bytes
(let ((result (buffer-string)))
(condition-case nil
(decode-coding-string result 'utf-8)
(error result))))))
(defun supertag-migrate--clean-plist-strings (plist)
"Recursively clean escaped strings in a plist."
(when plist
(let ((result '()))
(while plist
(let ((key (car plist))
(value (cadr plist)))
(push key result)
(push (cond
((stringp value)
(supertag-migrate--unescape-string value))
((listp value)
(mapcar (lambda (item)
(if (stringp item)
(supertag-migrate--unescape-string item)
item))
value))
(t value))
result)
(setq plist (cddr plist))))
(nreverse result))))
(defun supertag-migrate--ensure-node-location-data (node-props)
"Ensure node has necessary location data for jumping.
Migrates old field names (:file-path -> :file, :pos -> :position) and
returns updated node properties with required location fields."
(let ((file (plist-get node-props :file))
(position (plist-get node-props :position))
(raw-value (plist-get node-props :raw-value))
(file-path (plist-get node-props :file-path))
(pos (plist-get node-props :pos)))
;; Migrate old field names to new ones
(when (and file-path (not file))
(setq node-props (plist-put node-props :file file-path))
(setq file file-path))
(when (and pos (not position))
(setq node-props (plist-put node-props :position pos))
(setq position pos))
;; If we don't have :raw-value but have :title, copy it
(unless raw-value
(let ((title (plist-get node-props :title)))
(when title
(setq node-props (plist-put node-props :raw-value title)))))
;; Warn only if we still don't have location data after migration attempt
(unless file
(message "Warning: Node missing :file attribute, navigation may not work"))
(unless position
(message "Warning: Node missing :position attribute, navigation may not work"))
node-props))
(defun supertag-migrate--safely-load-data (file)
"Read FILE and extract `org-supertag-db--object` and `org-supertag-db--link`.
This function works by evaluating the entire file in a lexical context
where the hash-table variables are pre-defined."
(let ((org-supertag-db--object (ht-create))
(org-supertag-db--link (ht-create))
(org-supertag-db--embeds (ht-create)))
(with-temp-buffer
;; Force UTF-8 encoding for reading
(let ((coding-system-for-read 'utf-8-unix)
(buffer-file-coding-system 'utf-8-unix))
(insert-file-contents file))
(set-buffer-file-coding-system 'utf-8-unix)
(goto-char (point-min))
(let ((eof (cons 'eof nil)))
(while (not (eobp))
(let ((form (condition-case nil
(read (current-buffer))
(end-of-file eof))))
(unless (eq form eof)
;; Eval each form. This will populate the lexically bound hash tables.
(eval form t))))))
(list org-supertag-db--object org-supertag-db--link org-supertag-db--embeds)))
(defun ht-deep-copy-table (table)
"Create a deep copy of hash TABLE.
This function recursively copies nested hash tables."
(let ((copy (ht-create)))
(maphash
(lambda (key value)
(puthash key
(if (hash-table-p value)
(ht-deep-copy-table value)
value)
copy))
table)
copy))
(defun supertag-migrate--backup-db (file-to-backup)
"Create a timestamped backup of the specified database file."
(when (and file-to-backup (file-exists-p file-to-backup))
(let ((backup-file (format "%s.bak-%s"
file-to-backup
(format-time-string "%Y%m%d-%H%M%S"))))
(copy-file file-to-backup backup-file t)
(message "Old database backed up to: %s" backup-file))))
;; ------------------------------------------------------------------
;; Legacy :tag: migration (optional utility)
;; ------------------------------------------------------------------
(defun supertag--detect-headline-tag-style (headline)
"Detect tag style used on HEADLINE element. Returns 'inline, 'org, 'both or 'none."
(let* ((raw (org-element-property :raw-value headline))
(org-tags (org-element-property :tags headline))
(has-inline (and raw (string-match-p "#[^[:space:]#]+" raw)))
(has-org (and org-tags (> (length org-tags) 0))))
(cond
((and has-inline has-org) 'both)
(has-inline 'inline)
(has-org 'org)
(t 'none))))
(defun supertag--rewrite-headline-tags (headline style)
"Rewrite HEADLINE tags to STYLE. Returns plist (:changedp t :begin BEG :end END) or nil."
(let* ((beg (org-element-property :begin headline))
(end (save-excursion (goto-char beg) (end-of-line) (point)))
(level (org-element-property :level headline))
(title (org-element-property :raw-value headline))
(tags (org-element-property :tags headline))
(clean-title (string-trim (replace-regexp-in-string ":[[:alnum:]_@#%]+:" ""
(replace-regexp-in-string "#[^[:space:]#]+" "" title))))
(inline-part (when tags (mapconcat (lambda (tag) (concat "#" tag)) tags " ")))
(org-part (when tags (concat ":" (mapconcat #'identity tags ":") ":")))
(new-line (pcase style
('inline (format "%s %s%s"
(make-string level ?*) clean-title
(if inline-part (concat " " inline-part) "")))
('org (format "%s %s%s"
(make-string level ?*) clean-title
(if org-part (concat " " org-part) "")))
('both (format "%s %s%s%s"
(make-string level ?*) clean-title
(if inline-part (concat " " inline-part) "")
(if org-part (concat " " org-part) "")))
(_ nil))))
(when new-line
(save-excursion
(goto-char beg)
(delete-region beg end)
(insert new-line))
(list :changedp t :begin beg :end (save-excursion (goto-char beg) (end-of-line) (point))))))
(defun supertag-migration--backup-file (file)
"Create a unique adjacent backup for FILE. Return backup path."
(let ((backup
(make-temp-file
(expand-file-name
(format ".%s.supertag-migration-" (file-name-nondirectory file))
(file-name-directory file))
nil ".bak")))
(copy-file file backup t t)
backup))
(defun supertag-migration--restore-backup (file backup)
"Restore FILE from BACKUP. Return t on success."
(when (and (file-exists-p backup))
(copy-file backup file t t)
(when-let* ((buffer (find-buffer-visiting file)))
(with-current-buffer buffer
(let ((inhibit-message t))
(revert-buffer t t t))))
t))
(defconst supertag-migration--reciprocal-buffer
"*Supertag Reciprocal Link Migration*"
"Preview buffer for ambiguous reciprocal links.")
(defun supertag-migration--link-owner (link file-header)
"Return LINK's persistent source ID and title.
FILE-HEADER supplies the owner for links outside every headline."
(let ((parent (org-element-property :parent link)))
(while (and parent (not (eq (org-element-type parent) 'headline)))
(setq parent (org-element-property :parent parent)))
(if parent
(list (org-element-property :ID parent)
(org-element-property :raw-value parent))
(list (plist-get file-header :id)
(plist-get file-header :title)))))
(defun supertag-migration--scan-reference-occurrences (file)
"Return persistent directed reference occurrences physically in FILE."
(with-temp-buffer
(insert-file-contents file)
(delay-mode-hooks (org-mode))
(let* ((file (file-truename file))
(file-hash (secure-hash 'sha256 (current-buffer)))
(file-header (supertag-sync--parse-file-header))
(ast (org-element-parse-buffer))
occurrences)
(org-element-map ast 'link
(lambda (link)
(when-let* ((target (car (supertag--extract-refs (list link))))
(owner (supertag-migration--link-owner link file-header))
(source (car owner)))
(let* ((begin (org-element-property :begin link))
(end (- (org-element-property :end link)
(or (org-element-property :post-blank link) 0)))
(text (buffer-substring-no-properties begin end))
(id (secure-hash
'sha256
(prin1-to-string
(list file file-hash source target begin end text))))
(source-title (or (cadr owner) source))
(target-title
(or (plist-get (supertag-node-get target) :title) target)))
(push
(list :id id :from source :to target :file file
:begin begin :end end
:line (line-number-at-pos begin t)
:text text :file-hash file-hash
:source-title source-title :target-title target-title
:label
(format "Delete %s → %s (%s:%d) [%s]"
source-title target-title
(file-name-nondirectory file)
(line-number-at-pos begin t)
(substring id 0 8)))
occurrences)))))
(nreverse occurrences))))
(defun supertag-migration--reciprocal-candidates (files)
"Return exact mutual directed link occurrences from FILES."
(let ((directions (make-hash-table :test 'equal)) occurrences)
(dolist (file files)
(setq occurrences
(nconc occurrences
(supertag-migration--scan-reference-occurrences file))))
(dolist (item occurrences)
(puthash (cons (plist-get item :from) (plist-get item :to)) t directions))
(sort
(cl-remove-if-not
(lambda (item)
(let ((from (plist-get item :from))
(to (plist-get item :to)))
(and (not (equal from to))
(gethash (cons to from) directions))))
occurrences)
(lambda (left right)
(let ((left-key (cons (plist-get left :file) (plist-get left :begin)))
(right-key (cons (plist-get right :file) (plist-get right :begin))))
(or (string< (car left-key) (car right-key))
(and (equal (car left-key) (car right-key))
(< (cdr left-key) (cdr right-key)))))))))
(defun supertag-migration--show-reciprocal-preview (report)
"Display read-only reciprocal migration REPORT."
(with-current-buffer (get-buffer-create supertag-migration--reciprocal-buffer)
(let ((inhibit-read-only t))
(erase-buffer)
(insert "Ambiguous Reciprocal Link Migration\n\n"
"A mutual pair does not prove which link was an old automatic backlink.\n"
"Nothing is selected or deleted by default.\n\n")
(if (eq 'preview (plist-get report :status))
(progn
(insert (format "%d candidate occurrence(s):\n\n"
(plist-get report :candidate-count)))
(dolist (item (plist-get report :candidates))
(insert "[ ] " (plist-get item :label) "\n"
" " (plist-get item :text) "\n")))
(insert (format "Preview aborted: snapshot is %s.\n"
(plist-get report :snapshot-status)))
(dolist (error (plist-get report :errors))
(insert (format " %s\n" error))))
(goto-char (point-min))
(special-mode))
(display-buffer (current-buffer)))
report)
;;;###autoload
(defun supertag-migration-preview-reciprocal-links (&optional displayp)
"Preview exact link occurrences participating in mutual directed pairs.
The scan is read-only. Mutuality is only a candidate signal: this command
does not infer ownership and does not select anything for deletion."
(interactive (list t))
(let* ((snapshot (supertag-sync--snapshot-build))
(snapshot-status (plist-get snapshot :status))
(files (sort (mapcar #'file-truename
(copy-sequence (plist-get snapshot :files)))
#'string<))
report)
(if (not (eq snapshot-status 'complete))
(setq report
(list :status 'aborted :snapshot-status snapshot-status
:files-scanned 0 :candidate-count 0 :candidates nil
:errors (plist-get snapshot :errors)))
(condition-case err
(let ((candidates
(supertag-migration--reciprocal-candidates files)))
(setq report
(list :status 'preview :snapshot-status snapshot-status
:files-scanned (length files)
:candidate-count (length candidates)
:candidates candidates :errors nil)))
(error
(setq report
(list :status 'aborted :snapshot-status snapshot-status
:files-scanned 0 :candidate-count 0 :candidates nil
:errors (list (error-message-string err)))))))
(if displayp
(supertag-migration--show-reciprocal-preview report)
report)))
(defun supertag-migration--restore-state-table (table snapshot)
"Replace TABLE contents with SNAPSHOT."
(clrhash table)
(maphash (lambda (key value) (puthash key value table)) snapshot))
(defun supertag-migration--selected-candidates (report candidate-ids)
"Resolve CANDIDATE-IDS against REPORT, or return nil if stale."
(let ((wanted (delete-dups (copy-sequence candidate-ids))) selected)
(dolist (id wanted)
(when-let* ((item (cl-find id (plist-get report :candidates)
:key (lambda (candidate)
(plist-get candidate :id))
:test #'equal)))
(push item selected)))
(when (= (length wanted) (length selected))
(nreverse selected))))
;;;###autoload
(defun supertag-migration-execute-reciprocal-links (report candidate-ids)
"Delete exact CANDIDATE-IDS selected from preview REPORT.
Return a report plist. Empty or stale selections abort without writes.
Every affected Org file is backed up before the first deletion; file and
Store changes are restored if projection fails."
(if (null candidate-ids)
(list :status 'aborted :reason 'no-selection :removed 0)
(let* ((fresh (supertag-migration-preview-reciprocal-links))
(original (supertag-migration--selected-candidates report candidate-ids))
(selected (and original
(supertag-migration--selected-candidates fresh candidate-ids))))
(if (or (not (eq 'preview (plist-get fresh :status)))
(null original) (null selected))
(list :status 'aborted :reason 'stale-preview :removed 0)
(let* ((files (delete-dups (mapcar (lambda (item) (plist-get item :file))
selected)))
(state-table (supertag-sync--get-state-table))
(state-before (copy-hash-table state-table))
(deferred-before (copy-hash-table supertag-sync--deferred-files))
(internal-before
(copy-hash-table supertag-sync--internal-modifications))
(snapshot-before (copy-tree (supertag-sync--snapshot-get)))
(counters '(:nodes-created 0 :nodes-updated 0 :nodes-deleted 0
:references-created 0 :references-deleted 0))
buffers opened backups report-result)
(unwind-protect
(condition-case err
(progn
;; Refuse to overwrite user edits and validate every exact range
;; before creating snapshots or touching any file.
(dolist (file files)
(let* ((existing (find-buffer-visiting file))
(buffer (or existing (find-file-noselect file))))
(unless existing (push buffer opened))
(with-current-buffer buffer
(when (buffer-modified-p)
(error "Unsaved edits in %s" file))
(unless (verify-visited-file-modtime buffer)
(revert-buffer t t t))
(dolist (item (cl-remove-if-not
(lambda (candidate)
(equal file (plist-get candidate :file)))
selected))
(unless (and (<= (plist-get item :end) (point-max))
(equal (plist-get item :text)
(buffer-substring-no-properties
(plist-get item :begin)
(plist-get item :end))))
(error "Stale link occurrence in %s" file))))
(push (cons file buffer) buffers)))
(dolist (file files)
(push (cons file (supertag-migration--backup-file file)) backups))
(supertag-with-transaction
(dolist (pair buffers)
(let ((file (car pair)))
(with-current-buffer (cdr pair)
(save-restriction
(widen)
(dolist
(item
(sort
(cl-remove-if-not
(lambda (candidate)
(equal file (plist-get candidate :file)))
(copy-sequence selected))
(lambda (left right)
(> (plist-get left :begin)
(plist-get right :begin)))))
(delete-region (plist-get item :begin)
(plist-get item :end))))
(supertag--mark-internal-modification file)
(save-buffer))))
(let ((supertag-sync--is-full-rescan-p t))
(dolist (file files)
(supertag-sync--process-single-file file counters)))
(supertag-sync--rebuild-reference-caches))
(setq report-result
(list :status 'complete :removed (length selected)
:files-changed (length files)
:backups (nreverse backups))))
(error
(let (restore-errors)
(dolist (pair backups)
(condition-case restore-error
(supertag-migration--restore-backup (car pair) (cdr pair))
(error
(push (error-message-string restore-error) restore-errors))))
(supertag-migration--restore-state-table state-table state-before)
(setq supertag-sync--deferred-files deferred-before
supertag-sync--internal-modifications internal-before)
(supertag-sync--snapshot-set snapshot-before)
(when restore-errors
(error "Migration and recovery failed; backups: %S; errors: %S"
backups (nreverse restore-errors)))
(setq report-result
(list :status 'failed :removed 0
:files-changed 0 :backups (nreverse backups)
:errors (list (error-message-string err)))))))
(dolist (buffer opened)
(when (buffer-live-p buffer) (kill-buffer buffer))))
report-result)))))
;;;###autoload
(defun supertag-migrate-reciprocal-links ()
"Preview and explicitly select ambiguous reciprocal links to delete."
(interactive)
(let* ((preview (supertag-migration-preview-reciprocal-links))
(candidates (plist-get preview :candidates)))
(supertag-migration--show-reciprocal-preview preview)
(cond
((not (eq 'preview (plist-get preview :status))) preview)
((null candidates)
(message "Supertag: no reciprocal link candidates found")
(list :status 'aborted :reason 'no-candidates :removed 0))
(t
(let* ((labels (mapcar (lambda (item) (plist-get item :label)) candidates))
(chosen-labels
(completing-read-multiple
"Delete exact link occurrences (none by default): " labels nil t))
(chosen
(cl-remove-if-not
(lambda (item) (member (plist-get item :label) chosen-labels))
candidates)))
(cond
((null chosen)
(list :status 'aborted :reason 'no-selection :removed 0))
((not (yes-or-no-p
(format "Delete %d selected link occurrence(s)? " (length chosen))))
(list :status 'aborted :reason 'confirmation-declined :removed 0))
(t
(let ((result
(supertag-migration-execute-reciprocal-links
preview (mapcar (lambda (item) (plist-get item :id)) chosen))))
(message "Supertag reciprocal migration: %s, %d removed"
(plist-get result :status) (or (plist-get result :removed) 0))
result))))))))
(defun supertag-migrate-legacy-tags-file (file &optional dry-run)
"Migrate org native :tag: in FILE to inline #tags. Returns report plist.
When DRY-RUN is non-nil, do not modify the file; only report changes."
(unless (file-exists-p file)
(error "File not found: %s" file))
(let ((changed 0) (errors '()) (backups '()) (headlines 0))
(with-current-buffer (find-file-noselect file)
(save-excursion
(goto-char (point-min))
(let ((ast (org-element-parse-buffer)))
(org-element-map ast 'headline
(lambda (hl)
(setq headlines (1+ headlines))
(let ((style (supertag--detect-headline-tag-style hl)))
(when (memq style '(org both))
(condition-case err
(unless dry-run
;; Ensure single backup per file
(unless (assoc file backups)
(push (cons file (supertag-migration--backup-file file)) backups))
(when (supertag--rewrite-headline-tags hl 'inline)
(setq changed (1+ changed))))
(error (push (format "%s" err) errors))))))
(unless dry-run (save-buffer)))))
(list :file file :changed changed :headlines headlines :backups (mapcar #'cdr backups) :errors errors))))
(defun supertag-migrate-legacy-tags-directory (dir &optional dry-run)
"Migrate all .org files in DIR (recursively). Returns report plist."
(let ((files (directory-files-recursively dir "\\.org$" t))
(total 0) (changed 0) (errors '()) (reports '()) (backups '()))
(dolist (f files)
(setq total (1+ total))
(let ((r (supertag-migrate-legacy-tags-file f dry-run)))
(setq changed (+ changed (plist-get r :changed)))
(setq reports (cons r reports))
(setq backups (append backups (plist-get r :backups)))
(setq errors (append errors (plist-get r :errors)))))
(list :files (length files) :changed changed :reports (nreverse reports) :backups backups :errors errors)))
(defun supertag-migrate--process-data (old-objects old-links old-embeds)
"Process old data and return a new store and indexes."
(let ((store (ht-create))
(nodes-ht (ht-create))
(tags-ht (ht-create))
(fields-ht (ht-create))
(relations-ht (ht-create))
(embeds-ht (ht-create))
(id-mapping (ht-create))) ; Track old-id -> new-id mappings
(puthash :nodes nodes-ht store)
(puthash :tags tags-ht store)
(puthash :fields fields-ht store)
(puthash :relations relations-ht store)
(when old-embeds
(puthash :embeds embeds-ht store))
;; Process objects
(maphash
(lambda (id props)
(let ((type (plist-get props :type))
;; Clean escaped strings in the properties
(cleaned-props (supertag-migrate--clean-plist-strings props)))
(cond ((eq type :node)
;; Preserve existing node-id to maintain file consistency
(let* ((enhanced-props (supertag-migrate--ensure-node-location-data cleaned-props))
(final-props (plist-put enhanced-props :id id)))
;; Handle tags stored directly on the node object's :tags property.
(let ((old-tags (plist-get final-props :tags)))
(if (listp old-tags)
;; If :tags exists and is a list, sanitize the tag names
;; into the new ID format and replace the property.
(let ((new-tags-list
(delq nil
(mapcar (lambda (tag-name)
(when (and (stringp tag-name) (not (string-empty-p tag-name)))
(let ((sanitized-tag (supertag-migrate--sanitize-tag-name tag-name)))
;; CRITICAL: Ensure a corresponding tag definition exists in the central registry.
;; If not, create a minimal one on-demand, preserving any existing fields.
(unless (gethash sanitized-tag tags-ht)
(puthash sanitized-tag
`(:id ,sanitized-tag
:name ,tag-name
:type :tag
:fields nil
:extends nil)
tags-ht))
sanitized-tag)))
old-tags))))
(setq final-props (plist-put final-props :tags new-tags-list)))
;; If :tags is not a list or is nil, remove it to ensure clean data.
(setq final-props (plist-remove final-props :tags))))
(message "Migrating node (preserving ID): %s" id)
(puthash id final-props nodes-ht)
;; No ID mapping needed since we preserve the original ID
(puthash id id id-mapping)))
((eq type :tag)
;; Convert old tag-id to semantic name format
(let* ((tag-name (or (plist-get cleaned-props :name) id))
(new-tag-id (supertag-migrate--sanitize-tag-name tag-name))
;; Preserve existing fields and extends, or set to nil if not present
(fields (plist-get cleaned-props :fields))
(extends (plist-get cleaned-props :extends))
(final-props (plist-put
(plist-put
(plist-put cleaned-props :id new-tag-id)
:fields (or fields nil))
:extends (or extends nil))))
(message "Migrating tag: %s -> %s (fields: %s, extends: %s)"
id new-tag-id
(if fields "yes" "no")
(if extends "yes" "no"))
(puthash new-tag-id final-props tags-ht)
;; Store mapping for updating relations later
(puthash id new-tag-id id-mapping)))
(t (message "Skipping unknown object type: %s" type)))))
old-objects)
;; Process embeds if they exist
(when old-embeds
(maphash
(lambda (id props)
(puthash id props embeds-ht))
old-embeds))
;; Process links
(maphash
(lambda (link-id link-props)
(let* ((type (plist-get link-props :type))
(from (plist-get link-props :from))
(to (plist-get link-props :to)))
(pcase type
(:node-tag
;; Map old IDs to new IDs
(let* ((new-from (gethash from id-mapping from))
(new-to (gethash to id-mapping to))
(node-data (gethash new-from nodes-ht)))
;; Ensure both node and tag exist before creating the link.
(when (and node-data new-to)
(puthash new-from
(plist-put node-data :tags (cl-adjoin new-to (plist-get node-data :tags)))
nodes-ht))))
(:node-field
;; Map old IDs to new IDs
(let* ((new-from (gethash from id-mapping from))
(old-tag-id (plist-get link-props :tag-id))
(new-tag-id (gethash old-tag-id id-mapping))
(value (plist-get link-props :value)))
;; Ensure the node, the associated tag, and the value all exist.
(when (and new-from to new-tag-id value)
(let ((node-fields (gethash new-from fields-ht (ht-create))))
(puthash new-from node-fields fields-ht)
(let ((tag-fields (gethash new-tag-id node-fields (ht-create))))
(puthash new-tag-id tag-fields node-fields)
(puthash to value tag-fields))))))
(:node-ref
;; Map old IDs to new IDs
(let* ((new-from (gethash from id-mapping from))
(new-to (gethash to id-mapping to))
(node-data (gethash new-from nodes-ht)))
(when (and node-data new-to)
(puthash new-from
(plist-put node-data :refs (cl-adjoin new-to (plist-get node-data :refs)))
nodes-ht))))
(_
;; Map old IDs to new IDs for relations
(let* ((new-from (gethash from id-mapping from))
(new-to (gethash to id-mapping to)))
;; Only create the relation if both endpoints were successfully migrated.
(when (and new-from new-to)
(let* ((new-rel-id (supertag-migrate--generate-relation-id new-from new-to type))
(updated-props (plist-put (plist-put link-props :from new-from) :to new-to)))
(message "Migrating relation: %s -> %s" link-id new-rel-id)
(puthash new-rel-id updated-props relations-ht))))))))
old-links)
;; Return the new store
store))
(defun supertag-migrate--build-indexes (store)
"Build all performance indexes from the STORE."
(unless (hash-table-p store)
(error "Invalid store: expected hash table, got %s" (type-of store)))
(let ((indexes (ht-create))
(nodes-ht (gethash :nodes store)))
;; Validate nodes-ht
(unless (hash-table-p nodes-ht)
(error "Invalid nodes hash table: expected hash table, got %s" (type-of nodes-ht)))
(puthash :tags (ht-create) indexes)
(puthash :words (ht-create) indexes)
(puthash :dates (ht-create) indexes)
(let ((tag-idx (gethash :tags indexes))
(word-idx (gethash :words indexes))
(date-idx (gethash :dates indexes)))
;; Only proceed if nodes-ht is valid and not empty
(when (and (hash-table-p nodes-ht) (> (hash-table-count nodes-ht) 0))
(maphash
(lambda (node-id node-data)
;; 1. Build tag index
(let ((tags (plist-get node-data :tags)))
(when tags
(dolist (tag tags)
(when tag
(let ((nodes-list (gethash tag tag-idx '())))
(unless (member node-id nodes-list)
(puthash tag (cons node-id nodes-list) tag-idx)))))))
;; 2. Build word index from title and content
(dolist (text (list (plist-get node-data :title)
(plist-get node-data :content)))
(when (stringp text)
(dolist (word (split-string (downcase text) "[^[:word:]]+" t))
(when (> (length word) 2)
(let ((nodes-list (gethash word word-idx '())))
(unless (member node-id nodes-list)
(puthash word (cons node-id nodes-list) word-idx)))))))
;; 3. Build date index
(let ((created (plist-get node-data :created-at))
(modified (plist-get node-data :modified-at)))
(when created
(let ((date-map (gethash :created-at date-idx (ht-create))))
(puthash :created-at date-map date-idx)
(puthash node-id created date-map)))
(when modified
(let ((date-map (gethash :modified-at date-idx (ht-create))))
(puthash :modified-at date-map date-idx)
(puthash node-id modified date-map)))))
nodes-ht)))
indexes))
(defun supertag-migrate--save-new-db (store indexes)
"Save the new STORE and INDEXES to the conventional file location."
(let* ((default-dir (expand-file-name "supertag" user-emacs-directory))
(new-db-file (expand-file-name "supertag-db.el" default-dir)))
(make-directory default-dir t)
(message "Saving new database to %s..." new-db-file)
(with-temp-file new-db-file
;; Use the most robust method to ensure UTF-8 output, by controlling
;; the buffer-local coding system, the file-writing coding system,
;; and the printer's escaping behavior.
(let ((buffer-file-coding-system 'utf-8-unix)
(coding-system-for-write 'utf-8-unix)
(coding-system-for-read 'utf-8-unix)
(print-escape-nonascii nil)
(print-escape-multibyte nil)
(print-escape-control-characters nil)
(print-quoted-char-oneline nil)
(print-escape-newlines nil)
(print-continuous-numbering nil)
(print-gensym nil))
(setq-local buffer-file-coding-system 'utf-8-unix)
(setq-local coding-system-for-write 'utf-8-unix)
(let ((print-level nil)
(print-length nil)
(print-circle nil)
(print-escape-nonascii nil)
(print-escape-multibyte nil)
(print-escape-control-characters nil)
(print-quoted-char-oneline nil)
(print-escape-newlines nil)
(print-continuous-numbering nil)
(print-gensym nil))
(insert ";;; supertag.db --- Data store for Supertag\n")
(insert ";;; -*- coding: utf-8 -*-\n\n")
;; Output store data directly as hash table (compatible with supertag-store.el)
(insert ";; supertag--store data\n")
(prin1 (ht-deep-copy-table store) (current-buffer))
(insert "\n\n")
;; Output index data directly as hash table
(insert ";; supertag--store-indexes data\n")
(prin1 (ht-deep-copy-table indexes) (current-buffer))
(insert "\n"))))
(message "Data migration successfully completed!")
(message "New database file is at: %s" new-db-file)))
;;;###autoload
(defun supertag-migrate-database-to-new-arch ()
"Interactively migrate an old org-supertag-db.el file to the new data-centric store."
(interactive)
(let ((old-db-file (read-file-name "Select your old org-supertag-db.el file: ")))
(unless (and old-db-file (file-exists-p old-db-file))
(user-error "Migration cancelled: File not found."))
(when (yes-or-no-p (format "Migrate from %s? (A backup will be created)" old-db-file))
(message "Starting self-contained migration...")
(supertag-migrate--backup-db old-db-file)
(message "Safely loading data from %s..." old-db-file)
(let* ((old-data (supertag-migrate--safely-load-data old-db-file))
(old-objects (car old-data))
(old-links (cadr old-data))
(old-embeds (nth 2 old-data)))
(message "Loaded %d objects and %d links."
(hash-table-count old-objects)
(hash-table-count old-links))
(message "Processing data into new format...")
(let* ((new-store (supertag-migrate--process-data old-objects old-links old-embeds))
(new-indexes (supertag-migrate--build-indexes new-store)))
(message "Saving new database to file...")
(supertag-migrate--save-new-db new-store new-indexes))))))
;; ------------------------------------------------------------------
;; Global field model migration (modern store -> global fields)
;; ------------------------------------------------------------------
(defcustom supertag-migration-log-buffer "*supertag-migration*"
"Buffer name for migration logs."
:type 'string
:group 'supertag-migration)
(defcustom supertag-migration-dry-run t
"When non-nil, migration commands default to dry-run (no writes)."
:type 'boolean
:group 'supertag-migration)
(defvar supertag-migration--stats nil
"Plist of migration stats for the current run.")
(defun supertag-migration--log (fmt &rest args)
"Log formatted message to `supertag-migration-log-buffer'."
(with-current-buffer (get-buffer-create supertag-migration-log-buffer)
(goto-char (point-max))
(insert (apply #'format (concat fmt "\n") args))))
(defun supertag-migration--reset-stats ()
"Reset migration stats."
(setq supertag-migration--stats
'(:fields-created 0
:associations-created 0
:values-migrated 0
:conflicts nil
:skipped 0))
(supertag-migration--log "Stats reset: %S" supertag-migration--stats))
(defun supertag-migration--increment (key &optional delta)
"Increment KEY in stats by DELTA (default 1)."
(let* ((delta (or delta 1))
(current (plist-get supertag-migration--stats key)))
(setq supertag-migration--stats
(plist-put supertag-migration--stats key (+ (or current 0) delta)))))
(defun supertag-migration--record-conflict (item)
"Record conflict ITEM in stats."
(let* ((entry (if (and item (listp item))
item
(list :reason :unspecified :raw item)))
(existing (plist-get supertag-migration--stats :conflicts))
(updated (cons entry existing)))
(setq supertag-migration--stats
(plist-put supertag-migration--stats :conflicts updated))
(supertag-migration--log "Conflict recorded entry=%S updated=%S" entry updated)))
(defun supertag-migration--dry-run-p (&optional force)
"Return t when dry-run is active, unless FORCE is non-nil."
(and (not force)
(or supertag-migration-dry-run
(bound-and-true-p current-prefix-arg))))
(defun supertag-migration--compare-field-defs (a b)
"Return non-nil when field definitions A and B are compatible.
Compares :type and :config/ :options, ignoring ordering of plist."
(and (eq (plist-get a :type) (plist-get b :type))
(equal (plist-get a :config) (plist-get b :config))
(equal (plist-get a :options) (plist-get b :options))))
(defun supertag-migration--sanitize-field-id (field-name)
"Return sanitized field id for FIELD-NAME or nil."
(supertag-sanitize-field-id field-name))
(defun supertag-migration--collect-tag-fields ()
"Return list of (TAG-ID . FIELD-PLISTS) from legacy tag definitions."
(let ((tags (supertag-store-get-collection :tags))
result)
(when (hash-table-p tags)
(maphash
(lambda (tag-id tag-data)
(let* ((plist (cond
((hash-table-p tag-data)
(let (p)
(maphash (lambda (k v) (setq p (plist-put p k v))) tag-data)
p))
((listp tag-data) tag-data)
(t nil)))
(fields (plist-get plist :fields)))
(when (listp fields)
(push (cons tag-id fields) result))))
tags))
(nreverse result)))
(defconst supertag-migration--global-field-backup-collections
'(:tags :fields :field-definitions :tag-field-associations :field-values)
"Collections that a global field migration can change.")
(defconst supertag-migration--invalid-association
(list :supertag-invalid-association)
"Sentinel returned for a malformed global field association.")
(defun supertag-migration--stable-value (value)
"Return deterministic representation of VALUE for audit output."
(supertag--persistence--canonicalize-value value))
(defun supertag-migration--stable-equal-p (left right)
"Return non-nil when LEFT and RIGHT have equal canonical contents."
(equal (supertag-migration--stable-value left)
(supertag-migration--stable-value right)))
(defun supertag-migration--audit-definition-plist (definition)
"Return DEFINITION as a plist, or nil when it has no valid mapping shape."
(cond
((hash-table-p definition)
(let (result)
(maphash (lambda (key value)
(setq result (plist-put result key value)))
definition)
result))
((and (listp definition)
(proper-list-p definition)
(zerop (% (length definition) 2))
(cl-loop for (key _) on definition by #'cddr
always (keywordp key)))
definition)))
(defun supertag-migration--audit-field-definition-valid-p (definition)
"Return non-nil when DEFINITION has a name and keyword type."
(when-let* ((plist
(supertag-migration--audit-definition-plist definition)))
(and (stringp (plist-get plist :name))
(keywordp (plist-get plist :type)))))
(defun supertag-migration--audit-field-defs-equal-p (left right)
"Return non-nil when LEFT and RIGHT have equal field semantics.
`:id' and display `:name' may differ; every other property must match."
(cl-labels ((signature (definition)
(when-let* ((plist
(supertag-migration--audit-definition-plist
definition)))