appstore-precheck 1.19.0 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +81 -39
  3. package/package.json +2 -2
  4. package/skills/appstore-precheck/SKILL.md +41 -146
  5. package/skills/appstore-precheck/guidelines-baseline.json +284 -35
  6. package/skills/appstore-precheck/guidelines-fingerprints.json +307 -93
  7. package/skills/appstore-precheck/references/finding-commentary.md +93 -0
  8. package/skills/appstore-precheck/references/methodology.md +56 -19
  9. package/skills/appstore-precheck/references/optional-review.md +56 -0
  10. package/skills/appstore-precheck/references/pierre-deep-review.md +292 -47
  11. package/skills/appstore-precheck/references/review-catalog.json +500 -13
  12. package/skills/appstore-precheck/references/screenshot-vision-review.md +8 -8
  13. package/skills/appstore-precheck/references/simulator-dynamic-review.md +73 -12
  14. package/skills/appstore-precheck/references/typesafe.md +15 -0
  15. package/skills/appstore-precheck/scripts/artifact-review.sh +10 -0
  16. package/skills/appstore-precheck/scripts/augment-json.py +29 -0
  17. package/skills/appstore-precheck/scripts/build-run.sh +5 -0
  18. package/skills/appstore-precheck/scripts/coverage-sections.sh +6 -0
  19. package/skills/appstore-precheck/scripts/dynamic-run.sh +94 -9
  20. package/skills/appstore-precheck/scripts/dynamic.sh +25 -1
  21. package/skills/appstore-precheck/scripts/evidence.sh +8 -3
  22. package/skills/appstore-precheck/scripts/findings.sh +8 -0
  23. package/skills/appstore-precheck/scripts/lib/artifact-review.py +518 -0
  24. package/skills/appstore-precheck/scripts/lib/asc-client.py +293 -0
  25. package/skills/appstore-precheck/scripts/lib/build-evidence.py +50 -0
  26. package/skills/appstore-precheck/scripts/lib/build-exec.py +50 -0
  27. package/skills/appstore-precheck/scripts/lib/build-plan.py +106 -0
  28. package/skills/appstore-precheck/scripts/lib/build-plan.sh +15 -0
  29. package/skills/appstore-precheck/scripts/lib/build-run.py +177 -0
  30. package/skills/appstore-precheck/scripts/lib/coverage-run.sh +23 -0
  31. package/skills/appstore-precheck/scripts/lib/coverage-sections.py +250 -0
  32. package/skills/appstore-precheck/scripts/lib/dyn-demo-login.py +111 -0
  33. package/skills/appstore-precheck/scripts/lib/dyn-device.sh +32 -4
  34. package/skills/appstore-precheck/scripts/lib/dyn-explore.py +316 -0
  35. package/skills/appstore-precheck/scripts/lib/dyn-guideline-capture.py +301 -0
  36. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.py +112 -0
  37. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.sh +23 -0
  38. package/skills/appstore-precheck/scripts/lib/dyn-process.py +75 -0
  39. package/skills/appstore-precheck/scripts/lib/dyn-quorum.sh +28 -30
  40. package/skills/appstore-precheck/scripts/lib/dyn-scrub.py +77 -0
  41. package/skills/appstore-precheck/scripts/lib/dyn-signals.sh +2 -2
  42. package/skills/appstore-precheck/scripts/lib/metadata-review.py +369 -0
  43. package/skills/appstore-precheck/scripts/lib/optin-scan.sh +79 -0
  44. package/skills/appstore-precheck/scripts/lib/optional-records.py +60 -0
  45. package/skills/appstore-precheck/scripts/lib/runtime-blocking.py +26 -0
  46. package/skills/appstore-precheck/scripts/lib/safe_write.py +70 -0
  47. package/skills/appstore-precheck/scripts/lib/scan-guidelines.sh +109 -0
  48. package/skills/appstore-precheck/scripts/lib/static-guidelines.py +370 -0
  49. package/skills/appstore-precheck/scripts/lib/static-reader.py +39 -0
  50. package/skills/appstore-precheck/scripts/metadata-review.sh +4 -0
  51. package/skills/appstore-precheck/scripts/opt-in-review.py +160 -0
  52. package/skills/appstore-precheck/scripts/runtime-review.sh +5 -0
  53. package/skills/appstore-precheck/scripts/scan.sh +58 -24
  54. package/skills/appstore-precheck/scripts/semantic/client.py +3 -1
  55. package/skills/appstore-precheck/scripts/semantic/collect.py +82 -38
  56. package/skills/appstore-precheck/scripts/semantic/engine.py +165 -127
  57. package/skills/appstore-precheck/scripts/semantic/questions.py +5 -1
  58. package/skills/appstore-precheck/scripts/semantic/review_v4.py +81 -0
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env python3
2
+ """Conservative D12-D17 observations; incomplete evidence always abstains.
3
+
4
+ Capture and MusicKit checks establish positive observations only. Missing visual
5
+ or OS evidence is never proof that a warning or authorization was omitted.
6
+ """
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+ import statistics
11
+
12
+ RULES = {'dyn-cpu-idle': '2.4.2', 'dyn-capture-indicator': '2.5.14',
13
+ 'dyn-musickit-auth': '4.5.2', 'dyn-miniapp-index': '4.7.4',
14
+ 'dyn-miniapp-rating-label': '4.7.5', 'dyn-location-timing': '5.1.5'}
15
+
16
+
17
+ def evaluate(rule, obs):
18
+ if not isinstance(obs, dict):
19
+ return 'SKIP', 'Malformed observation'
20
+ if not obs.get('applicable'):
21
+ return 'SKIP', 'No applicable shipped or source signal was established'
22
+ if not obs.get('usable'):
23
+ return 'SKIP', obs.get('reason', 'Missing, timed-out or degenerate observation')
24
+ if rule == 'dyn-cpu-idle':
25
+ samples = obs.get('samples', [])
26
+ if not obs.get('pid_verified') or obs.get('idle_seconds', 0) < 20 or len(samples) != 3:
27
+ return 'SKIP', 'Need a verified app process and three samples after 20 idle seconds'
28
+ if any(not isinstance(x, (int, float)) or isinstance(x, bool) or not 0 <= x <= 10000 for x in samples):
29
+ return 'SKIP', 'CPU samples are invalid'
30
+ median = statistics.median(samples)
31
+ return ('FINDING' if median > 40 else 'PASS'), 'Observed idle process CPU median %.1f%% (advisory)' % median
32
+ if rule == 'dyn-miniapp-index':
33
+ if obs.get('directory_heading') and obs.get('directory_unavailable'):
34
+ return 'FINDING', 'Observed mini-app directory explicitly reported unavailable; scope is this screen'
35
+ if obs.get('directory_heading') and obs.get('visible_items', 0):
36
+ return 'PASS', 'Mini-app directory and entries observed on the captured screen'
37
+ return 'SKIP', 'Partial exploration cannot establish absence of a directory'
38
+ if rule == 'dyn-miniapp-rating-label':
39
+ total = obs.get('fully_visible_items', 0)
40
+ if not obs.get('directory_heading') or not total:
41
+ return 'SKIP', 'No fully visible mini-app entries with readable geometry were captured'
42
+ missing = total - obs.get('rated_items', 0)
43
+ return ('FINDING' if missing > 0 else 'PASS'), '%d/%d fully visible entries lacked an accessible age label; inspect screenshots' % (missing, total)
44
+ if rule == 'dyn-location-timing':
45
+ if obs.get('os_prompt') != 'location':
46
+ return 'SKIP', 'No location alert with verified OS ownership and alert class was captured'
47
+ if obs.get('prompt_phase') == 'launch' and obs.get('app_context_observed'):
48
+ return 'FINDING', 'OS location permission appeared before any user action; app purpose and request justification were not assessed (timing observation only)'
49
+ if obs.get('prompt_phase') == 'action' and obs.get('location_context'):
50
+ return 'PASS', 'OS location permission followed an explicit location action'
51
+ return 'SKIP', 'Location prompt observed, but its request context is ambiguous'
52
+ return observe_only(rule, obs)
53
+
54
+
55
+ def observe_only(rule, obs):
56
+ if rule == 'dyn-musickit-auth':
57
+ if obs.get('flow_triggered') and obs.get('os_prompt') == 'music':
58
+ return 'PASS', 'OS media-library authorization alert observed after an explicit music action'
59
+ return 'SKIP', 'Music authorization absence is inconclusive; library access was not independently established'
60
+ if rule == 'dyn-capture-indicator':
61
+ required = ('flow_triggered', 'new_indicator_frame', 'status_indicator', 'screenshots_verified')
62
+ if all(obs.get(k) for k in required):
63
+ return 'PASS', 'New app recording frame and OS status indicator observed with before/after screenshots'
64
+ return 'SKIP', 'Recording indicators require OS status-bar geometry and a new labelled app frame; missing evidence needs vision review'
65
+ return 'SKIP', 'Unknown check'
66
+
67
+
68
+ def aggregate(repeats, rule):
69
+ ids = [r.get('repeat') for r in repeats]
70
+ valid = all(isinstance(x, int) and not isinstance(x, bool) and x > 0 for x in ids)
71
+ valid = valid and all(r.get('fresh') is True and isinstance(r.get('observations'), dict) for r in repeats)
72
+ if len(repeats) < 3 or not valid or len(set(ids)) != len(ids):
73
+ return 'SKIP', 'Need at least three distinct observations on freshly erased owned devices'
74
+ votes = [evaluate(rule, r.get('observations', {}).get(rule, {})) for r in repeats]
75
+ kinds = [v[0] for v in votes]
76
+ if len(set(kinds)) == 1 and kinds[0] != 'SKIP':
77
+ return kinds[0], 'quorum %d/%d; fresh erase verified; %s' % (len(votes), len(votes), votes[-1][1])
78
+ return 'SKIP', 'No unanimous complete observations (PASS=%d FINDING=%d SKIP=%d); %s' % (kinds.count('PASS'), kinds.count('FINDING'), kinds.count('SKIP'), votes[-1][1])
79
+
80
+
81
+ def read_repeats(path, expected):
82
+ if path.is_dir():
83
+ repeats = []
84
+ for number in range(1, expected + 1):
85
+ try:
86
+ record = json.loads((path / ('repeat-%d.json' % number)).read_text())
87
+ if not isinstance(record, dict) or record.get('repeat') != number:
88
+ raise ValueError('invalid repeat')
89
+ except (OSError, ValueError):
90
+ record = {'repeat': number, 'fresh': False, 'observations': {}}
91
+ repeats.append(record)
92
+ return repeats
93
+ try:
94
+ records = json.loads(path.read_text())
95
+ return records if isinstance(records, list) and all(isinstance(r, dict) for r in records) else []
96
+ except (OSError, ValueError):
97
+ return []
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument('observations', type=Path)
103
+ parser.add_argument('--expected', type=int, default=0)
104
+ args = parser.parse_args()
105
+ repeats = read_repeats(args.observations, args.expected)
106
+ for rule, guideline in RULES.items():
107
+ kind, message = aggregate(repeats, rule)
108
+ print('DYNAMIC-%s: %s [%s] — %s' % (kind, guideline, rule, message))
109
+
110
+
111
+ if __name__ == '__main__':
112
+ main()
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env bash
2
+ # Additional observations are collected only after a verified owned fresh erase.
3
+ # Dependencies: HERE, UDID/BID/INSTALLED/EXE/REPO, OUT and the runner's emit helper.
4
+ dyn_extended_capture() {
5
+ local folder="$DYN_EXT_DIR/repeat-$1" pid="" tree="$OUT/hierarchy-$1.json"
6
+ mkdir "$folder" || return 0
7
+ [[ -f "$DYN_EXT_DIR/pid-$1.txt" ]] && pid="$(cat "$DYN_EXT_DIR/pid-$1.txt")"
8
+ [[ "${LAST_SIGNALS##*,}" != unread ]] || tree="$folder/unavailable.json"
9
+ python3 -B "$HERE/lib/dyn-process.py" --timeout 240 --grace 1 -- \
10
+ python3 -B "$HERE/lib/dyn-guideline-capture.py" \
11
+ --udid "$UDID" --bundle-id "$BID" --app "$INSTALLED" --executable "$EXE" \
12
+ --pid "$pid" --initial-tree "$tree" --repo "$REPO" \
13
+ --out "$folder" --repeat "$1" --fresh-owned > "$DYN_EXT_DIR/repeat-$1.json" 2> "$DYN_EXT_DIR/repeat-$1.stderr.log" || {
14
+ printf 'Additional observation collector failed; see %s\n' "$DYN_EXT_DIR/repeat-$1.stderr.log" >&2
15
+ }
16
+ }
17
+
18
+ dyn_extended_report() {
19
+ local line
20
+ while IFS= read -r line; do emit "$line"; done < <(
21
+ python3 -B "$HERE/lib/dyn-guidelines.py" "$DYN_EXT_DIR" --expected "$REPEATS"
22
+ )
23
+ }
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env python3
2
+ """Bounded POSIX driver process groups; terminate descendants on cancel/deadline."""
3
+ import argparse
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+
9
+
10
+ DEFAULT_GRACE = 15
11
+
12
+
13
+ def stop(proc, grace=DEFAULT_GRACE):
14
+ """TERM the whole group, wait ``grace`` seconds for cleanup, then KILL it."""
15
+ try:
16
+ os.killpg(proc.pid, signal.SIGTERM)
17
+ except ProcessLookupError:
18
+ return
19
+ try:
20
+ proc.wait(timeout=grace)
21
+ except subprocess.TimeoutExpired:
22
+ pass
23
+ # The group leader may exit while its child ignores TERM.
24
+ try:
25
+ os.killpg(proc.pid, signal.SIGKILL)
26
+ except ProcessLookupError:
27
+ pass
28
+ proc.wait()
29
+
30
+
31
+ def run(argv, timeout, grace=DEFAULT_GRACE, **kwargs):
32
+ try:
33
+ proc = subprocess.Popen(argv, start_new_session=True, **kwargs)
34
+ except FileNotFoundError as exc:
35
+ error = str(exc) if kwargs.get('text') else str(exc).encode()
36
+ return subprocess.CompletedProcess(argv, 127, '' if kwargs.get('text') else b'', error)
37
+ previous = {}
38
+ def cancelled(signum, _frame):
39
+ raise InterruptedError(signum, 'Driver cancelled')
40
+ try:
41
+ for sig in (signal.SIGINT, signal.SIGTERM):
42
+ previous[sig] = signal.signal(sig, cancelled)
43
+ stdout, stderr = proc.communicate(timeout=timeout)
44
+ return subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr)
45
+ except BaseException:
46
+ # Do not let a second cancellation interrupt artifact/device cleanup.
47
+ for sig in previous:
48
+ signal.signal(sig, signal.SIG_IGN)
49
+ stop(proc, grace)
50
+ raise
51
+ finally:
52
+ for sig, handler in previous.items():
53
+ signal.signal(sig, handler)
54
+
55
+
56
+ def main():
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument('--timeout', type=float, required=True)
59
+ parser.add_argument('--grace', type=float, default=DEFAULT_GRACE,
60
+ help='seconds between TERM and KILL when the deadline expires')
61
+ parser.add_argument('command', nargs=argparse.REMAINDER)
62
+ args = parser.parse_args()
63
+ argv = args.command[1:] if args.command[:1] == ['--'] else args.command
64
+ if args.timeout <= 0 or args.grace <= 0 or not argv:
65
+ parser.error('positive deadline, grace and command required')
66
+ try:
67
+ return run(argv, args.timeout, args.grace).returncode
68
+ except subprocess.TimeoutExpired:
69
+ return 124
70
+ except InterruptedError:
71
+ return 143
72
+
73
+
74
+ if __name__ == '__main__':
75
+ sys.exit(main())
@@ -6,16 +6,15 @@
6
6
  # not prose. Sourced by dynamic-run.sh. Bash 3.2 compatible.
