Repository navigation
Expand file tree
/
Copy pathStorageSelfTest.java
More file actions
839 lines (752 loc) · 42.9 KB
/
Copy pathStorageSelfTest.java
File metadata and controls
839 lines (752 loc) · 42.9 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
import com.qoder.taskdeck.Json;
import com.qoder.taskdeck.LedgerFile;
import com.qoder.taskdeck.LocalStore;
import com.qoder.taskdeck.StoreMerge;
import com.qoder.taskdeck.Task;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* JVM self-test for the TaskDeck storage core. Run it on a Mac with the Mac's
* real store as the only argument:
*
* java StorageSelfTest ~/TaskDeck/tasks.json
*
* Every check prints PASS/FAIL; the exit code is 1 if any assertion failed.
*/
public class StorageSelfTest {
private static int passed;
private static int failed;
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("usage: StorageSelfTest <path-to-mac-tasks.json>");
System.exit(2);
}
try {
testJson();
testIso8601();
testMergeSemantics();
testTombstones();
testWireShape();
testLocalStore();
// Detailed assertions run against a frozen fixture, so the suite cannot
// break when the user files another task. The live store is only
// smoke-tested for parseability and stability.
File fixture = new File(args.length > 1 ? args[1] : "testdata/mac-store-fixture.json");
if (fixture.isFile()) testRealMacFile(fixture);
else check(false, "mac: fixture missing at " + fixture.getAbsolutePath());
smokeTestLiveStore(new File(args[0]));
} catch (Throwable t) {
failed++;
System.out.println("FAIL unexpected exception escaped the tests: " + t);
t.printStackTrace(System.out);
}
System.out.println("--------------------------------------------------");
System.out.println("assertions " + (passed + failed) + ", passed " + passed + ", failed " + failed);
System.out.println(failed == 0 ? "ALL PASS" : "TEST FAILURES");
System.exit(failed == 0 ? 0 : 1);
}
// ------------------------------------------------------------------ json
private static void testJson() {
String tricky = "He said \"ship it\" \u2014 caf\u00e9 \u4e2d\u6587 \ud83d\ude42 "
+ "path C:\\Temp url http://example.com/a?b=c </script>"
+ " line\nbreak\ttab"
+ (char) 0x2028 + "sep" + (char) 0x2029
+ " nested {\"key\": \"}v{\" }";
Map<String, Object> logEntry = new LinkedHashMap<String, Object>();
logEntry.put("at", "2026-09-22T20:28:29.205Z");
logEntry.put("author", "qoder");
logEntry.put("id", "9921DE2C-1588-48DD-BAF9-B07DFAC8E913");
logEntry.put("text", "a \\ \"quoted\" {brace} payload");
Map<String, Object> t = new LinkedHashMap<String, Object>();
t.put("id", "t99zz9");
t.put("title", "Rounded \ud83d\ude42 trip");
t.put("notes", tricky);
t.put("status", "open");
t.put("priority", "high");
t.put("order", Long.valueOf(10));
t.put("weight", Double.valueOf(2.5));
t.put("timed", Boolean.FALSE);
t.put("completedAt", null);
t.put("tags", Arrays.asList("caf\u00e9", "q\"x", "back\\slash", "a/b"));
t.put("log", Arrays.<Object>asList(logEntry));
Map<String, Object> doc = new LinkedHashMap<String, Object>();
doc.put("version", Long.valueOf(1));
doc.put("updatedAt", "2026-09-22T20:14:30.531Z");
doc.put("tasks", new ArrayList<Object>(Arrays.<Object>asList(t)));
doc.put("deleted", new LinkedHashMap<String, Object>());
String text = Json.write(doc);
check(text.contains("\\/"), "json: forward slash escaped like Foundation");
check(text.contains("\\u2028") && text.contains("\\u2029"), "json: U+2028/U+2029 escaped");
check(text.indexOf("\ud83d\ude42") >= 0 && text.indexOf("\u4e2d\u6587") >= 0,
"json: non-ASCII emitted raw as UTF-8, not \\u escaped (like Foundation)");
check(text.indexOf("weight\" : 2.5") > 0, "json: Double keeps its fraction");
check(text.indexOf("order\" : 10") > 0, "json: Long prints bare");
Object back = Json.parse(text);
check(back instanceof LinkedHashMap, "json: document parses to LinkedHashMap");
checkEq(((Map<?, ?>) back).get("version"), Long.valueOf(1), "json: integers parse as Long");
check(Json.parse("7.5") instanceof Double, "json: fraction parses as Double");
check(Json.parse("-3e2") instanceof Double
&& ((Double) Json.parse("-3e2")).doubleValue() == -300.0, "json: exponent parses as Double");
check(Json.parse("null") == null, "json: null literal");
check(Json.parse("true").equals(Boolean.TRUE) && Json.parse("false").equals(Boolean.FALSE),
"json: boolean literals");
check(Json.parse("[1,2]") instanceof ArrayList, "json: arrays parse to ArrayList");
checkEq(Json.write(back), text, "json: write(parse(x)) byte-stable");
checkEq(back, doc, "json: deep structural round trip (unicode, quotes, backslashes, braces)");
Map<?,?> odd = (Map<?,?>) Json.parse("{\"a\":\"x {\\\"y\\\"} z\",\"b\":[{\"c\":null,\"d\":true}]}");
checkEq(odd.get("a"), "x {\"y\"} z", "json: string containing escaped quotes and braces");
List<?> bl = (List<?>) odd.get("b");
checkEq(((Map<?, ?>) bl.get(0)).get("d"), Boolean.TRUE, "json: nested array-of-objects intact");
checkEq(Json.parse("\"a\\/b\""), "a/b", "json: \\/ unescapes");
checkEq(Json.parse("\"\\u0041\""), "A", "json: \\uXXXX unescapes");
Map<String, Object> ba = new LinkedHashMap<String, Object>();
ba.put("b", Long.valueOf(1));
ba.put("a", Long.valueOf(2));
checkEq(Json.write(ba), "{\n \"a\" : 2,\n \"b\" : 1\n}", "json: keys sorted, Swift pretty spacing");
checkEq(Json.write(new LinkedHashMap<String, Object>()), "{\n\n}", "json: empty object as Swift emits");
checkEq(Json.write(new ArrayList<Object>()), "[\n\n]", "json: empty array as Swift emits");
Map<String, Object> withEmpty = new LinkedHashMap<String, Object>();
withEmpty.put("k", new LinkedHashMap<String, Object>());
checkEq(Json.write(withEmpty), "{\n \"k\" : {\n\n }\n}", "json: nested empty container indent");
checkThrowsJson("{", "json: unclosed object throws");
checkThrowsJson("[1,]", "json: trailing comma throws");
checkThrowsJson("{'a':1}", "json: single quotes throw");
checkThrowsJson("", "json: empty input throws");
checkThrowsJson("nul", "json: truncated literal throws");
checkThrowsJson("[1] [2]", "json: trailing document throws");
checkThrowsJson("{\"a\" 1}", "json: missing colon throws");
checkThrowsJson("\"unterminated", "json: unterminated string throws");
check(Json.parse(" {\"a\":1} ") instanceof Map, "json: surrounding whitespace tolerated");
}
// ------------------------------------------------------------------- iso
private static void testIso8601() {
long frac = Json.parseIso8601("2026-09-22T20:14:30.531Z");
checkEq(Json.iso8601(frac), "2026-09-22T20:14:30.531Z", "iso: fractional round trip");
long whole = Json.parseIso8601("2026-09-22T20:14:30Z");
checkEq(Json.iso8601(whole), "2026-09-22T20:14:30.000Z", "iso: whole-second form parsed, .000 emitted");
checkEq(whole, Json.parseIso8601("2026-09-22T20:14:30.000Z"), "iso: whole == .000");
checkEq(Json.parseIso8601("2026-09-23T01:44:30.531+05:30"), Long.valueOf(frac), "iso: +HH:mm offset");
checkEq(Json.parseIso8601("2026-09-22T12:14:30.531-08:00"), Long.valueOf(frac), "iso: -HH:mm offset");
checkEq(Json.parseIso8601("2026-09-23T01:44:30.531+0530"), Long.valueOf(frac), "iso: offset without colon");
checkEq(Json.parseIso8601("2026-09-22T20:14:30.531999Z"), Long.valueOf(frac),
"iso: long fraction truncates to millis");
checkEq(Json.parseIso8601("2026-09-22T20:14:30.5Z"), Long.valueOf(frac - 31L), "iso: short fraction pads");
checkEq(Json.parseIso8601("1970-01-01T00:00:00.000Z"), Long.valueOf(0L), "iso: epoch zero");
checkEq(Json.iso8601(0L), "1970-01-01T00:00:00.000Z", "iso: epoch zero prints");
checkEq(Json.iso8601(-1L), "1969-12-31T23:59:59.999Z", "iso: pre-epoch floor arithmetic");
checkEq(Json.parseIso8601("1969-12-31T23:59:59.999Z"), Long.valueOf(-1L), "iso: pre-epoch parses");
checkEq(Json.parseIso8601("2000-01-01T00:00:00Z"), Long.valueOf(946684800000L), "iso: Y2K anchor");
checkEq(Json.parseIso8601("2024-01-01T00:00:00Z"), Long.valueOf(1704067200000L), "iso: 2024 anchor");
checkEq(Json.parseIso8601("2024-03-01T00:00:00Z") - Json.parseIso8601("2024-02-28T00:00:00Z"),
Long.valueOf(2 * 86400000L), "iso: leap February has 29 days");
checkEq(Json.parseIso8601("2025-03-01T00:00:00Z") - Json.parseIso8601("2025-02-28T00:00:00Z"),
Long.valueOf(86400000L), "iso: common February has 28 days");
checkEq(Json.iso8601(Json.parseIso8601("9999-12-31T23:59:59.999Z")), "9999-12-31T23:59:59.999Z",
"iso: far future round trip");
checkThrowsIso("", "iso: empty throws");
checkThrowsIso("nope", "iso: garbage throws");
checkThrowsIso("2026-09-22 20:14:30Z", "iso: space separator rejected");
checkThrowsIso("2026-09-22T20:14Z", "iso: missing seconds rejected");
checkThrowsIso("2026-09-22T20:14:30", "iso: missing zone rejected");
checkThrowsIso("2026-13-01T00:00:00Z", "iso: month 13 rejected");
checkThrowsIso("2026-09-22T25:00:00Z", "iso: hour 25 rejected");
checkThrowsIso("2025-02-29T00:00:00Z", "iso: non-leap Feb 29 rejected");
checkThrowsIso("2026-09-22T20:14:61Z", "iso: second 61 rejected");
checkThrowsIso("2026-09-22T20:14:30.Z", "iso: empty fraction rejected");
checkThrowsIso("2026-09-32T00:00:00Z", "iso: day 32 rejected");
checkThrowsIso("2026-09-22T20:14:30+99:00", "iso: absurd offset rejected");
checkThrowsIso("2026-09-22T20:14:30Z ", "iso: trailing space rejected");
checkThrowsIso("+400-01-01T00:00:00Z", "iso: non-four-digit year rejected");
}
// ----------------------------------------------------------------- merge
private static void testMergeSemantics() {
Task a1 = task("ta1", "a1-local", 100L, 50L, 10);
Task a2 = task("ta2", "a2-only-local", 200L, 60L, 20);
LedgerFile A = fileOf(1000L, a1, a2);
A.version = 2;
Task b1 = task("ta1", "a1-remote", 150L, 50L, 10);
Task b3 = task("tb3", "b3-only-remote", 90L, 40L, 30);
LedgerFile B = fileOf(900L, b1, b3);
B.version = 3;
LedgerFile m1 = StoreMerge.merge(A, B);
checkEq(m1.tasks.size(), Integer.valueOf(3), "merge: union of tasks by id");
checkEq(m1.find("ta1").title, "a1-remote", "merge: strictly newer remote replaces local");
check(m1.find("ta2") != null && m1.find("tb3") != null, "merge: side-exclusive tasks both survive");
LedgerFile m2 = StoreMerge.merge(B, A);
checkEq(m2.find("ta1").title, "a1-remote", "merge: newest wins regardless of argument order");
checkEq(m2.find("tb3").title, "b3-only-remote", "merge: reverse direction still unions");
Task f1 = task("tx", "first", 500L, 1L, 5);
Task f2 = task("tx", "second", 500L, 1L, 5);
checkEq(StoreMerge.merge(fileOf(0L, f1), fileOf(0L, f2)).find("tx").title, "first",
"merge: equal stamps keep the first argument's copy");
checkEq(StoreMerge.merge(fileOf(0L, f2), fileOf(0L, f1)).find("tx").title, "second",
"merge: ...which is whichever copy is passed first");
checkEq(m1.version, 3, "merge: version is the max of both");
checkEq(m1.updatedAt, 1000L, "merge: updatedAt is the max of both");
LedgerFile dx = fileOf(1L);
dx.deleted.put("td1", Long.valueOf(10L));
dx.deleted.put("td2", Long.valueOf(50L));
LedgerFile dy = fileOf(1L);
dy.deleted.put("td1", Long.valueOf(20L));
dy.deleted.put("td3", Long.valueOf(30L));
LedgerFile md = StoreMerge.merge(dx, dy);
checkEq(md.deleted.size(), Integer.valueOf(3), "merge: deleted is the union");
checkEq(md.deleted.get("td1"), Long.valueOf(20L), "merge: deleted keeps the newer stamp");
checkEq(md.deleted.get("td2"), Long.valueOf(50L), "merge: local-only tombstone kept");
checkEq(md.deleted.get("td3"), Long.valueOf(30L), "merge: remote-only tombstone kept");
Task o3 = task("to3", "order-30", 10L, 1000L, 30);
Task o2 = task("to2", "order-10-older", 10L, 99L, 10);
Task o1 = task("to1", "order-10-newest", 10L, 1L, 10);
LedgerFile sorted = StoreMerge.merge(fileOf(1L, o3, o2, o1), LedgerFile.empty());
checkEq(idSequence(sorted), "[to1, to2, to3]", "merge: tasks sorted by order then createdAt");
checkEq(A.tasks.size(), Integer.valueOf(2), "merge: first input left untouched");
checkEq(B.tasks.size(), Integer.valueOf(2), "merge: second input left untouched");
LedgerFile idem = StoreMerge.merge(A, A.copy());
checkEq(idSequence(idem), idSequence(A), "merge: a file merged with itself is unchanged");
}
// ----------------------------------------------------------- tombstones
private static void testTombstones() {
LedgerFile local = fileOf(1000L, task("td", "about-to-die", 100L, 50L, 10));
LedgerFile remote = fileOf(2000L);
remote.deleted.put("td", Long.valueOf(200L));
LedgerFile dead = StoreMerge.merge(local, remote);
check(dead.find("td") == null, "tombstone: newer marker removes the task during merge");
checkEq(dead.deleted.get("td"), Long.valueOf(200L), "tombstone: the marker survives");
LedgerFile deadRev = StoreMerge.merge(remote, local);
check(deadRev.find("td") == null, "tombstone: delete happens in either merge direction");
LedgerFile l2 = fileOf(1L, task("td", "restored", 300L, 50L, 10));
LedgerFile r2 = fileOf(1L);
r2.deleted.put("td", Long.valueOf(200L));
LedgerFile revived = StoreMerge.merge(l2, r2);
check(revived.find("td") != null, "tombstone: strictly newer task revives");
check(revived.deleted.isEmpty(), "tombstone: revive clears the marker inside merge");
LedgerFile tie = fileOf(1L, task("td", "tie", 200L, 50L, 10));
tie.deleted.put("td", Long.valueOf(200L));
LedgerFile tieOut = StoreMerge.merge(tie, LedgerFile.empty());
check(tieOut.find("td") == null && tieOut.deleted.containsKey("td"),
"tombstone: equal stamps — the marker still wins (replacement is strictly greater)");
LedgerFile f = fileOf(1L, task("tr", "back from the dead", 250L, 1L, 10));
f.deleted.put("tr", Long.valueOf(50L));
StoreMerge.reconcileDeletions(f);
check(f.find("tr") != null && f.deleted.isEmpty(),
"reconcile: restoring a deleted task clears its tombstone");
LedgerFile g = fileOf(1L, task("tr", "stale copy", 75L, 1L, 10));
g.deleted.put("tr", Long.valueOf(90L));
StoreMerge.reconcileDeletions(g);
check(g.find("tr") == null && g.deleted.containsKey("tr"),
"reconcile: newer tombstone removes the stale task");
StoreMerge.reconcileDeletions(g);
check(g.find("tr") == null && g.deleted.containsKey("tr"), "reconcile: idempotent");
LedgerFile h = LedgerFile.empty();
h.deleted.put("gone", Long.valueOf(5L));
StoreMerge.reconcileDeletions(h);
checkEq(h.deleted.get("gone"), Long.valueOf(5L), "reconcile: tombstone with no task stands untouched");
}
// ----------------------------------------------------------- wire shape
private static void testWireShape() {
// recur as the Mac's {"unit":...,"weekdays":[...]} payload (the real
// file has no recurring task, so exercise the encoder directly).
Task r = task("trec", "repeat me", 100L, 50L, 10);
r.recur = "onWeekdays";
r.recurWeekdays = new ArrayList<Integer>(Arrays.asList(Integer.valueOf(2), Integer.valueOf(4), Integer.valueOf(6)));
String rj = fileOf(1L, r).toJson();
check(rj.contains("\"recur\" : {") && rj.contains("\"unit\" : \"onWeekdays\"")
&& rj.contains("\"weekdays\" : ["), "wire: recur emitted as unit/weekdays payload");
LedgerFile rp = LedgerFile.parse(rj);
checkEq(rp.find("trec").recur, "onWeekdays", "wire: recur unit round trips");
checkEq(rp.find("trec").recurWeekdays, Arrays.asList(Integer.valueOf(2), Integer.valueOf(4), Integer.valueOf(6)),
"wire: recur weekdays round trip");
Task unsorted = task("tuns", "sorted on read", 1L, 1L, 1);
unsorted.recur = "onWeekdays";
unsorted.recurWeekdays = new ArrayList<Integer>(Arrays.asList(Integer.valueOf(6), Integer.valueOf(2)));
String uj = fileOf(1L, unsorted).toJson();
checkEq(LedgerFile.parse(uj).find("tuns").recurWeekdays,
Arrays.asList(Integer.valueOf(2), Integer.valueOf(6)), "wire: weekdays sorted like Recurrence.init");
Task weekly = task("twee", "weekly", 1L, 1L, 1);
weekly.recur = "weekly";
String wj = fileOf(1L, weekly).toJson();
check(wj.contains("\"weekdays\" : [\n\n") , "wire: weekly carries an empty weekdays array like Swift");
LedgerFile wp = LedgerFile.parse(wj);
checkEq(wp.find("twee").recur, "weekly", "wire: plain unit survives");
checkEq(wp.find("twee").recurWeekdays, new ArrayList<Integer>(), "wire: empty weekdays survives");
Task done = task("tdone", "finished", 300L, 200L, 10);
done.status = Task.DONE;
done.completedAt = Long.valueOf(123L);
done.dueMillis = Long.valueOf(456L);
done.timed = true;
String dj = fileOf(1L, done).toJson();
check(dj.contains("\"completedAt\" : \"1970-01-01T00:00:00.123Z\"")
&& dj.contains("\"due\" : \"1970-01-01T00:00:00.456Z\""), "wire: completedAt/due as ISO strings");
LedgerFile dp = LedgerFile.parse(dj);
checkEq(dp.find("tdone").completedAt, Long.valueOf(123L), "wire: completedAt round trips");
checkEq(dp.find("tdone").dueMillis, Long.valueOf(456L), "wire: due round trips");
check(dp.find("tdone").timed, "wire: timed flag round trips");
check(!dj.contains("\"recur\""), "wire: unset recur omitted like encodeIfPresent");
Task bare = task("tbare", "no optionals", 10L, 10L, 1);
String bj = fileOf(1L, bare).toJson();
check(!bj.contains("\"due\"") && !bj.contains("\"completedAt\""),
"wire: null due/completedAt omitted");
LedgerFile garbage = LedgerFile.parse("{ not json");
checkEq(garbage.tasks.size(), Integer.valueOf(0), "wire: garbage parses to empty file, never throws");
checkEq(garbage.version, Integer.valueOf(1), "wire: empty file keeps version 1");
check(LedgerFile.parse(null).tasks.isEmpty(), "wire: null parses to empty file");
check(LedgerFile.parse("[]").tasks.isEmpty(), "wire: wrong root type parses to empty file");
LedgerFile emptyOut = LedgerFile.empty();
check(emptyOut.toJson().contains("\"version\" : 1"), "wire: empty file serialises");
checkEq(LedgerFile.parse(emptyOut.toJson()).tasks.size(), Integer.valueOf(0), "wire: empty round trip");
}
// ------------------------------------------------------------ localstore
private static void testLocalStore() throws Exception {
File dir = new File(System.getProperty("java.io.tmpdir"), "taskdeck-selftest-" + System.nanoTime());
check(dir.mkdirs(), "store: temp dir created");
File storeFile = new File(dir, "taskdeck.json");
try {
LocalStore s1 = new LocalStore(storeFile);
check(s1.snapshot().tasks.isEmpty(), "store: missing file starts empty");
check(storeFile.equals(s1.file()), "store: file() points at the store file");
s1.mutate(addTask("talpha", "alpha", 100L, 1L, 10));
check(storeFile.exists(), "store: mutate wrote the file");
String content1 = readUtf8(storeFile);
check(content1.contains("\"alpha\"") && content1.contains("\"createdAt\""),
"store: file holds the wire format");
check(noTempSiblings(dir), "store: atomic write left no temp file behind");
checkEq(LedgerFile.parse(content1).find("talpha").updatedAt, 100L, "store: task round-trips from disk");
checkEq(s1.snapshot().find("talpha").title, "alpha", "store: snapshot reflects the mutation");
// External writer (second store = sync landing on disk):
LocalStore s2 = new LocalStore(storeFile);
s2.mutate(addTask("tbeta", "beta", 200L, 2L, 20));
storeFile.setLastModified(1000L); // mtime now LIES — only a content compare can reload
s1.mutate(addTask("tgamma", "gamma", 300L, 3L, 30));
LedgerFile snap = s1.snapshot();
check(snap.find("tbeta") != null, "store: reloads external change by content, not mtime");
check(snap.find("talpha") != null && snap.find("tgamma") != null,
"store: own tasks survive the reload-and-merge");
// Both writers edit the same task; newest stamp must win everywhere:
s2.mutate(rename("tbeta", "beta-v2", System.currentTimeMillis() + 10000L));
s1.mutate(rename("tbeta", "beta-v1", System.currentTimeMillis()));
s2.mutate(noop());
s1.mutate(noop());
checkEq(s1.snapshot().find("tbeta").title, "beta-v2",
"store: two writers converge on the newest stamp (s1 side)");
checkEq(s2.snapshot().find("tbeta").title, "beta-v2",
"store: two writers converge on the newest stamp (s2 side)");
// mutate stamps the envelope updatedAt
long beforeStamp = LedgerFile.parse(readUtf8(storeFile)).updatedAt;
Thread.sleep(5L);
s1.mutate(noop());
check(LedgerFile.parse(readUtf8(storeFile)).updatedAt > beforeStamp,
"store: every mutation restamps updatedAt");
// Corrupt file must be set aside, never clobbered:
String garbage = "{ this is not json, but it must not be lost";
writeUtf8(storeFile, garbage);
s1.mutate(addTask("tdelta", "delta", 400L, 4L, 40));
LedgerFile recovered = LedgerFile.parse(readUtf8(storeFile));
check(recovered.find("tdelta") != null && recovered.find("talpha") != null,
"store: keeps working over an unparseable file");
File[] backups = corruptBackups(dir);
checkEq(backups.length, 1, "store: unparseable bytes quarantined exactly once");
if (backups.length == 1) {
checkEq(readUtf8(backups[0]), garbage, "store: corrupt file set aside intact, not overwritten");
check(backups[0].getName().startsWith("taskdeck.corrupt-")
&& backups[0].getName().endsWith(".json"),
"store: quarantine name follows the Mac's <base>.corrupt-<iso>.json");
}
// replaceFrom: remote tombstone wins, local-only work survives
LedgerFile remote = LedgerFile.empty();
remote.updatedAt = System.currentTimeMillis();
remote.deleted.put("talpha", Long.valueOf(System.currentTimeMillis() + 100000L));
Task echo = task("techo", "from-remote", Long.valueOf(System.currentTimeMillis() + 50000L).longValue(), 5L, 50);
echo.notes = "echo of a Mac edit \u2014 \"quotes\" and \\ backslash";
remote.tasks.add(echo);
s1.replaceFrom(remote);
snap = s1.snapshot();
check(snap.find("talpha") == null, "store: replaceFrom honours a newer remote tombstone");
check(snap.find("techo") != null && snap.find("tbeta") != null,
"store: replaceFrom unions remote and local");
checkEq(LedgerFile.parse(readUtf8(storeFile)).find("techo").title, "from-remote",
"store: replaceFrom saved to disk");
// Restoring a deleted task through mutate must clear its tombstone
s1.mutate(addTask("talpha", "alpha-restored",
System.currentTimeMillis() + 200000L, 1L, 10));
snap = s1.snapshot();
checkEq(snap.find("talpha").title, "alpha-restored", "store: deleted task restored");
check(!snap.deleted.containsKey("talpha"), "store: restore clears the tombstone after the mutation");
// snapshot() hands out a detached copy
LedgerFile hand = s1.snapshot();
String firstId = hand.tasks.get(0).id;
hand.tasks.get(0).title = "mutated-through-hand";
check(!"mutated-through-hand".equals(s1.snapshot().find(firstId).title),
"store: snapshot() is detached from internal state");
// A brand-new store on the same file sees everything (fresh reload)
LocalStore s3 = new LocalStore(storeFile);
checkEq(s3.snapshot().tasks.size(), s1.snapshot().tasks.size(),
"store: reopened store matches the live one");
check(s3.lastError() == null, "store: clean reopened store reports no error");
// replaceFrom after an external edit merges both sides
s2.mutate(addTask("textnl", "external-line",
System.currentTimeMillis() + 300000L, 6L, 60));
s1.replaceFrom(LedgerFile.empty());
check(s1.snapshot().find("textnl") != null,
"store: replaceFrom also folds in intervening disk changes");
} finally {
deleteRecursively(dir);
}
}
// --------------------------------------------------------- real Mac file
/** The live store moves; only prove it still parses and is stable. */
private static void smokeTestLiveStore(File live) throws Exception {
if (!live.isFile()) { check(true, "live: no store at " + live + " (skipped)"); return; }
String text = readUtf8(live);
LedgerFile f = LedgerFile.parse(text);
check(f.tasks.size() > 0, "live: parses with " + f.tasks.size() + " tasks");
check(LedgerFile.parse(f.toJson()).toJson().equals(f.toJson()),
"live: parse -> emit is stable");
for (Task t : f.tasks) {
if (t.id == null || t.id.length() == 0 || t.updatedAt <= 0) {
check(false, "live: task " + t.id + " is malformed");
return;
}
}
check(true, "live: every task has an id and a real updatedAt");
}
private static void testRealMacFile(File macFile) throws Exception {
check(macFile.isFile(), "mac: found the real store at " + macFile);
String text = readUtf8(macFile);
LedgerFile f = LedgerFile.parse(text);
checkEq(f.version, Integer.valueOf(1), "mac: version 1");
// The live store grows as the user files things, so this suite must
// derive its expectations from the file rather than hard-code a count.
int n = f.tasks.size();
check(n > 0, "mac: parsed a non-empty live store (" + n + " tasks)");
// The envelope is stamped at save time, so it must never predate a task.
long newest = 0L;
for (Task t : f.tasks) newest = Math.max(newest, t.updatedAt);
check(f.updatedAt >= newest, "mac: envelope updatedAt is not older than any task");
check(newest > 0L, "mac: every task carries a real updatedAt");
check(f.deleted.isEmpty(), "mac: empty deleted parsed");
// The whole point: re-emit the Mac's file and get it back byte for byte.
String out = f.toJson();
if (out.equals(text)) {
check(true, "mac: parse -> toJson reproduces tasks.json BYTE-FOR-BYTE");
} else {
reportFirstDiff(out, text);
check(false, "mac: parse -> toJson reproduces tasks.json BYTE-FOR-BYTE");
}
checkEq(out.length(), Integer.valueOf(text.length()), "mac: re-emitted length matches");
// Stable across another parse cycle (what sync will do repeatedly).
String out2 = LedgerFile.parse(out).toJson();
check(out2.equals(out), "mac: parse -> emit -> parse -> emit is stable");
// Merge must not disturb anything either (raw log ids ride along).
LedgerFile merged = StoreMerge.merge(f, LedgerFile.empty());
checkEq(merged.tasks.size(), Integer.valueOf(n), "mac: merge with an empty file keeps all tasks");
String mout = merged.toJson();
check(mout.equals(out), "mac: merge(empty) re-emit still byte-identical");
// Value-level deep equality against the raw document, task by task.
Map<?,?> origRoot = (Map<?,?>) Json.parse(text);
Map<?,?> reRoot = (Map<?,?>) Json.parse(out);
checkEq(reRoot.keySet(), origRoot.keySet(), "mac: top-level key set preserved");
List<?> origTasks = (List<?>) origRoot.get("tasks");
List<?> reTasks = (List<?>) reRoot.get("tasks");
checkEq(reTasks.size(), origTasks.size(), "mac: task count re-emitted");
for (int i = 0; i < origTasks.size(); i++) {
Map<?,?> o = (Map<?,?>) origTasks.get(i);
Map<?,?> r = (Map<?,?>) reTasks.get(i);
checkEq(r.keySet(), o.keySet(), "mac: task[" + i + "] field set intact (no loss, no invention)");
check(o.equals(r), "mac: task[" + i + "] " + o.get("id") + " deep-equal after re-emit");
}
// Field-by-field, the values that matter, from the model side.
for (int i = 0; i < origTasks.size(); i++) {
Map<?,?> o = (Map<?,?>) origTasks.get(i);
Task t = f.tasks.get(i);
String why = fieldDiff(o, t, i);
check(why == null, "mac: task " + o.get("id") + " title/tags/due/recur/log fields"
+ (why == null ? "" : " — " + why));
}
// Named spot checks against the synthetic fixture. The fixture is
// checked in (testdata/mac-store-fixture.json); these pin the edge
// cases the round-trip must preserve: log UUIDs, \\/ escaping, quotes.
Task trip = f.find("m3n4o5");
check(trip != null, "mac: task m3n4o5 present");
checkEq(trip.title, "Plan weekend trip", "mac: spot title");
checkEq(trip.priority, "urgent", "mac: spot priority");
checkEq(trip.log.size(), Integer.valueOf(1), "mac: the one log entry parsed");
checkEq(trip.log.get(0).author, "user", "mac: log author");
check(trip.log.get(0).text.contains("leave Saturday morning"), "mac: log text intact");
checkEq(Long.valueOf(trip.log.get(0).at), Json.parseIso8601("2026-03-01T10:30:00.250Z"),
"mac: log time parsed to millis");
// Pinned to a value the user can legitimately change; assert sanity instead.
check(trip.updatedAt > 1577836800000L, "mac: task updatedAt parsed to a real instant");
checkEq(Long.valueOf(trip.createdAt), Json.parseIso8601("2026-03-01T09:20:00.000Z"), "mac: task createdAt");
Map<?,?> rawTrip = (Map<?,?>) origTasks.get(indexOf(origTasks, "m3n4o5"));
Map<?,?> rawTripLog = (Map<?,?>) ((List<?>) rawTrip.get("log")).get(0);
checkEq(rawTripLog.get("id"), "11111111-2222-3333-4444-555555555555", "mac: raw log UUID in source");
Map<?,?> reTrip = (Map<?,?>) reTasks.get(indexOf(reTasks, "m3n4o5"));
Map<?,?> reTripLog = (Map<?,?>) ((List<?>) reTrip.get("log")).get(0);
checkEq(reTripLog.get("id"), "11111111-2222-3333-4444-555555555555",
"mac: log UUID preserved through parse/emit — the Mac's decoder requires it");
Task milk = f.find("a1b2c3");
checkEq(milk.tags, Arrays.asList("groceries"), "mac: tags list");
check(milk.notes.contains("corner store / dairy"), "mac: \\/ decoded to / on read");
check(out.contains("corner store \\/ dairy"), "mac: re-emitted as \\/ exactly like the Mac's file");
checkEq(f.find("d4e5f6").priority, "high", "mac: high priority");
checkEq(f.find("d4e5f6").order, Integer.valueOf(5), "mac: order integer");
// Optional keys must stay null when absent. Asserted across every task so
// it cannot break when the user completes or dates one of them.
for (Task t : f.tasks) {
check(t.completedAt == null || Task.DONE.equals(t.status),
"mac: only done tasks carry completedAt");
check(t.dueMillis == null || t.dueMillis > 1577836800000L,
"mac: due is null or a real instant");
check(t.createdAt > 0 && t.updatedAt > 0, "mac: both stamps populated");
}
check(f.find("j0k1l2") != null, "mac: a known seeded task is still addressable");
checkEq(f.find("g7h8i9").title, "Read \"The Design of Everyday Things\" chapter 3",
"mac: title with straight quotes inside");
// Store round trip on the real data: the app opening the Mac's file
// must be able to save it back untouched.
File dir = new File(System.getProperty("java.io.tmpdir"), "taskdeck-realcop-" + System.nanoTime());
dir.mkdirs();
try {
File copy = new File(dir, "tasks.json");
writeUtf8(copy, text);
LocalStore store = new LocalStore(copy);
checkEq(store.snapshot().tasks.size(), Integer.valueOf(n), "mac: store opened the real file");
store.mutate(noop());
String after = readUtf8(copy);
Map<?,?> afterRoot = (Map<?,?>) Json.parse(after);
checkEq(((List<?>) afterRoot.get("tasks")).size(), Integer.valueOf(n),
"mac: store round trip keeps every task");
checkEq(taskIds(afterRoot), taskIds(origRoot), "mac: store round trip keeps ids and order");
check(after.contains("11111111-2222-3333-4444-555555555555"),
"mac: store round trip preserves log UUID");
// every title survives individually
List<?> afterTasks = (List<?>) afterRoot.get("tasks");
boolean titlesOk = afterTasks.size() == origTasks.size();
for (int i = 0; titlesOk && i < afterTasks.size(); i++) {
titlesOk = ((Map<?, ?>) afterTasks.get(i)).get("title")
.equals(((Map<?, ?>) origTasks.get(i)).get("title"));
}
check(titlesOk, "mac: every task title intact after store round trip");
} finally {
deleteRecursively(dir);
}
}
/** Returns null when the model and the raw wire entry agree on everything. */
private static String fieldDiff(Map<?,?> wire, Task t, int i) {
if (!eq(t.id, wire.get("id"))) return "id";
if (!eq(t.title, wire.get("title"))) return "title";
if (!eq(t.notes, wire.get("notes"))) return "notes";
if (!eq(t.status, wire.get("status"))) return "status";
if (!eq(t.priority, wire.get("priority"))) return "priority";
if (!eq(t.source, wire.get("source"))) return "source";
if (!eq(Long.valueOf(t.order), wire.get("order"))) return "order";
if (!eq(Boolean.valueOf(t.timed), wire.get("timed"))) return "timed";
if (!eq(Long.valueOf(t.createdAt), Json.parseIso8601((String) wire.get("createdAt")))) return "createdAt";
if (!eq(Long.valueOf(t.updatedAt), Json.parseIso8601((String) wire.get("updatedAt")))) return "updatedAt";
if (!eq(t.dueMillis, millisOrNullW(wire.get("due")))) return "due";
if (!eq(t.completedAt, millisOrNullW(wire.get("completedAt")))) return "completedAt";
if (!eq(t.tags, wire.get("tags"))) return "tags";
Object rw = wire.get("recur");
if (rw != null) {
if (t.recur == null || !eq(t.recur, ((Map<?, ?>) rw).get("unit"))) return "recur.unit";
List<?> wd = (List<?>) ((Map<?, ?>) rw).get("weekdays");
if (t.recurWeekdays == null || t.recurWeekdays.size() != wd.size()) return "recur.weekdays";
} else if (t.recur != null) {
return "recur";
}
List<?> log = (List<?>) wire.get("log");
if (t.log.size() != log.size()) return "log.size";
for (int k = 0; k < log.size(); k++) {
Map<?,?> e = (Map<?,?>) log.get(k);
Task.Log te = t.log.get(k);
if (te.at != Json.parseIso8601((String) e.get("at"))) return "log.at";
if (!eq(te.author, e.get("author"))) return "log.author";
if (!eq(te.text, e.get("text"))) return "log.text";
}
return null;
}
private static Object millisOrNullW(Object o) {
if (o == null) return null;
return Long.valueOf(Json.parseIso8601((String) o));
}
private static boolean eq(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
// ------------------------------------------------------------- plumbing
private static void check(boolean ok, String label) {
if (ok) {
passed++;
System.out.println("PASS " + label);
} else {
failed++;
System.out.println("FAIL " + label);
}
}
private static void checkEq(Object actual, Object expected, String label) {
boolean ok = eq(actual, expected);
if (ok) {
passed++;
System.out.println("PASS " + label);
} else {
failed++;
System.out.println("FAIL " + label + " — expected <" + expected + "> got <" + actual + ">");
}
}
private static void checkThrowsJson(String s, String label) {
boolean threw = false;
try {
Json.parse(s);
} catch (IllegalArgumentException e) {
threw = true;
}
check(threw, label);
}
private static void checkThrowsIso(String s, String label) {
boolean threw = false;
try {
Json.parseIso8601(s);
} catch (IllegalArgumentException e) {
threw = true;
}
check(threw, label);
}
private static void reportFirstDiff(String actual, String expected) {
int n = Math.min(actual.length(), expected.length());
int i = 0;
while (i < n && actual.charAt(i) == expected.charAt(i)) i++;
System.out.println(" first difference at index " + i
+ (i == n ? " (length only)" : "")
+ "; ours=[" + snippet(actual, i) + "] theirs=[" + snippet(expected, i) + "]");
}
private static String snippet(String s, int from) {
StringBuilder sb = new StringBuilder();
for (int k = Math.max(0, from - 10); k < Math.min(s.length(), from + 30); k++) {
char c = s.charAt(k);
if (c == '\n') sb.append("\\n");
else if (c == '\r') sb.append("\\r");
else if (c == '\t') sb.append("\\t");
else if (c < 0x20) sb.append(String.valueOf((char) ('?')));
else sb.append(c);
}
return sb.toString();
}
private static Task task(String id, String title, long updatedAt, long createdAt, int order) {
Task t = new Task();
t.id = id;
t.title = title;
t.updatedAt = updatedAt;
t.createdAt = createdAt;
t.order = order;
return t;
}
private static LedgerFile fileOf(long updatedAt, Task... ts) {
LedgerFile f = LedgerFile.empty();
f.updatedAt = Long.valueOf(updatedAt).longValue();
f.tasks.addAll(Arrays.asList(ts));
return f;
}
private static String idSequence(LedgerFile f) {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < f.tasks.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(f.tasks.get(i).id);
}
return sb.append(']').toString();
}
private static List<String> taskIds(Map<?,?> root) {
List<String> ids = new ArrayList<String>();
for (Object o : (List<?>) root.get("tasks")) ids.add((String) ((Map<?, ?>) o).get("id"));
return ids;
}
private static int indexOf(List<?> tasks, String id) {
for (int i = 0; i < tasks.size(); i++) {
if (id.equals(((Map<?, ?>) tasks.get(i)).get("id"))) return i;
}
return -1;
}
private static LocalStore.Mutation addTask(final String id, final String title,
final long updatedAt, final long createdAt, final int order) {
return new LocalStore.Mutation() {
@Override
public void apply(LedgerFile f) {
f.tasks.add(task(id, title, updatedAt, createdAt, order));
}
};
}
private static LocalStore.Mutation rename(final String id, final String title, final long stamp) {
return new LocalStore.Mutation() {
@Override
public void apply(LedgerFile f) {
Task t = f.find(id);
if (t != null) {
t.title = title;
t.updatedAt = stamp;
}
}
};
}
private static LocalStore.Mutation noop() {
return new LocalStore.Mutation() {
@Override
public void apply(LedgerFile f) {
}
};
}
private static boolean noTempSiblings(File dir) {
String[] names = dir.list();
if (names == null) return false;
for (int i = 0; i < names.length; i++) {
if (names[i].contains(".tmp-")) return false;
}
return true;
}
private static File[] corruptBackups(File dir) {
final File[] none = new File[0];
File[] all = dir.listFiles();
if (all == null) return none;
List<File> out = new ArrayList<File>();
for (int i = 0; i < all.length; i++) {
if (all[i].getName().contains(".corrupt-")) out.add(all[i]);
}
return out.toArray(new File[out.size()]);
}
private static String readUtf8(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(64, (int) file.length()));
byte[] buf = new byte[8192];
int r;
while ((r = in.read(buf)) > 0) bos.write(buf, 0, r);
return new String(bos.toByteArray(), "UTF-8");
} finally {
in.close();
}
}
private static void writeUtf8(File file, String text) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(text.getBytes("UTF-8"));
} finally {
out.close();
}
}
private static void deleteRecursively(File f) {
if (f.isDirectory()) {
File[] kids = f.listFiles();
if (kids != null) {
for (int i = 0; i < kids.length; i++) deleteRecursively(kids[i]);
}
}
f.delete();
}
}