File size: 40,865 Bytes
41dfd8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""COMPUTATION module — FastTimes (intermittent-fasting tracker).

CORE FUNCTION here is the fasting TIMER and the derived AGGREGATES. This app has
no calculator; its "input -> output" surface is:

  * a goal cell tapped -> a live timer that either COUNTS DOWN ("Remaining",
    timed goal) or COUNTS UP ("Elapsed Time", Open Fast); the timer VALUE is a
    computed HH:MM:SS that changes over time.
  * a timed goal -> a computed "Started" and "End Time" pair, End = Start + goal
    duration (Test 1 Hour: End = Start + 1h; Test Timer 10s: Started == End).
  * a timed goal reaching its target -> the value MODE flips: "Remaining"
    -> "Total Time", the goal name -> "Goal Reached!", and the value then counts
    UP; the "End Time" label -> "Goal".
  * saving completed fasts -> integer AGGREGATES: the Dashboard "Fasts" count
    (0 -> 1 -> 2), the Statistics "Total Fasts" ("1"/completed) and "Consistency"
    ("100%"/goals met when the goal was met), the History "August Summary"
    "Total Fasts", and a duration formatted \\d+h \\d+m.

Every asserted number/relationship was OBSERVED on the running original (see the
module docstring values above), never read from source or computed by hand. Wall-
clock-dependent values are asserted as RELATIONSHIPS (decreasing / increasing /
+1h offset / count deltas) and PATTERNS, with tolerance — the debug Test Timer's
~10s initial remaining is the only near-literal, and it carries a wide tolerance.

CEDES to sibling lanes: whether a screen is reachable -> navigation; a control's
checked/selected/enabled bit -> states; the mere EXISTENCE of a saved record (as
opposed to its numeric aggregate) -> interaction; a non-computed content string
-> text; the view-tree shape / drawn arcs -> structure (but the arc/chart that
ENCODES a value visually is a legitimate VLM here).

VLM budget for this lane = 4 (a value made visual, unreadable from the dump): the
active-fast circular progress RING (partially filled proportional to elapsed), the
FULL green ring at goal-reached, the statistics BAR CHART (bars of differing
heights), and the statistics stat-card cluster showing the computed numbers.

Compose renders as android.view.View / TextView with NO resource-ids, so every
target and read-back key is a visible text / content-desc / bounds-located node.

SAFETY: never taps "Delete" / "Delete Fast"; every exploratory tap is safe.

Run:  python3 test_android_computation.py <PACKAGE> <RESULTS_DIR>
"""
import os
import re
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,E402

require_kit(1)

RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR  # noqa: F405

_HMS = re.compile(r"^\d{1,2}:\d{2}:\d{2}$")          # HH:MM:SS timer value
_DUR = re.compile(r"\b(\d+)h\s+(\d+)m\b")            # "0h 2m" duration
_CLOCK = re.compile(r"(\d{1,2}):(\d{2})\s*([AP]M)", re.I)   # "3:41 PM"


# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
def _main_component():
    out = adb_shell("cmd", "package", "query-activities", "--brief",
                    "-a", "android.intent.action.MAIN",
                    "-c", "android.intent.category.LAUNCHER")
    cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
    good = [c for c in cands if "leakcanary" not in c.lower()]
    return (good or cands or [""])[0]


def open_main():
    """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
    force_stop()
    comp = _main_component()
    if comp:
        adb_shell("am", "start", "-n", comp)
    else:
        launch_app()
    settle("launch")
    wait_for_foreground()
    if "leakcanary" in get_current_activity().lower() and comp:
        adb_shell("am", "start", "-n", comp)
        settle("launch")


def open_main_clear():
    """Virgin state: wipe data (no active fast, empty history), then open Main."""
    clear_data()
    open_main()


# ── Domain helpers ───────────────────────────────────────────────────────────
def _dismiss_notif_rationale():
    """The first-run "Notification Preferences" rationale appears on the first goal
    tap after clear_data(). Dismiss it non-destructively (choice is irrelevant to
    the computations under test). Returns True if it was shown."""
    nodes = ui()
    if not find_node(nodes, text="Notification Preferences"):
        return False
    for label in ("No Notifications", "Skip", "Not Now", "Enable Notifications"):
        n = find_node(nodes, text=label)
        if n and is_safe(n):
            tap_node(n)
            settle("tap")
            return True
    return False


