File size: 45,700 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
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
#!/usr/bin/env python3
"""TEXT module — FastTimes (intermittent-fasting tracker).

This lane owns CONTENT / OUTPUT strings that an INTERACTION PRODUCES — the exact
words the app writes in response to a trigger — and is the sole owner of exact-
string equality. Every test is TRIGGER -> OBSERVATION that a specific literal
string appeared / changed on the destination surface. All strings asserted here
were OBSERVED on the running ORIGINAL (see the probe transcript in the delegation
notes), never read from source or computed.

What this lane asserts (LABELS / COPY, never a computed number):
  * empty-history status copy  "No recent fasts to show." (dynamic empty state)
  * active-fast timer LABELS produced by starting a goal: "Remaining" (timed),
    "Elapsed Time" + no "End Time" line (Open Fast)
  * the goal-met COPY the app authors on the target-met transition:
    "Goal Reached!" + label "Total Time"
  * the fasting PHASE-chip name "Post-Absorptive State" (produced by an active
    fast) and the phase-detail sheet's descriptive labels "Timing"/"Benefit"
    (produced by tapping the chip — depth 1)
  * the "Fast Complete!" summary copy: "Fast Complete!", "Rate your fast:",
    "Started:", "Ended:", "Save" (produced by End Fast — depth 1)
  * the Manage-Profiles empty-favourite HINT + section headers (depth 1)
  * the Statistics header FLIP "This week" -> "Last 30 days" (Weekly->Monthly)
    plus the empty-state subtitle and stat-card LABELS (depth 1)
  * the History month header CHANGE "August 2026" -> previous month, produced by
    the "Previous Month" control (depth 1; Next Month is disabled on the current
    month, so the observable change is via Previous)
  * the History-Info sheet copy "Understanding History" + legend (depth 2)
  * the Daily-Details sheet TITLE "Details for <Month> <day>" produced by tapping
    a day with data (depth 2)
  * the Settings footer version string and section headers (depth 1)

CEDES to sibling lanes: reachability itself -> navigation; the checked/selected
bit -> states; the mere existence of a saved record -> interaction; any computed
number (timer value, aggregate count, percentage) -> computation; the view-tree
shape / drawn arcs -> structure. This lane cares ONLY about literal text content.

Every string here is READABLE FROM THE DUMP (verified), so every assertion is a
RULE assertion and this lane uses ZERO vlm_assert — its VLM ceiling is 2 but the
brief is explicit that manufacturing a visual question for dump-readable text is
wrong; text earns LOW VLM and 0 is the correct count here.

Compose renders as android.view.View / TextView with NO resource-ids, so every
target is located by visible text / content-desc.

SAFETY: never taps "Delete" / "Delete Fast" / "Reset"; exploratory taps go
through is_safe()/safe_tap(). Each test opens its own entry point.

Run:  python3 test_android_text.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

# ── Tight patterns for the time/date-dependent produced strings (the assertion is
# always about the STRING CONTENT / shape, never a computed value). ─────────────
_MONTH_YEAR = re.compile(r"^[A-Z][a-z]+ \d{4}$")            # "August 2026"
_DETAILS = re.compile(r"Details for [A-Z][a-z]+ \d{1,2}")   # "Details for August 6"
_VERSION = re.compile(r"\d+\.\d+\.\d+-DEBUG \(\d+\)")       # "1.0.4-DEBUG (5)"
# The five possible fasting-phase chip names (near t=0 it is the first one).
_PHASE_NAMES = (
    "Post-Absorptive State", "Metabolic Switch", "Autophagy Activation",
    "Deep Ketosis & Repair", "Immune Regeneration",
)


# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
# it ~half the time). Resolve THIS package's real MainActivity at runtime — no
# hardcoded package or activity literal. ────────────────────────────────────────
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 (the choice is irrelevant
    to the copy 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 _wait_goal_reached(polls=18):
    """Poll until the 10s Test Timer flips to 'Goal Reached!'. 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 _all_text(nodes):
    return " | ".join(n.get("text", "") for n in nodes if n.get("text"))