7
7
  #
8
8
  # POLICY (from the Phase 2 contract)
9
- # * N=3 repeats, each on a freshly erased device. A FINDING needs 3/3; a mixed
10
- # result is a FINDING line carrying its ratio ("crashed on 2 of 3 launches") —
11
- # recorded as WARN by dynamic.sh like every FINDING, and never eligible for the
12
- # Phase 3 blocking channel, which reads the ratio.
9
+ # * N=3 repeats, each on a freshly erased device. A FINDING needs 3/3; mixed or incomplete
10
+ # observations are SKIP, with their counts preserved for human review.
13
11
  # * A driver timeout or an unreadable run is a SKIP for that repeat, never a
14
12
  # FINDING. If every repeat was a SKIP, the check is a SKIP.
15
- # * Launch health is a CONJUNCTION of four signals: process alive, screenshot not
13
+ # * Launch evidence combines four signals: process alive, screenshot not
16
14
  # uniform, no crash in the log stream, accessibility tree size. A signal that
17
15
  # could not be read is named in the line. A degenerate tree (Flutter / Compose)
18
- # is never a failure on its own.
16
+ # is never a failure on its own. A flat screenshot alone is not a crash.
17
+ # A clean log alone cannot establish a successful launch.
19
18
 
20
19
  # dyn_launch_verdict <process> <screenshot> <log> <tree>