def _on_dashboard(nodes=None):
    nodes = ui() if nodes is None else nodes
    return find_node(nodes, text="Set your goal") is not None


def _start_goal(cell_text):
    """From a CLEAN dashboard, tap a goal cell by name and land on the ACTIVE-FAST
    card (desc='End Fast'). Handles the first-run notification rationale. Returns
    True on success."""
    cell = find_node(ui(), text=cell_text)
    if not cell:
        return False
    tap_node(cell)
    settle("tap")
    _dismiss_notif_rationale()
    if find_node(ui(), content_desc="End Fast"):
        return True
    cell = find_node(ui(), text=cell_text)      # rationale may have eaten the tap
    if cell:
        tap_node(cell)
        settle("tap")
        _dismiss_notif_rationale()
    return find_node(ui(), content_desc="End Fast") is not None


def _timer_value(nodes=None):
    """The active-fast card's live HH:MM:SS value (a TextView matching ^\\d\\d:..).
    Returns the string, or None. There is exactly one such node on the card."""
    nodes = ui() if nodes is None else nodes
    for n in nodes:
        t = n.get("text", "").strip()
        if _HMS.match(t):
            return t
    return None


def _hms_to_secs(t):
    try:
        h, m, s = (int(x) for x in t.split(":"))
        return h * 3600 + m * 60 + s
    except Exception:
        return None


def _card_label(nodes=None):
    """Which mode-label is showing on the active-fast card: 'Remaining' /
    'Elapsed Time' / 'Total Time'. Returns the first found, else ''."""
    nodes = ui() if nodes is None else nodes
    for lbl in ("Remaining", "Elapsed Time", "Total Time"):
        if find_node(nodes, text=lbl):
            return lbl
    return ""


def _value_under_label(nodes, label_text, want, max_dy=170):
    """Read the stat VALUE that sits directly BELOW a card label and is x-aligned
    with it (the FastTimes stat-card pattern: label / big-value / subtitle). `want`
    is a predicate on the candidate text. Returns the matching text or None.

    Used for the Dashboard 'Fasts' count and the Statistics/History 'Total Fasts'
    and 'Consistency' cards, whose numbers have no id and no distinct text anchor —
    only their position under the label identifies them."""
    lbl = find_node(nodes, text=label_text)
    if not lbl or "_bounds" not in lbl:
        return None
    lx = lbl["_center"][0]
    ly2 = lbl["_bounds"][3]
    best = None
    for n in nodes:
        t = n.get("text", "").strip()
        b = n.get("_bounds")
        if not b or not t or not want(t):
            continue
        if b[1] >= ly2 and (b[1] - ly2) < max_dy and abs(n["_center"][0] - lx) < 150:
            if best is None or b[1] < best[1]:
                best = (t, b[1])
    return best[0] if best else None


def _fasts_count(nodes=None):
    """The integer under the Dashboard 'Fasts' stat blob. Returns int or None."""
    nodes = ui() if nodes is None else nodes
    v = _value_under_label(nodes, "Fasts", lambda t: t.isdigit())
    return int(v) if v is not None else None


def _wait_goal_reached(polls=18):
    """Poll until the Test Timer flips to 'Goal Reached!' (~10s). Bounded so a slow
    emulator never hangs. Returns whether it flipped."""
    for _ in range(polls):
        if find_node(ui(), text="Goal Reached!"):
            return True
        settle("tap")
    return False


def _modal_star_views():
    """The 5 clickable rating-star Views in the 'Fast Complete!' summary modal:
    empty-text clickable android.view.View nodes in one horizontal row. x-sorted."""
    nodes = ui()
    clk = [n for n in nodes
           if n.get("class", "").endswith("view.View")
           and n.get("clickable") == "true"
           and not n.get("text", "").strip()
           and not n.get("content-desc", "").strip()
           and "_bounds" in n]
    stars = []
    for n in clk:
        x1, y1, x2, y2 = n["_bounds"]
        w, h = x2 - x1, y2 - y1
        if w < 40 or h < 40:
            continue
        if 0.6 <= w / h <= 1.7:
            stars.append(n)
    if len(stars) < 5:
        return []
    stars.sort(key=lambda n: n["_center"][1])
    rows, cur = [], [stars[0]]
    for n in stars[1:]:
        if abs(n["_center"][1] - cur[-1]["_center"][1]) <= 30:
            cur.append(n)
        else:
            rows.append(cur)
            cur = [n]
    rows.append(cur)
    row = max(rows, key=len)
    row.sort(key=lambda n: n["_center"][0])
    return row