def _has_text(nodes, s):
    return find_node(nodes, text=s) is not None or find_node_ci(nodes, s) is not None


def _modal_star_views():
    """The clickable rating-star Views in the 'Fast Complete!' summary modal:
    empty-text square clickable android.view.View nodes in one horizontal row."""
    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)
    stars.sort(key=lambda n: n["_center"][0])
    return stars


def _open_summary_from_test_timer():
    """Start Test Timer, reach goal, tap End Fast -> the 'Fast Complete!' summary
    modal. Returns True when the modal is up (does NOT save)."""
    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")
    return find_node(ui(), text="Fast Complete!") is not None


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. Needed for the Daily-
    Details title test (a day cell only opens the sheet once it has data)."""
    if not _open_summary_from_test_timer():
        return False
    stars = _modal_star_views()
    if len(stars) >= 4:
        tap_node(stars[3])                    # 4th star (non-destructive)
        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():
    """Best-effort cleanup: dismiss the summary/active fast without saving."""
    if find_node(ui(), text="Fast Complete!"):
        back()
        settle("tap")
        return
    ef = find_node(ui(), content_desc="End Fast")
    if ef:
        tap_node(ef)
        settle("tap")
        back()
        settle("tap")


# ── Named depth helpers. The and_enter_*/and_reach_* NAME is what backs a
# depth>=1 claim; each body performs a REAL surface jump (proven by a surface
# change or a target-appeared/source-vanished check) before counting the surface.
def and_reach_statistics():
    """Dashboard -> Statistics ('Performance'). Proven: 'Trends' appears, the goal
    card 'Set your goal' vanishes. Counts one surface."""
    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, "2026", "Set your goal")


def and_enter_manage_profiles():
    """Dashboard -> 'Manage Profiles' screen. Confirms the surface changed and
    counts one surface. Returns (ok, note)."""
    return and_enter_surface(ui(), target_text="Manage Profiles")


def and_enter_settings():
    """Dashboard -> Settings screen (gear, desc='Settings'). Counts one surface."""
    return and_enter_surface(ui(), content_desc="Settings")


def and_enter_phase_sheet():
    """Active-fast card: tap the fasting-phase chip -> phase-detail bottom sheet.
    The chip renders a phase-name TextView (its bounds overlay the Canvas that
    owns the click). Proven: 'Timing' newly appears. Counts one surface."""
    before = and_showing()
    chip = None
    for name in _PHASE_NAMES:
        chip = find_node(ui(), text=name)
        if chip:
            break
    if not chip or not tap_node(chip):
        return False
    after = and_showing()
    if not and_reach(before, after, "Timing"):
        return False
    and_enter("phase_sheet")
    return True


def and_enter_daily_details():
    """History pane: tap a day cell that has a completed fast (desc='Goal Met')
    -> the Daily-Details bottom sheet. Proven: a 'Details for ...' title appears.
    Counts one surface (used at depth 2, after and_reach_history)."""
    cell = find_node(ui(), content_desc="Goal Met")
    if not cell or not tap_node(cell):
        return False
    if not any(_DETAILS.search(n.get("text", "") or "") for n in ui()):
        return False
    and_enter("daily_details")
    return True


def and_enter_history_info():
    """History pane: tap the 'History Info' (i) icon -> the 'Understanding
    History' bottom sheet. Proven: the sheet title appears. Counts one surface."""
    info = find_node(ui(), content_desc="History Info")
    if not info or not tap_node(info):
        return False
    if find_node(ui(), text="Understanding History") is None:
        return False
    and_enter("history_info")
    return True