21
20
  # process: alive | dead | unread
@@ -25,9 +24,9 @@
25
24
  # -> "<PASS|FINDING|SKIP><TAB><detail>"
26
25
  dyn_launch_verdict() {
27
26
  local proc="${1:-unread}" shot="${2:-unread}" log="${3:-unread}" tree="${4:-unread}"
28
- local unread="" fail="" ok="" degenerate=""
27
+ local unread="" fail="" ok="" degenerate="" positive=0
29
28
  case "$proc" in
30
- alive) ok="process alive" ;;
29
+ alive) ok="process alive"; positive=1 ;;
31
30
  dead) fail="process gone" ;;
32
31
  *) unread="process state" ;;
33
32
  esac
@@ -37,14 +36,15 @@ dyn_launch_verdict() {
37
36
  *) unread="${unread:+$unread, }log stream" ;;
38
37
  esac
39
38
  case "$shot" in
40
- varied) ok="${ok:+$ok, }screenshot not uniform" ;;
41
- uniform) fail="${fail:+$fail, }screenshot is a single flat colour" ;;
39
+ varied) ok="${ok:+$ok, }screenshot not uniform"; positive=1 ;;
40
+ uniform) unread="${unread:+$unread, }flat screenshot (first-screen review required)" ;;
42
41
  *) unread="${unread:+$unread, }screenshot" ;;