def save_test_timer_fast():
    """Complete + SAVE one Test Timer fast from a clean dashboard (rating 4 stars),
    landing back on the Dashboard with the fast persisted. Returns True on success.
    This produces a GOAL-MET completed fast, which is what makes Consistency 100%."""
    if not _start_goal("Test Timer"):
        return False
    _wait_goal_reached()
    ef = find_node(ui(), content_desc="End Fast")
    if not ef:
        return False
    tap_node(ef)
    settle("tap")
    stars = _modal_star_views()
    if len(stars) >= 4:
        tap_node(stars[3])                    # 4th star
        settle("tap")
    save = find_node(ui(), text="Save")
    if not save or not tap_node(save):
        return False
    settle("tap")
    return _on_dashboard()


def _end_active_no_save():
    """Tap End Fast then BACK out of the summary WITHOUT saving (keeps history
    clean). Best-effort cleanup only."""
    ef = find_node(ui(), content_desc="End Fast")
    if ef:
        tap_node(ef)
        settle("tap")
        back()
        settle("tap")


# ── Named depth helpers (the and_reach_* NAME backs a depth>=1 claim; each body is
# a real, PROVEN surface jump — target appeared, source vanished). ──────────────
def and_reach_statistics():
    """Dashboard -> Statistics ('Performance'). Proven: 'Trends' appears, the goal
    card 'Set your goal' vanishes. Counts one surface (jump_kind='reach')."""
    n = find_node(ui(), content_desc="Go to Statistics")
    if not n:
        return False
    return and_reach_surface(n, "Trends", "Set your goal")


def and_reach_history():
    """Dashboard -> History pane. Proven: 'August 2026' appears, 'Set your goal'
    vanishes. Counts one surface."""
    n = find_node(ui(), content_desc="Go to History")
    if not n:
        return False
    return and_reach_surface(n, "August 2026", "Set your goal")


# ═══════════════════════════════════════════════════════════════════════════════
# (1) COUNTDOWN — a timed goal's "Remaining" value DECREASES over time
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_countdown_decreases",))
def test_countdown_decreases():
    """Start 'Test 1 Hour' (a 1h timed goal): the card shows label 'Remaining' and a
    HH:MM:SS value that COUNTS DOWN. Read it twice ~3s apart and assert the second
    is strictly LESS than the first (and the initial value is just under 01:00:00,
    proving it started from the goal and is decrementing). The 1h window is used
    (not the 10s Test Timer) so the read is not racing the goal-reached flip."""
    open_main_clear()
    started = _start_goal("Test 1 Hour")
    if not started:
        record("computation_countdown_decreases", False,
               "feature_missing: could not start the 'Test 1 Hour' timed goal "
               "('End Fast' card not shown)",
               depth=0, jump_kind="value",
               expect="Remaining value decreases over ~3s (e.g. 00:59:57 -> 00:59:54)")
        return
    n1 = ui()
    label = _card_label(n1)
    v1 = _timer_value(n1)
    time.sleep(3)
    v2 = _timer_value(ui())
    s1 = _hms_to_secs(v1) if v1 else None
    s2 = _hms_to_secs(v2) if v2 else None
    # initial remaining is just under the 1h goal (allow slack for start latency)
    fresh_ok = s1 is not None and 3480 <= s1 <= 3600      # 58:00 .. 60:00
    decreased = s1 is not None and s2 is not None and s2 < s1
    ok = (label == "Remaining") and fresh_ok and decreased
    record("computation_countdown_decreases", bool(ok),
           "" if ok else (f"behavior_wrong: label={label!r} remaining did not count "
                          f"down (v1={v1!r} -> v2={v2!r}); expected label 'Remaining' "
                          f"and a strictly decreasing HH:MM:SS near 01:00:00"),
           depth=0, jump_kind="value",
           expect=f"label 'Remaining'; value decreases over ~3s (saw {v1} -> {v2})")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (2) COUNT-UP — Open Fast's "Elapsed Time" value INCREASES over time
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_countup_increases",))
def test_countup_increases():
    """Start 'Open Fast' (infinite goal): the card shows label 'Elapsed Time' and a
    HH:MM:SS value that COUNTS UP, and there is NO 'End Time' line. Read the value
    twice ~3s apart and assert the second is strictly GREATER than the first."""
    open_main_clear()
    started = _start_goal("Open Fast")
    if not started:
        record("computation_countup_increases", False,
               "feature_missing: could not start 'Open Fast' ('End Fast' card not "
               "shown)",
               depth=0, jump_kind="value",
               expect="Elapsed Time value increases over ~3s (e.g. 00:00:03 -> "
                      "00:00:06)")
        return
    n1 = ui()
    label = _card_label(n1)
    no_end_time = find_node(n1, text="End Time") is None      # Open Fast has none
    v1 = _timer_value(n1)
    time.sleep(3)
    v2 = _timer_value(ui())
    s1 = _hms_to_secs(v1) if v1 else None
    s2 = _hms_to_secs(v2) if v2 else None
    increased = s1 is not None and s2 is not None and s2 > s1
    ok = (label == "Elapsed Time") and no_end_time and increased
    record("computation_countup_increases", bool(ok),
           "" if ok else (f"behavior_wrong: label={label!r} elapsed did not count up "
                          f"(v1={v1!r} -> v2={v2!r}) / an 'End Time' line was present "
                          f"({not no_end_time}); expected 'Elapsed Time' counting up "
                          f"with no End Time"),
           depth=0, jump_kind="value",
           expect=f"label 'Elapsed Time', no End Time; value increases over ~3s "
                  f"(saw {v1} -> {v2})")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (3) FRESH TEST TIMER — initial 'Remaining' is ~10s (> 0 and <= 00:00:10)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_test_timer_initial_10s",
                   "computation_test_timer_initial_10s_vlm"))