# ═══════════════════════════════════════════════════════════════════════════════
# (1) EMPTY-HISTORY COPY — the dashboard empty-state status line
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_empty_history_copy",))
def test_empty_history_copy():
    """On a CLEAN dashboard the History section shows the exact dynamic empty-state
    copy 'No recent fasts to show.'. This is status text the app writes for the
    empty state (not static chrome — it is replaced by a fast entry once one is
    saved), so it is a strong produced-string TEXT assertion."""
    open_main_clear()
    nodes = ui()
    if not _on_dashboard(nodes):
        record("text_empty_history_copy", False,
               "setup_failed: dashboard ('Set your goal') not shown after a clean "
               "launch",
               depth=0, jump_kind="value", expect="'No recent fasts to show.'")
        return
    ok = _has_text(nodes, "No recent fasts to show.")
    record("text_empty_history_copy", bool(ok),
           "" if ok else "feature_missing: the empty-history status copy 'No recent "
                         "fasts to show.' was not shown on a clean dashboard",
           depth=0, jump_kind="value",
           expect="History empty-state copy reads 'No recent fasts to show.'")


# ═══════════════════════════════════════════════════════════════════════════════
# (2) TIMER LABEL 'Remaining' — produced by starting a TIMED goal
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_label_remaining",))
def test_label_remaining():
    """Starting a TIMED goal ('Test 1 Hour') produces the active-fast card label
    'Remaining' (this lane asserts the LITERAL LABEL, not the countdown value which
    computation owns). Assert it is ABSENT on the clean dashboard and PRESENT after
    starting — the discriminating change, so a hardcoded label on a dead shell
    cannot pass."""
    open_main_clear()
    absent = not _has_text(ui(), "Remaining")
    started = _start_goal("Test 1 Hour")
    if not started:
        record("text_label_remaining", False,
               "feature_missing: could not start the 'Test 1 Hour' timed goal "
               "('End Fast' card not shown)",
               depth=0, jump_kind="value",
               expect="active-fast card label reads 'Remaining'")
        return
    present = _has_text(ui(), "Remaining")
    ok = absent and present
    record("text_label_remaining", bool(ok),
           "" if ok else (f"behavior_wrong: 'Remaining' label state was absent={absent} "
                          f"present-after={present}; expected absent before and present "
                          f"after starting a timed goal"),
           depth=0, jump_kind="value",
           expect="label 'Remaining' absent before, present after starting a timed goal")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (3) TIMER LABEL 'Elapsed Time' (+ NO 'End Time') — produced by Open Fast
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_label_elapsed_time",))
def test_label_elapsed_time():
    """Starting 'Open Fast' (infinite goal) produces the label 'Elapsed Time' and,
    unlike a timed goal, NO 'End Time' line. Assert the label appears (absent before,
    present after) AND that the 'End Time' label is not present — the copy that
    distinguishes the open-goal card from a timed one."""
    open_main_clear()
    absent = not _has_text(ui(), "Elapsed Time")
    started = _start_goal("Open Fast")
    if not started:
        record("text_label_elapsed_time", False,
               "feature_missing: could not start 'Open Fast' ('End Fast' card not "
               "shown)",
               depth=0, jump_kind="value",
               expect="label 'Elapsed Time' present, no 'End Time' line")
        return
    nodes = ui()
    present = _has_text(nodes, "Elapsed Time")
    no_end_time = find_node(nodes, text="End Time") is None
    ok = absent and present and no_end_time
    record("text_label_elapsed_time", bool(ok),
           "" if ok else (f"behavior_wrong: 'Elapsed Time' absent={absent} "
                          f"present-after={present}; 'End Time' line present="
                          f"{not no_end_time} (Open Fast must show 'Elapsed Time' and "
                          f"no 'End Time')"),
           depth=0, jump_kind="value",
           expect="label 'Elapsed Time' appears and no 'End Time' line for Open Fast")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (4) GOAL-REACHED COPY — 'Goal Reached!' + label 'Total Time' (Test Timer ~10s)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_goal_reached_copy",))