43
42
  esac
44
43
  case "$tree" in
45
44
  unread|"") unread="${unread:+$unread, }accessibility tree" ;;
46
- *) if [[ "$tree" =~ ^[0-9]+$ ]] && (( tree <= 3 )); then degenerate="accessibility tree has $tree node(s) (degenerate: Flutter/Compose expose no semantics; not a failure on its own)"
47
- else ok="${ok:+$ok, }accessibility tree $tree nodes"; fi ;;
45
+ *) if [[ ! "$tree" =~ ^[0-9]+$ ]]; then unread="${unread:+$unread, }accessibility tree"
46
+ elif (( tree <= 3 )); then degenerate="accessibility tree has $tree node(s) (degenerate: Flutter/Compose expose no semantics; not a failure on its own)"
47
+ else ok="${ok:+$ok, }accessibility tree $tree nodes"; positive=1; fi ;;
48
48
  esac
49
49
  local detail=""
50
50
  if [[ -n "$fail" ]]; then
@@ -53,8 +53,10 @@ dyn_launch_verdict() {
53
53
  [[ -n "$unread" ]] && detail="$detail ($unread could not be read)"
54
54
  printf 'FINDING\t%s\n' "$detail"; return 0
55
55
  fi
56
- if [[ -z "$ok" ]]; then
57
- detail="no signal could be read${unread:+: $unread}"
56
+ if (( positive == 0 )) || [[ "$shot" == uniform ]]; then
57
+ detail="launch health inconclusive${ok:+; $ok}"
58
+ [[ -n "$degenerate" ]] && detail="$detail; $degenerate"
59
+ [[ -n "$unread" ]] && detail="$detail ($unread could not be read)"
58
60
  printf 'SKIP\t%s\n' "$detail"; return 0
59
61
  fi
60
62
  detail="$ok"
@@ -63,30 +65,26 @@ dyn_launch_verdict() {
63
65
  printf 'PASS\t%s\n' "$detail"
64
66
  }
65
67
 
66
- # dyn_quorum <pass> <finding> <skip> — fold N repeat verdicts into one.
67
- # -> "<PASS|FINDING|SKIP><TAB><detail>". FINDING only when every readable repeat
68
- # failed AND at least the full N failed; a mixed result is a FINDING with its ratio
69
- # (advisory, non-unanimous); all-SKIP is a SKIP.
68
+ # dyn_quorum <pass> <finding> <skip>: conclusions need three observed repeats.
69
+ # Mixed evidence and incomplete runs stay SKIP with counts for human review.
70
70
  dyn_quorum() {
71
71
  local pass="${1:-0}" finding="${2:-0}" skip="${3:-0}" n
72
72
  n=$((pass + finding + skip))
73
- if (( n == 0 )) || (( skip == n )); then
74
- printf 'SKIP\tno repeat could be driven (%d of %d skipped)\n' "$skip" "$n"; return 0
75
- fi
76
- if (( finding == n )); then
77
- printf 'FINDING\tquorum %d/%d: failed on every launch\n' "$finding" "$n"; return 0
78
- fi
79
- if (( finding > 0 )); then
80
- printf 'FINDING\tquorum %d/%d: failed on %d of %d launches (not unanimous; advisory, never blocking)%s\n' \
81
- "$finding" "$n" "$finding" "$n" "$( (( skip > 0 )) && printf '; %d could not be driven' "$skip")"; return 0
73
+ if (( n >= 3 && finding == n )); then
74
+ printf 'FINDING\tquorum %d/%d: failed on every launch\n' "$finding" "$n"
75
+ elif (( n >= 3 && pass == n )); then
76
+ printf 'PASS\tquorum %d/%d passed\n' "$pass" "$n"
77
+ else
78
+ printf 'SKIP\tquorum %d/%d failures, %d passed, %d skipped; at least three unanimous observations required\n' "$finding" "$n" "$pass" "$skip"
82
79
  fi
83
- printf 'PASS\tquorum %d/%d passed%s\n' "$pass" "$n" "$( (( skip > 0 )) && printf ' (%d of %d could not be driven)' "$skip" "$n")"
84
80
  }
85
81
 
86
- # dyn_line <PASS|FINDING|SKIP> <guideline> <rule-id> <message> -> one transcript line
87
- # in the grammar dynamic.sh parses (column 0, id in brackets, em-dash separator).
82
+ # Strip control characters from untrusted bundle names, ids and diagnostic text.
88
83
  dyn_line() {
89
84
  local kind="$1" guideline="$2" id="$3" msg="$4"
90
85
  case "$kind" in PASS|FINDING|SKIP) ;; *) kind=SKIP ;; esac