def test_test_timer_initial_remaining():
    """The debug 'Test Timer' goal is 10 seconds: immediately after starting it the
    'Remaining' value must be > 0 and <= ~10s (allow a small +slack for start
    latency, cap at 13s). This pins the debug constant WITH tolerance rather than a
    hard literal. The partially-filled progress RING (a value made visual) is the
    paired VLM."""
    open_main_clear()
    started = _start_goal("Test Timer")
    if not started:
        record("computation_test_timer_initial_10s", False,
               "feature_missing: could not start 'Test Timer' ('End Fast' card not "
               "shown)",
               depth=0, jump_kind="value",
               expect="initial Remaining > 0 and <= ~00:00:10")
        vlm_assert("computation_test_timer_initial_10s",
                   "Is a large timer value shown in the centre with a coloured "
                   "circular progress ring or arc drawn around it? Answer YES or NO.",
                   RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
        return
    n1 = ui()
    label = _card_label(n1)
    v1 = _timer_value(n1)
    s1 = _hms_to_secs(v1) if v1 else None
    ok = (label in ("Remaining", "Total Time")) and s1 is not None and 0 < s1 <= 13
    record("computation_test_timer_initial_10s", bool(ok),
           "" if ok else (f"behavior_wrong: fresh Test Timer remaining={v1!r} "
                          f"(label={label!r}); expected a value > 0 and <= ~10s "
                          f"(cap 13s)"),
           depth=0, jump_kind="value",
           expect=f"fresh Test Timer 'Remaining' > 0 and <= ~00:00:10 (saw {v1})")
    # VLM (value-made-visual): a partially filled ring encodes the elapsed fraction.
    vlm_assert("computation_test_timer_initial_10s",
               "Is a large timer value (like 00:00:10) shown in the centre of the "
               "card with a coloured circular progress ring or arc drawn around it? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (4) GOAL-REACHED TRANSITION — 'Remaining' -> 'Total Time' + 'Goal Reached!',
#     then the value counts UP (the VALUE MODE flips)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_goal_reached_transition",
                   "computation_goal_reached_transition_vlm"))