def test_goal_reached_copy():
    """The 10-second debug 'Test Timer' authors goal-met COPY when its target is
    met: the goal-name line flips to 'Goal Reached!' and the label becomes 'Total
    Time'. Assert both literal strings are ABSENT while counting down and PRESENT
    after ~10s (this lane owns the string CONTENT; the states lane owns the
    transition bit). Generous bounded poll."""
    open_main_clear()
    started = _start_goal("Test Timer")
    if not started:
        record("text_goal_reached_copy", False,
               "feature_missing: could not start 'Test Timer' ('End Fast' card not "
               "shown)",
               depth=0, jump_kind="value",
               expect="'Goal Reached!' + label 'Total Time' appear")
        return
    before = ui()
    absent = (find_node(before, text="Goal Reached!") is None
              and find_node(before, text="Total Time") is None)
    flipped = _wait_goal_reached()
    after = ui()
    present = (find_node(after, text="Goal Reached!") is not None
              and find_node(after, text="Total Time") is not None)
    ok = absent and flipped and present
    record("text_goal_reached_copy", bool(ok),
           "" if ok else (f"behavior_wrong: goal-met copy absent-before={absent} "
                          f"present-after={present}; expected 'Goal Reached!' and "
                          f"'Total Time' to appear once the Test Timer target is met"),
           depth=0, jump_kind="value",
           expect="'Goal Reached!' + label 'Total Time' absent before, present after "
                  "target met")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (5) FASTING PHASE-CHIP NAME — produced by an active fast
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_phase_chip_name",))
def test_phase_chip_name():
    """An active fast shows a fasting PHASE chip whose text is a phase name. Near
    t=0 the phase is Post-Absorptive, so the chip reads 'Post-Absorptive State'.
    Assert the chip text is one of the known phase names (OR across them for
    robustness to elapsed time), ABSENT before the fast and PRESENT after."""
    open_main_clear()
    absent = not any(_has_text(ui(), p) for p in _PHASE_NAMES)
    started = _start_goal("Test 1 Hour")
    if not started:
        record("text_phase_chip_name", False,
               "feature_missing: could not start 'Test 1 Hour' to reveal the phase "
               "chip",
               depth=0, jump_kind="value",
               expect="phase chip reads a phase name (e.g. 'Post-Absorptive State')")
        return
    nodes = ui()
    shown = next((p for p in _PHASE_NAMES if _has_text(nodes, p)), None)
    ok = absent and shown is not None
    record("text_phase_chip_name", bool(ok),
           "" if ok else (f"behavior_wrong: no known fasting-phase name on the active "
                          f"card (absent-before={absent}, shown={shown!r}); expected "
                          f"one of {_PHASE_NAMES}"),
           depth=0, jump_kind="value",
           expect=f"active-fast phase chip reads a phase name (saw {shown!r})")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (6) PHASE-DETAIL SHEET COPY — 'Timing' / 'Benefit' produced by tapping the chip
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_phase_sheet_labels",))
def test_phase_sheet_labels():
    """Tapping the fasting-phase chip on the active-fast card opens a phase-detail
    bottom sheet with descriptive LABELS 'Timing' and 'Benefit'. Crosses one
    surface (depth 1, backed by and_enter_phase_sheet, which proves 'Timing'
    appeared) and asserts both literal labels — a strong produced-copy test."""
    open_main_clear()
    if not _start_goal("Test 1 Hour"):
        record("text_phase_sheet_labels", False,
               "setup_failed: could not start a fast to reach the phase chip",
               depth=1, jump_kind="value",
               expect="phase-detail sheet shows 'Timing' and 'Benefit' labels")
        return
    if not and_enter_phase_sheet():                 # depth 1 (proven surface jump)
        record("text_phase_sheet_labels", False,
               "setup_failed: tapping the phase chip did not open the phase-detail "
               "sheet",
               depth=1, jump_kind="value",
               expect="phase-detail sheet shows 'Timing' and 'Benefit' labels")
        _end_active_no_save()
        return
    nodes = ui()
    ok = _has_text(nodes, "Timing") and _has_text(nodes, "Benefit")
    record("text_phase_sheet_labels", bool(ok),
           "" if ok else "behavior_wrong: the phase-detail sheet did not show both "
                         "descriptive labels 'Timing' and 'Benefit'",
           depth=1, jump_kind="value",
           expect="phase-detail sheet shows the labels 'Timing' and 'Benefit'")
    back()
    settle("tap")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (7) FAST COMPLETE! SUMMARY COPY — produced by End Fast
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_fast_complete_copy",))
def test_fast_complete_copy():
    """Ending a fast (End Fast on the active card) opens a summary modal whose copy
    is app-authored: title 'Fast Complete!', the prompt 'Rate your fast:', the
    labels 'Started:' and 'Ended:', and a 'Save' button label. Crosses one surface
    (depth 1, backed by and_enter) and asserts all five literal strings. End Fast
    is non-destructive; the modal is dismissed without saving."""
    open_main_clear()
    if not _open_summary_from_test_timer():
        record("text_fast_complete_copy", False,
               "setup_failed: could not reach the 'Fast Complete!' summary (start "
               "Test Timer -> End Fast)",
               depth=1, jump_kind="value",
               expect="summary shows 'Fast Complete!', 'Rate your fast:', 'Started:', "
                      "'Ended:', 'Save'")
        return
    and_enter("fast_complete_summary")              # depth 1 (the End Fast modal)
    nodes = ui()
    want = ("Fast Complete!", "Rate your fast:", "Started:", "Ended:", "Save")
    missing = [s for s in want if not _has_text(nodes, s)]
    ok = not missing
    record("text_fast_complete_copy", bool(ok),
           "" if ok else f"behavior_wrong: the Fast Complete summary is missing copy "
                         f"{missing}",
           depth=1, jump_kind="value",
           expect="summary shows 'Fast Complete!' / 'Rate your fast:' / 'Started:' / "
                  "'Ended:' / 'Save'")
    _end_active_no_save()