86
+ guideline="$(printf '%s' "$guideline" | LC_ALL=C tr '[:cntrl:]' ' ')"
87
+ id="$(printf '%s' "$id" | LC_ALL=C tr '[:cntrl:]' ' ')"
88
+ msg="$(printf '%s' "$msg" | LC_ALL=C tr '[:cntrl:]' ' ')"
91
89
  printf 'DYNAMIC-%s: %s [%s] — %s\n' "$kind" "$guideline" "$id" "$msg"
92
90
  }
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env python3
2
+ """Redact runtime hierarchies before any persistent write; raw trees stay in memory."""
3
+ import argparse
4
+ import importlib.util
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import subprocess
10
+
11
+ EMAIL = re.compile(r'[A-Za-z0-9.!#$%&\x27*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+')
12
+ STRUCTURAL = {'bounds', 'type', 'class', 'packageName', 'bundleId'}
13
+
14
+
15
+ def sibling(name):
16
+ spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + '.py'))
17
+ module = importlib.util.module_from_spec(spec)
18
+ spec.loader.exec_module(module)
19
+ return module
20
+
21
+
22
+ def scrub_text(value):
23
+ for key in ('USERNAME', 'PASSWORD'):
24
+ secret = os.getenv('PRECHECK_DEMO_' + key, '')
25
+ if secret:
26
+ value = value.replace(secret, '[redacted]')
27
+ return EMAIL.sub('[redacted email]', value)
28
+
29
+
30
+ def scrub_tree(value, authenticated=False, allowed=None, key=''):
31
+ allowed = allowed or set()
32
+ if isinstance(value, str):
33
+ clean = scrub_text(value)
34
+ if authenticated and key not in STRUCTURAL and clean not in allowed:
35
+ return '[redacted]'
36
+ return clean
37
+ if isinstance(value, list):
38
+ return [scrub_tree(x, authenticated, allowed, key) for x in value]
39
+ if isinstance(value, dict):
40
+ return {scrub_text(k): scrub_tree(v, authenticated, allowed, k) for k, v in value.items()}
41
+ return value
42
+
43
+
44
+ def count_nodes(value):
45
+ if isinstance(value, list):
46
+ return sum(count_nodes(x) for x in value)
47
+ if isinstance(value, dict):
48
+ return int('attributes' in value) + sum(count_nodes(x) for x in value.get('children', []))
49
+ return 0
50
+
51
+
52
+ def capture(udid, out, timeout):
53
+ result = sibling('dyn-process').run(['maestro', '--device', udid, 'hierarchy'],
54
+ timeout=timeout, grace=1, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
55
+ if result.returncode:
56
+ raise ValueError('Hierarchy driver failed')
57
+ tree = scrub_tree(json.loads(result.stdout.decode('utf-8')))
58
+ sibling('safe_write').write_text(out, json.dumps(tree, ensure_ascii=True))
59
+ return count_nodes(tree)
60
+
61
+
62
+ def main():
63
+ parser = argparse.ArgumentParser()
64
+ parser.add_argument('--udid', required=True)
65
+ parser.add_argument('--out', type=Path, required=True)
66
+ parser.add_argument('--timeout', type=float, default=45)
67
+ args = parser.parse_args()
68
+ try:
69
+ print(capture(args.udid, args.out, args.timeout))
70
+ except (OSError, ValueError, subprocess.SubprocessError):
71
+ print('unread')
72
+ return 1
73
+ return 0
74
+
75
+
76
+ if __name__ == '__main__':
77
+ raise SystemExit(main())
@@ -94,8 +94,7 @@ dyn_signal_tree() {
94
94
  local udid="$1" out="$2" n
95
95
  if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "maestro --device $udid hierarchy > $out # one Maestro invocation, one flow"; echo unread; return 0; fi
96
96
  command -v maestro >/dev/null 2>&1 || { echo unread; return 0; }
97
- dyn_with_timeout "$DYN_MAESTRO_TIMEOUT" sh -c 'maestro --device "$1" hierarchy > "$2" 2>/dev/null' _ "$udid" "$out" || { echo unread; return 0; }
98
- n="$(jq '[.. | objects | select(has("attributes"))] | length' "$out" 2>/dev/null)" || { echo unread; return 0; }
97
+ n="$(python3 -B "$DYN_LIB_DIR/dyn-scrub.py" --udid "$udid" --out "$out" --timeout "$DYN_MAESTRO_TIMEOUT")" || { echo unread; return 0; }
99
98
  [[ "$n" =~ ^[0-9]+$ ]] && echo "$n" || echo unread
100
99
  }
101
100
 
@@ -108,6 +107,7 @@ dyn_repeat() {
108
107
  : > "$marker"; : > "$log"
109
108
  dyn_log_start "$udid" "$exe" "$bid" "$log"
110
109
  pid="$(dyn_launch "$udid" "$bid")"
110
+ [[ -z "${DYN_EXT_DIR:-}" ]] || printf '%s\n' "$pid" > "$DYN_EXT_DIR/pid-$i.txt"
111
111
  if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "sleep $window # observation window, repeat $i"; else sleep "$window"; fi
112
112
  proc="$(dyn_signal_process "$pid")"
113
113
  shot="$(dyn_signal_screenshot "$udid" "$png")"