def test_goal_reached_transition():
    """Start Test Timer with label 'Remaining' (counting down); after ~10s the value
    MODE flips: the goal name becomes 'Goal Reached!', the label becomes 'Total
    Time', and the value then COUNTS UP from the goal. Assert the before ('Remaining'
    present, 'Goal Reached!'/'Total Time' absent) -> after ('Goal Reached!' +
    'Total Time' present) transition AND that the post-goal value increases. The
    FULL green ring at goal-reached is the paired VLM."""
    open_main_clear()
    started = _start_goal("Test Timer")
    if not started:
        record("computation_goal_reached_transition", False,
               "feature_missing: could not start 'Test Timer'",
               depth=0, jump_kind="transition",
               expect="'Remaining' -> 'Total Time' + 'Goal Reached!'; then value "
                      "counts up")
        vlm_assert("computation_goal_reached_transition",
                   "Is a fully-closed bright green circular ring drawn around the "
                   "timer (indicating the fasting goal was reached)? Answer YES or NO.",
                   RESULTS_DIR, tag="color", depth=0, jump_kind="transition")
        return
    before = ui()
    remaining_before = (_card_label(before) == "Remaining"
                        and find_node(before, text="Goal Reached!") is None
                        and find_node(before, text="Total Time") is None)
    flipped = _wait_goal_reached()
    after = ui()
    reached = (flipped
               and find_node(after, text="Goal Reached!") is not None
               and find_node(after, text="Total Time") is not None)
    # after reaching, the value counts UP
    v1 = _timer_value(after)
    time.sleep(3)
    v2 = _timer_value(ui())
    s1 = _hms_to_secs(v1) if v1 else None
    s2 = _hms_to_secs(v2) if v2 else None
    counts_up = s1 is not None and s2 is not None and s2 > s1
    ok = remaining_before and reached and counts_up
    record("computation_goal_reached_transition", bool(ok),
           "" if ok else ("behavior_wrong: the Test Timer did not flip 'Remaining' "
                          "-> 'Total Time'/'Goal Reached!'" if not reached
                          else f"behavior_wrong: after goal-reached the value did not "
                               f"count up (v1={v1!r} -> v2={v2!r})"),
           depth=0, jump_kind="transition",
           expect=f"label 'Remaining' -> 'Total Time' + 'Goal Reached!' shown; then "
                  f"value counts up (saw {v1} -> {v2})")
    # VLM (value-made-visual): the ring is fully closed & green once the goal is met.
    vlm_assert("computation_goal_reached_transition",
               "Is a fully-closed bright green circular ring drawn all the way around "
               "the timer (indicating the fasting goal was reached), rather than a "
               "partially-filled arc? Answer YES or NO.",
               RESULTS_DIR, tag="color", depth=0, jump_kind="transition")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (5) START / END TIME — both render; End >= Start; Test 1 Hour End = Start + 1h
# ═══════════════════════════════════════════════════════════════════════════════

def _clock_minutes(nodes, label_text):
    """Read the 'Today, H:MM PM' timestamp under a card label ('Started'/'End Time')
    and return minutes-since-midnight (0..1439), or None. Parses the first
    H:MM AM/PM in the value node directly below the label."""
    val = _value_under_label(nodes, label_text, lambda t: _CLOCK.search(t) is not None)
    if not val:
        return None
    m = _CLOCK.search(val)
    if not m:
        return None
    h, mm, ap = int(m.group(1)), int(m.group(2)), m.group(3).upper()
    h = h % 12
    if ap == "PM":
        h += 12
    return h * 60 + mm


@and_test(expects=("computation_end_time_offset",))
def test_start_end_time_offset():
    """A TIMED goal computes 'Started' and 'End Time' = Started + goal duration.
    Start 'Test 1 Hour': assert BOTH timestamps render and End = Start + 60 min
    (a real computed offset, ±2 min for the read/rollover), handling the midnight
    wrap. This is the app's most concrete arithmetic on user-visible values."""
    open_main_clear()
    started = _start_goal("Test 1 Hour")
    if not started:
        record("computation_end_time_offset", False,
               "feature_missing: could not start 'Test 1 Hour'",
               depth=0, jump_kind="value",
               expect="End Time = Started + 60 min (both render)")
        return
    nodes = ui()
    both_render = (find_node(nodes, text="Started") is not None
                   and find_node(nodes, text="End Time") is not None)
    start_min = _clock_minutes(nodes, "Started")
    end_min = _clock_minutes(nodes, "End Time")
    diff = None
    if start_min is not None and end_min is not None:
        diff = (end_min - start_min) % (24 * 60)          # wrap past midnight
    offset_ok = diff is not None and abs(diff - 60) <= 2
    ok = both_render and offset_ok
    record("computation_end_time_offset", bool(ok),
           "" if ok else (f"behavior_wrong: Test 1 Hour End Time was not Start + 60m "
                          f"(start_min={start_min}, end_min={end_min}, diff={diff}); "
                          f"both_render={both_render}"),
           depth=0, jump_kind="value",
           expect=f"End Time = Started + 60 min (observed diff {diff} min)")
    _end_active_no_save()