# ═══════════════════════════════════════════════════════════════════════════════
# (8) MANAGE-PROFILES EMPTY-FAVOURITE HINT + section headers
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_manage_profiles_hint",))
def test_manage_profiles_hint():
    """Opening 'Manage Profiles' from the Dashboard shows, when no favourite is set,
    the hint 'Press and hold a profile to add it as your favourite' under the
    'Favourite Fast' section, alongside the 'Other Profiles' header. Crosses one
    surface (depth 1, backed by and_enter_manage_profiles) and asserts the hint plus
    both section headers — produced copy on the destination."""
    open_main_clear()
    ok_enter, note = and_enter_manage_profiles()    # depth 1 (surface change proven)
    if not ok_enter:
        record("text_manage_profiles_hint", False,
               note or "setup_failed: could not reach the Manage Profiles screen",
               depth=1, jump_kind="value",
               expect="hint 'Press and hold a profile to add it as your favourite'")
        return
    nodes = ui()
    hint = _has_text(nodes, "Press and hold a profile to add it as your favourite")
    fav = _has_text(nodes, "Favourite Fast")
    other = _has_text(nodes, "Other Profiles")
    ok = hint and fav and other
    record("text_manage_profiles_hint", bool(ok),
           "" if ok else (f"behavior_wrong: Manage Profiles copy — hint={hint}, "
                          f"'Favourite Fast'={fav}, 'Other Profiles'={other}; expected "
                          f"all three"),
           depth=1, jump_kind="value",
           expect="empty-favourite hint + 'Favourite Fast' + 'Other Profiles' headers")


# ═══════════════════════════════════════════════════════════════════════════════
# (9) STATISTICS HEADER FLIP — 'This week' -> 'Last 30 days' (Weekly -> Monthly)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_stats_header_flip",))
def test_stats_header_flip():
    """The Statistics ('Performance') screen header reads 'This week' under the
    Weekly segment; tapping the 'Monthly' segment flips the header text to 'Last 30
    days'. Crosses one surface (depth 1, backed by and_reach_statistics) and asserts
    the BEFORE->AFTER string change ('This week' present & 'Last 30 days' absent, ->
    'Last 30 days' present & 'This week' absent)."""
    open_main_clear()
    if not and_reach_statistics():                  # depth 1 (proven reach)
        record("text_stats_header_flip", False,
               "setup_failed: could not reach the Statistics ('Performance') screen",
               depth=1, jump_kind="transition",
               expect="header 'This week' -> 'Last 30 days'")
        return
    before = ui()
    week_before = (find_node(before, text="This week") is not None
                   and find_node(before, text="Last 30 days") is None)
    monthly = find_node(before, text="Monthly")
    if not monthly or not safe_tap(monthly):
        record("text_stats_header_flip", False,
               "setup_failed: 'Monthly' segment not found/tappable on Statistics",
               depth=1, jump_kind="transition",
               expect="header 'This week' -> 'Last 30 days'")
        return
    settle("tap")
    after = ui()
    month_after = (find_node(after, text="Last 30 days") is not None
                   and find_node(after, text="This week") is None)
    ok = week_before and month_after
    record("text_stats_header_flip", bool(ok),
           "" if ok else (f"behavior_wrong: header did not flip — week_before="
                          f"{week_before}, month_after={month_after}; expected 'This "
                          f"week' -> 'Last 30 days' on Weekly->Monthly"),
           depth=1, jump_kind="transition",
           expect="Statistics header 'This week' -> 'Last 30 days' on Weekly->Monthly")


# ═══════════════════════════════════════════════════════════════════════════════
# (10) STATISTICS EMPTY-STATE + STAT-CARD LABELS (produced copy on the destination)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_stats_labels",))
def test_stats_labels():
    """The Statistics screen shows the empty-state subtitle 'Keep going to build a
    habit!' and the stat-card LABELS 'Total Fasts' / 'Average Fast' / 'Consistency'
    with sub-labels 'completed' / 'this week' / 'goals met' (this lane asserts the
    LABEL strings, never the numbers). Crosses one surface (depth 1, backed by
    and_reach_statistics)."""
    open_main_clear()
    if not and_reach_statistics():                  # depth 1 (proven reach)
        record("text_stats_labels", False,
               "setup_failed: could not reach the Statistics ('Performance') screen",
               depth=1, jump_kind="value",
               expect="stat-card labels 'Total Fasts'/'Average Fast'/'Consistency'")
        return
    nodes = ui()
    want = ("Keep going to build a habit!", "Total Fasts", "Average Fast",
            "Consistency", "completed", "this week", "goals met")
    missing = [s for s in want if not _has_text(nodes, s)]
    ok = not missing
    record("text_stats_labels", bool(ok),
           "" if ok else f"behavior_wrong: Statistics is missing label copy {missing}",
           depth=1, jump_kind="value",
           expect="subtitle 'Keep going to build a habit!' + stat labels Total Fasts/"
                  "Average Fast/Consistency + completed/this week/goals met")


# ═══════════════════════════════════════════════════════════════════════════════
# (11) HISTORY MONTH HEADER CHANGE — 'August 2026' -> previous month
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_history_month_change",))
def test_history_month_change():
    """The History pane's month header reads a '<Month> <Year>' string (e.g. 'August
    2026'). Tapping 'Previous Month' advances the label to the prior month (Next
    Month is disabled on the current month, so Previous is the observable change).
    Crosses one surface (depth 1, backed by and_reach_history) and asserts the
    header STRING CHANGED to a different, well-formed '<Month> <Year>'."""
    open_main_clear()
    if not and_reach_history():                     # depth 1 (proven reach)
        record("text_history_month_change", False,
               "setup_failed: could not reach the History pane",
               depth=1, jump_kind="transition",
               expect="month header '<Month> <Year>' changes after 'Previous Month'")
        return

    def _month_header(nodes):
        return next((n.get("text", "").strip() for n in nodes
                     if _MONTH_YEAR.fullmatch(n.get("text", "").strip())), None)

    before = _month_header(ui())
    prev = find_node(ui(), content_desc="Previous Month")
    if before is None or not prev or not tap_node(prev):
        record("text_history_month_change", False,
               f"setup_failed: month header ({before!r}) or 'Previous Month' control "
               f"not usable",
               depth=1, jump_kind="transition",
               expect="month header '<Month> <Year>' changes after 'Previous Month'")
        return
    settle("tap")
    after = _month_header(ui())
    ok = (after is not None and after != before
          and _MONTH_YEAR.fullmatch(after) is not None)
    record("text_history_month_change", bool(ok),
           "" if ok else (f"behavior_wrong: month header did not change on 'Previous "
                          f"Month' (before={before!r} after={after!r}); expected a "
                          f"different '<Month> <Year>' string"),
           depth=1, jump_kind="transition",
           expect=f"month header changed '{before}' -> '{after}' via 'Previous Month'")