@and_test(expects=("computation_test_timer_start_eq_end",))
def test_test_timer_start_equals_end():
    """The 10-second 'Test Timer' goal computes Started and End Time within the same
    minute, so they render EQUAL (0-min offset). Assert both render and End - Start
    is 0 min (allow 1 min for a read straddling a minute boundary). Complements the
    +1h case: same machinery, different goal duration -> different computed value."""
    open_main_clear()
    started = _start_goal("Test Timer")
    if not started:
        record("computation_test_timer_start_eq_end", False,
               "feature_missing: could not start 'Test Timer'",
               depth=0, jump_kind="value",
               expect="Test Timer Started == End Time (0-min offset)")
        return
    nodes = ui()
    both_render = (find_node(nodes, text="Started") is not None
                   and find_node(nodes, text="End Time") is not None)
    start_min = _clock_minutes(nodes, "Started")
    end_min = _clock_minutes(nodes, "End Time")
    diff = None
    if start_min is not None and end_min is not None:
        diff = (end_min - start_min) % (24 * 60)
    same_min = diff is not None and diff <= 1
    ok = both_render and same_min
    record("computation_test_timer_start_eq_end", bool(ok),
           "" if ok else (f"behavior_wrong: Test Timer End Time was not within the "
                          f"same minute as Started (start_min={start_min}, "
                          f"end_min={end_min}, diff={diff}); both_render={both_render}"),
           depth=0, jump_kind="value",
           expect=f"Test Timer End Time - Started == 0 min (observed diff {diff})")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (6) FASTS COUNT — clean baseline is 0, then 0 -> 1 -> 2 as fasts are saved
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_fasts_count_zero",))
def test_fasts_count_zero():
    """On a CLEAN install the Dashboard 'Fasts / N / this month' aggregate is 0 (and
    History reads 'No recent fasts to show.'). The negative baseline that makes the
    0->1 delta discriminating."""
    open_main_clear()
    nodes = ui()
    count = _fasts_count(nodes)
    empty_hist = find_node_ci(nodes, "No recent fasts to show.") is not None
    ok = (count == 0) and empty_hist
    record("computation_fasts_count_zero", bool(ok),
           "" if ok else (f"behavior_wrong: clean-install Dashboard 'Fasts' count was "
                          f"{count!r} (expected 0) / History not empty "
                          f"({empty_hist})"),
           depth=0, jump_kind="value",
           expect="clean-install Dashboard 'Fasts' count == 0")


@and_test(expects=("computation_fasts_count_zero_to_one",))
def test_fasts_count_zero_to_one():
    """The 'Fasts' aggregate increments 0 -> 1 after completing and SAVING one Test
    Timer fast. Reads the count BEFORE (must be 0) and AFTER the save (must be 1) —
    the count is the computed aggregate, not the record's mere existence."""
    open_main_clear()
    before = _fasts_count(ui())
    made = save_test_timer_fast()
    after = _fasts_count(ui()) if made else None
    ok = (before == 0) and made and (after == 1)
    record("computation_fasts_count_zero_to_one", bool(ok),
           "" if ok else ("feature_missing: could not complete+Save a Test Timer fast"
                          if not made
                          else f"behavior_wrong: Dashboard 'Fasts' count was "
                               f"{before!r} before and {after!r} after saving one fast "
                               f"(expected 0 -> 1)"),
           depth=0, jump_kind="value",
           expect=f"Dashboard 'Fasts' count 0 -> 1 after one saved fast (saw {before} "
                  f"-> {after})")


@and_test(expects=("computation_fasts_count_two",))
def test_fasts_count_two():
    """The aggregate keeps climbing: after a SECOND saved Test Timer fast the count
    is 2. A recreation that keeps only a single 'latest' row (not a real count)
    stalls at 1. Asserts the 0,1,2 progression across two saves."""
    open_main_clear()
    counts = [_fasts_count(ui())]                 # baseline 0
    for _ in range(2):
        if not save_test_timer_fast():
            break
        counts.append(_fasts_count(ui()))
    ok = (len(counts) == 3
          and all(c is not None for c in counts)
          and counts == [0, 1, 2])
    record("computation_fasts_count_two", bool(ok),
           "" if ok else (f"behavior_wrong: Dashboard 'Fasts' count did not climb "
                          f"0 -> 1 -> 2 across two saves (saw {counts}) — only one "
                          f"record appears to be kept"),
           depth=0, jump_kind="value",
           expect=f"Dashboard 'Fasts' count 0,1,2 across two saves (observed {counts})")