# ═══════════════════════════════════════════════════════════════════════════════
# (12) HISTORY-INFO SHEET COPY — 'Understanding History' + legend
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_history_info_sheet",))
def test_history_info_sheet():
    """The History toolbar's 'History Info' (i) icon opens a bottom sheet titled
    'Understanding History' with legend copy ('Calendar View', 'Daily Timeline').
    Crosses TWO surfaces (History pane, then the info sheet) — depth 2, backed by
    and_reach_history + and_enter_history_info — and asserts the sheet's literal
    title and legend labels."""
    open_main_clear()
    if not and_reach_history():                     # depth 1 (proven reach)
        record("text_history_info_sheet", False,
               "setup_failed: could not reach the History pane",
               depth=2, jump_kind="value",
               expect="sheet 'Understanding History' + legend 'Calendar View'")
        return
    if not and_enter_history_info():                # depth 2 (proven: title appeared)
        record("text_history_info_sheet", False,
               "setup_failed: tapping 'History Info' did not open the 'Understanding "
               "History' sheet",
               depth=2, jump_kind="value",
               expect="sheet 'Understanding History' + legend 'Calendar View'")
        return
    nodes = ui()
    title = _has_text(nodes, "Understanding History")
    legend = _has_text(nodes, "Calendar View") and _has_text(nodes, "Daily Timeline")
    ok = title and legend
    record("text_history_info_sheet", bool(ok),
           "" if ok else (f"behavior_wrong: History-Info sheet copy — title={title}, "
                          f"legend('Calendar View'+'Daily Timeline')={legend}"),
           depth=2, jump_kind="value",
           expect="History-Info sheet 'Understanding History' + 'Calendar View' + "
                  "'Daily Timeline'")


# ═══════════════════════════════════════════════════════════════════════════════
# (13) DAILY-DETAILS SHEET TITLE — 'Details for <Month> <day>' produced by a tap
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_daily_details_title",))
def test_daily_details_title():
    """After saving one Test Timer fast, tapping today's day cell (desc='Goal Met')
    in History opens a Daily-Details bottom sheet whose title is 'Details for
    <Month> <day>' (the app derives the day from the device clock, asserted via a
    tight regex on the STRING shape, not a hardcoded day). Crosses TWO surfaces
    (History pane, then the day sheet) — depth 2, backed by and_reach_history +
    and_enter_daily_details."""
    open_main_clear()
    if not _save_test_timer_fast():
        record("text_daily_details_title", False,
               "setup_failed: could not complete+Save a Test Timer fast (needed so a "
               "day cell has data)",
               depth=2, jump_kind="value",
               expect="Daily-Details sheet title matches 'Details for <Month> <day>'")
        return
    if not and_reach_history():                     # depth 1 (proven reach)
        record("text_daily_details_title", False,
               "setup_failed: could not reach the History pane after saving a fast",
               depth=2, jump_kind="value",
               expect="Daily-Details sheet title matches 'Details for <Month> <day>'")
        return
    if not and_enter_daily_details():               # depth 2 (proven: title appeared)
        record("text_daily_details_title", False,
               "setup_failed: tapping the day-with-data cell did not open the Daily-"
               "Details sheet",
               depth=2, jump_kind="value",
               expect="Daily-Details sheet title matches 'Details for <Month> <day>'")
        return
    nodes = ui()
    title = next((n.get("text", "") for n in nodes
                  if _DETAILS.search(n.get("text", "") or "")), None)
    ok = title is not None
    record("text_daily_details_title", bool(ok),
           "" if ok else "behavior_wrong: the Daily-Details sheet title did not match "
                         "'Details for <Month> <day>'",
           depth=2, jump_kind="value",
           expect=f"Daily-Details title matches 'Details for <Month> <day>' (saw "
                  f"{title!r})")


# ═══════════════════════════════════════════════════════════════════════════════
# (14) SETTINGS SECTION HEADERS — produced copy on the Settings destination
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_settings_headers",))
def test_settings_headers():
    """The Settings screen shows literal section headers: 'Appearance', 'Color
    Scheme', 'Notifications', 'Data Management'. Crosses one surface (depth 1, backed
    by and_enter_settings) and asserts these are copy on the DESTINATION (not home
    chrome). 'Appearance'/'Color Scheme' are at the top; 'Notifications'/'Data
    Management' are reached by scrolling within Settings."""
    open_main_clear()
    ok_enter, note = and_enter_settings()           # depth 1 (surface change proven)
    if not ok_enter:
        record("text_settings_headers", False,
               note or "setup_failed: could not reach the Settings screen",
               depth=1, jump_kind="value",
               expect="section headers Appearance/Color Scheme/Notifications/Data "
                      "Management")
        return
    top = ui()
    have_top = _has_text(top, "Appearance") and _has_text(top, "Color Scheme")
    # Scroll within Settings to bring the lower section headers into view.
    scroll_into_view("Data Management", max_swipes=6)
    low = ui()
    have_low = _has_text(low, "Notifications") and _has_text(low, "Data Management")
    ok = have_top and have_low
    record("text_settings_headers", bool(ok),
           "" if ok else (f"behavior_wrong: Settings headers — top(Appearance+Color "
                          f"Scheme)={have_top}, lower(Notifications+Data Management)="
                          f"{have_low}"),
           depth=1, jump_kind="value",
           expect="Settings shows headers 'Appearance'/'Color Scheme'/'Notifications'/"
                  "'Data Management'")


# ═══════════════════════════════════════════════════════════════════════════════
# (15) SETTINGS FOOTER VERSION STRING — app-authored copy (regex, no computed value)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("text_settings_version",))
def test_settings_version():
    """The Settings footer shows the app-authored version literal, matching
    '\\d+\\.\\d+\\.\\d+-DEBUG \\(\\d+\\)' (e.g. '1.0.4-DEBUG (5)'), next to the
    'Fast Times' footer label. This is copy the app renders — the observation is
    that the string is PRESENT; NO computed value is derived from it. A regex keeps
    it stable across a version bump while still asserting the string shape. Crosses
    one surface (depth 1, backed by and_enter_settings) and scrolls to the footer."""
    open_main_clear()
    ok_enter, note = and_enter_settings()           # depth 1 (surface change proven)
    if not ok_enter:
        record("text_settings_version", False,
               note or "setup_failed: could not reach the Settings screen",
               depth=1, jump_kind="value",
               expect="footer version matches '\\d+.\\d+.\\d+-DEBUG (\\d+)'")
        return
    # The version footer is at the very bottom of the Settings list.
    seen = None
    for _ in range(10):
        nodes = ui()
        seen = next((n.get("text", "") for n in nodes
                     if _VERSION.search(n.get("text", "") or "")), None)
        if seen:
            break
        scroll_down(0.7)
    ok = seen is not None
    record("text_settings_version", bool(ok),
           "" if ok else "feature_missing: no version footer matching "
                         "'\\d+.\\d+.\\d+-DEBUG (\\d+)' was found in Settings",
           depth=1, jump_kind="value",
           expect=f"Settings footer version matches '\\d+.\\d+.\\d+-DEBUG (\\d+)' "
                  f"(saw {seen!r})")


# ═══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_empty_history_copy,
    test_label_remaining,
    test_label_elapsed_time,
    test_goal_reached_copy,
    test_phase_chip_name,
    test_phase_sheet_labels,
    test_fast_complete_copy,
    test_manage_profiles_hint,
    test_stats_header_flip,
    test_stats_labels,
    test_history_month_change,
    test_history_info_sheet,
    test_daily_details_title,
    test_settings_headers,
    test_settings_version,
]

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