# ═══════════════════════════════════════════════════════════════════════════════
# (7) STATISTICS AGGREGATES — Total Fasts = 1, Consistency = 100% (goal met)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_stats_total_fasts_one",
                   "computation_stats_total_fasts_one_vlm"))
def test_stats_total_fasts_one():
    """After one goal-met Test Timer fast, the Statistics ('Performance') screen's
    'Total Fasts' card reads '1' (with subtitle 'completed'). Crosses to Statistics
    (depth 1, backed by and_reach_statistics) and reads the computed aggregate. The
    stat-card cluster showing the numbers is the paired VLM."""
    open_main_clear()
    made = save_test_timer_fast()
    reached = made and and_reach_statistics()      # depth 1 (proven reach)
    if not reached:
        record("computation_stats_total_fasts_one", False,
               "setup_failed: could not save a fast and reach Statistics"
               if not made else
               "setup_failed: Statistics ('Trends') not reached from 'Go to "
               "Statistics'",
               depth=1, jump_kind="value",
               expect="Statistics 'Total Fasts' card reads '1'")
        vlm_assert("computation_stats_total_fasts_one",
                   "Do the three rounded statistic cards near the bottom show numeric "
                   "values under their titles (a whole number under 'Total Fasts' and "
                   "a percentage under 'Consistency')? Answer YES or NO.",
                   RESULTS_DIR, tag="content", depth=1, jump_kind="value")
        return
    nodes = ui()
    total = _value_under_label(nodes, "Total Fasts", lambda t: t.isdigit())
    ok = total == "1"
    record("computation_stats_total_fasts_one", bool(ok),
           "" if ok else f"behavior_wrong: Statistics 'Total Fasts' read {total!r} "
                         f"after one saved fast (expected '1')",
           depth=1, jump_kind="value",
           expect=f"Statistics 'Total Fasts' == '1' (read {total!r})")
    # VLM (value-made-visual): the expressive stat-card cluster shows the numbers.
    vlm_assert("computation_stats_total_fasts_one",
               "Do the three rounded statistic cards near the bottom each show a large "
               "numeric value under their title (for example a whole number under "
               "'Total Fasts' and a percentage under 'Consistency')? Answer YES or NO.",
               RESULTS_DIR, tag="content", depth=1, jump_kind="value")


@and_test(expects=("computation_stats_consistency_100",))
def test_stats_consistency_100():
    """A Test Timer fast REACHES its goal, so after saving one the Statistics
    'Consistency' card reads '100%' (subtitle 'goals met'). Crosses to Statistics
    (depth 1) and reads the computed percentage — a derived value from goals-met /
    total."""
    open_main_clear()
    made = save_test_timer_fast()
    reached = made and and_reach_statistics()      # depth 1 (proven reach)
    if not reached:
        record("computation_stats_consistency_100", False,
               "setup_failed: could not save a fast and reach Statistics",
               depth=1, jump_kind="value",
               expect="Statistics 'Consistency' card reads '100%'")
        return
    nodes = ui()
    pct = _value_under_label(nodes, "Consistency", lambda t: t.endswith("%"))
    ok = pct == "100%"
    record("computation_stats_consistency_100", bool(ok),
           "" if ok else f"behavior_wrong: Statistics 'Consistency' read {pct!r} after "
                         f"one goal-met fast (expected '100%')",
           depth=1, jump_kind="value",
           expect=f"Statistics 'Consistency' == '100%' (read {pct!r})")


@and_test(expects=("computation_stats_chart_vlm",))
def test_stats_chart_vlm():
    """The Statistics screen renders a bar/line CHART whose bar HEIGHTS encode the
    per-day/period values — a value made visual that never reaches the view tree.
    Crosses to Statistics (depth 1) and asks the VLM about the drawn bars. Pure VLM
    (no dump-readable rule half beyond reachability, which navigation owns)."""
    open_main_clear()
    made = save_test_timer_fast()
    reached = made and and_reach_statistics()      # depth 1 (proven reach)
    if not reached:
        vlm_assert("computation_stats_chart",
                   "Are there several vertical or horizontal bars of differing "
                   "lengths drawn above a row of day/date axis labels (T F S S M T W)? "
                   "Answer YES or NO.",
                   RESULTS_DIR, tag="shape", depth=1, jump_kind="value")
        return
    # VLM (value-made-visual): the chart bars differ in height/length by value.
    vlm_assert("computation_stats_chart",
               "Are there several coloured bars drawn in a row above the day/date axis "
               "labels (like T F S S M T W), representing a chart of values? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=1, jump_kind="value")


# ═══════════════════════════════════════════════════════════════════════════════
# (8) HISTORY AGGREGATE — August Summary 'Total Fasts' = 1
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_history_summary_total_one",))
def test_history_summary_total_one():
    """After one saved Test Timer fast, the History pane's 'August Summary' ->
    'Total Fasts' card reads '1'. Crosses to the History pane (depth 1, backed by
    and_reach_history) and reads the month aggregate."""
    open_main_clear()
    made = save_test_timer_fast()
    reached = made and and_reach_history()          # depth 1 (proven reach)
    if not reached:
        record("computation_history_summary_total_one", False,
               "setup_failed: could not save a fast and reach the History pane",
               depth=1, jump_kind="value",
               expect="History 'August Summary' 'Total Fasts' reads '1'")
        return
    # the summary sits below the calendar; scroll it into view then read the value
    summary = scroll_into_view("August Summary", max_swipes=4)
    nodes = ui()
    total = _value_under_label(nodes, "Total Fasts", lambda t: t.isdigit())
    ok = (summary is not None) and total == "1"
    record("computation_history_summary_total_one", bool(ok),
           "" if ok else f"behavior_wrong: History 'August Summary' 'Total Fasts' read "
                         f"{total!r} after one saved fast (expected '1')",
           depth=1, jump_kind="value",
           expect=f"History 'August Summary' 'Total Fasts' == '1' (read {total!r})")


# ═══════════════════════════════════════════════════════════════════════════════
# (9) DURATION FORMATTING — a saved fast renders a \\d+h \\d+m duration
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_duration_format",))
def test_duration_format():
    """A completed fast's duration is computed and rendered as '<H>h <M>m' (e.g.
    '0h 2m'). After saving one Test Timer fast, the Dashboard History section shows
    the entry under 'This Week' with a duration matching \\d+h \\d+m. Assert the
    PATTERN renders (the exact minutes depend on wall-clock rollover during the ~10s
    fast, so the value itself is NOT hard-coded) and that no duration was present on
    the clean baseline."""
    open_main_clear()
    absent_before = not any(_DUR.search(n.get("text", "")) for n in ui())
    made = save_test_timer_fast()
    nodes = ui() if made else []
    dur_node = next((n.get("text", "") for n in nodes
                     if _DUR.search(n.get("text", ""))), None)
    this_week = made and find_node(nodes, text="This Week") is not None
    parsed = _DUR.search(dur_node) if dur_node else None
    # h and m are non-negative and well-formed (m < 60 is the only sanity bound)
    format_ok = parsed is not None and 0 <= int(parsed.group(2)) < 60
    ok = absent_before and made and this_week and format_ok
    record("computation_duration_format", bool(ok),
           "" if ok else ("feature_missing: could not save a Test Timer fast"
                          if not made
                          else f"behavior_wrong: no '<H>h <M>m' duration rendered in "
                               f"the Dashboard History after saving (dur={dur_node!r}, "
                               f"absent_before={absent_before})"),
           depth=0, jump_kind="value",
           expect=f"saved fast renders a '\\d+h \\d+m' duration under 'This Week' "
                  f"(saw {dur_node!r})")


# ═══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_countdown_decreases,
    test_countup_increases,
    test_test_timer_initial_remaining,
    test_goal_reached_transition,
    test_start_end_time_offset,
    test_test_timer_start_equals_end,
    test_fasts_count_zero,
    test_fasts_count_zero_to_one,
    test_fasts_count_two,
    test_stats_total_fasts_one,
    test_stats_consistency_100,
    test_stats_chart_vlm,
    test_history_summary_total_one,
    test_duration_format,
]

if __name__ == "__main__":
    if not device_online():
        print("setup_failed: device offline / adb tunnel down — aborting")
        sys.exit(2)
    run_suite(TESTS, "computation")