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,177 @@
1
+ """Explicit build tier, operating exclusively in a disposable project copy."""
2
+ import argparse
3
+ import importlib.util
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ import time
12
+
13
+
14
+ def module(name):
15
+ spec = importlib.util.spec_from_file_location(name.replace('-', '_'), Path(__file__).with_name(name + '.py'))
16
+ value = importlib.util.module_from_spec(spec); spec.loader.exec_module(value)
17
+ return value
18
+
19
+
20
+ PLAN, EXEC, EVIDENCE = module('build-plan'), module('build-exec'), module('build-evidence')
21
+
22
+
23
+ def arguments():
24
+ parser = argparse.ArgumentParser(description=__doc__)
25
+ parser.add_argument('--repo', type=Path, default=Path('.'))
26
+ parser.add_argument('--out', type=Path)
27
+ parser.add_argument('--framework', choices=['native', 'rn', 'flutter', 'kmp'])
28
+ parser.add_argument('--platform', default='ios')
29
+ parser.add_argument('--timeout', type=int, default=1200)
30
+ parser.add_argument('--deadline', type=int, default=2400)
31
+ parser.add_argument('--dry-run', action='store_true')
32
+ return parser.parse_args()
33
+
34
+
35
+ def scheme_list(output):
36
+ schemes = set()
37
+ decoder = json.JSONDecoder()
38
+ for index, char in enumerate(output):
39
+ if char != '{':
40
+ continue
41
+ try:
42
+ data, _ = decoder.raw_decode(output[index:])
43
+ except ValueError:
44
+ continue
45
+ if isinstance(data, dict):
46
+ for value in data.values():
47
+ if isinstance(value, dict) and isinstance(value.get('schemes'), list):
48
+ schemes.update(s for s in value['schemes'] if isinstance(s, str))
49
+ return sorted(schemes)
50
+
51
+
52
+ def prepare_framework(args, copy, step):
53
+ if args.framework != 'rn':
54
+ return
55
+ choices = [('pnpm-lock.yaml', ['pnpm', 'i', '--frozen-lockfile']), ('yarn.lock', ['yarn', '--frozen-lockfile']),
56
+ ('package-lock.json', ['npm', 'ci']), ('npm-shrinkwrap.json', ['npm', 'ci'])]
57
+ command = next((command for file, command in choices if (copy / file).is_file()), None)
58
+ if command is None:
59
+ raise ValueError('React Native requires a reproducible package-manager lockfile')
60
+ if step(command)[0]:
61
+ raise ValueError('dependency installation failed; inspect build.log')
62
+ data = json.loads((copy / 'package.json').read_text()) if (copy / 'package.json').is_file() else {}
63
+ expo = 'expo' in dict(data.get('dependencies', {}), **data.get('devDependencies', {}))
64
+ if expo and step(['npx', 'expo', 'prebuild', '--platform', 'ios', '--no-install'])[0]:
65
+ raise ValueError('Expo prebuild failed; inspect build.log')
66
+ if (copy / 'ios/Podfile').is_file() and step(['pod', 'install', '--project-directory=ios'])[0]:
67
+ raise ValueError('pod installation failed; inspect build.log')
68
+
69
+
70
+ def run_steps(args, copy, work, out, project):
71
+ end = time.monotonic() + args.deadline
72
+ def step(command):
73
+ remaining = min(args.timeout, end - time.monotonic())
74
+ if remaining <= 0:
75
+ raise ValueError('build deadline exceeded')
76
+ return EXEC.execute(command, copy, work / 'home', out / 'build.log', remaining)
77
+ prepare_framework(args, copy, step)
78
+ found = PLAN.projects(copy)
79
+ if args.framework == 'rn' and len(found) != 1:
80
+ raise ValueError('generated project selection is ambiguous: ' + ', '.join(found))
81
+ project = found[0] if found else project
82
+ flags = [] if project == 'Package.swift' else ['-workspace' if project.endswith('.xcworkspace') else '-project', project]
83
+ if args.framework == 'flutter':
84
+ for command in (['flutter', 'pub', 'get'], ['flutter', 'build', 'ios', '--simulator']):
85
+ if step(command)[0]:
86
+ raise ValueError('Flutter command failed; inspect build.log')
87
+ return 'debug', list((copy / 'build/ios/iphonesimulator').glob('*.app'))
88
+ code, output = step(['xcodebuild', '-list', '-json'] + flags)
89
+ if code:
90
+ raise ValueError('scheme discovery failed; inspect build.log')
91
+ schemes = scheme_list(output)
92
+ if len(schemes) != 1:
93
+ raise ValueError('select one shared scheme; candidates: ' + ', '.join(schemes))
94
+ for config in ('Release', 'Debug'):
95
+ if config == 'Debug' and args.framework == 'kmp' and (copy / 'gradlew').is_file():
96
+ if step(['./gradlew', '--project-cache-dir', str(work / 'gradle-cache'), ':shared:linkDebugFrameworkIosSimulatorArm64'])[0]:
97
+ raise ValueError('KMP framework preparation failed; inspect build.log')
98
+ command = ['xcodebuild'] + flags + ['-scheme', schemes[0], '-sdk', 'iphonesimulator', '-configuration', config,
99
+ '-derivedDataPath', str(work / 'dd'), 'CODE_SIGNING_ALLOWED=NO', 'build']
100
+ if step(command)[0] == 0:
101
+ return config.lower(), list((work / 'dd/Build/Products' / (config + '-iphonesimulator')).glob('*.app'))
102
+ raise ValueError('Release and Debug build failed; inspect build.log')
103
+
104
+
105
+ def build(args, repo, project, out):
106
+ before = EVIDENCE.snapshot(repo)
107
+ config, exported = 'unknown', None
108
+ try:
109
+ with tempfile.TemporaryDirectory(prefix='precheck-build-') as temporary:
110
+ work = Path(temporary); copy = work / 'project'
111
+ PLAN.copy_inputs(repo, copy)
112
+ config, apps = run_steps(args, copy, work, out, project)
113
+ if len(apps) != 1 or not (apps[0] / 'Info.plist').is_file():
114
+ raise ValueError('build must produce exactly one simulator .app')
115
+ exported = out / (config.title() + '-iphonesimulator') / apps[0].name
116
+ exported.parent.mkdir(parents=True, exist_ok=True)
117
+ shutil.copytree(apps[0], exported)
118
+ print('app_path=' + str(exported))
119
+ print('build_config=' + config)
120
+ finally:
121
+ if not EVIDENCE.finish(repo, before, out, config, exported):
122
+ raise ValueError('source changed during build; evidence is not bound')
123
+
124
+
125
+ def interrupted(signum, frame):
126
+ raise KeyboardInterrupt()
127
+
128
+
129
+ def project_candidates(repo, framework):
130
+ projects = PLAN.projects(repo)
131
+ if framework == 'flutter' or len(projects) == 1:
132
+ return projects
133
+ if framework == 'rn' and not projects and (repo / 'package.json').is_file():
134
+ data = json.loads((repo / 'package.json').read_text())
135
+ if 'expo' in dict(data.get('dependencies', {}), **data.get('devDependencies', {})):
136
+ return []
137
+ raise ValueError('select one Xcode project/workspace; candidates: ' + ', '.join(projects))
138
+
139
+
140
+ def main():
141
+ args = arguments(); repo = args.repo.resolve()
142
+ home = Path.home().resolve()
143
+ if repo in (Path('/'), home) or repo in home.parents or args.timeout < 1 or args.deadline < 1:
144
+ print('build-run: unsafe repository or invalid timeout', file=sys.stderr); return 64
145
+ if not repo.is_dir():
146
+ print('build-run: repository missing', file=sys.stderr); return 66
147
+ if args.framework is None:
148
+ args.framework = subprocess.check_output(['bash', str(Path(__file__).resolve().parents[1] / 'framework-detect.sh'), '--root', str(repo)], text=True).strip() or 'native'
149
+ try:
150
+ if args.platform != 'ios':
151
+ raise ValueError('platform not audited: ' + args.platform)
152
+ projects = project_candidates(repo, args.framework)
153
+ PLAN.checked_links(repo)
154
+ if args.dry_run:
155
+ print('PLAN: isolated copy; Release then Debug; CODE_SIGNING_ALLOWED=NO; project=' + ', '.join(projects)); return 0
156
+ tool = 'flutter' if args.framework == 'flutter' else 'xcodebuild'
157
+ if not shutil.which(tool) or not shutil.which('rsync'):
158
+ raise ValueError(tool + '/rsync unavailable; install tools or provide an existing .app')
159
+ out = args.out.resolve() if args.out else Path(tempfile.mkdtemp(prefix='precheck-artifact-'))
160
+ if out == repo or repo in out.parents:
161
+ raise ValueError('--out must be outside the source project')
162
+ if repo == Path(tempfile.gettempdir()).resolve() or repo in Path(tempfile.gettempdir()).resolve().parents:
163
+ raise ValueError('temporary directory must be outside source project')
164
+ out.mkdir(parents=True, exist_ok=True)
165
+ print('artifact_dir=' + str(out))
166
+ for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
167
+ signal.signal(sig, interrupted)
168
+ build(args, repo, projects[0] if projects else '', out)
169
+ return 0
170
+ except KeyboardInterrupt:
171
+ print('SKIP: build interrupted'); return 130
172
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
173
+ print('SKIP: build-run — ' + str(exc)); return 3
174
+
175
+
176
+ if __name__ == '__main__':
177
+ raise SystemExit(main())
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env bash
2
+ # Append static run coverage; optional tier summaries are reported separately.
3
+ coverage_run_json() {
4
+ jq --argjson gaps "${COVERAGE_GAPS_JSON:-[]}" --slurpfile baseline "$SCRIPT_DIR/../guidelines-baseline.json" '
5
+ ($baseline[0]) as $b
6
+ | ($b.all_sections | map(. as $s
7
+ | select(any($b.all_sections[]; startswith($s + ".")) | not)
8
+ | select($b.not_counted[.] == null))) as $leaves
9
+ | ([.findings[] | select(.severity == "WARN" or .severity == "FAIL") | .guideline
10
+ | split("(")[0] | select(. as $s | $leaves | index($s))] | unique) as $touched
11
+ | ([.findings[] | select(.severity == "SKIP" and .rule_id != "modular-checks-not-audited")] | length) as $legacy
12
+ | ([$gaps[].guideline, (.findings[] | select(.severity == "SKIP") | .guideline)]
13
+ | map(split("(")[0]) | map(select(. as $s | $leaves | index($s))) | unique) as $skipped
14
+ | .summary.not_audited = ($legacy + ($gaps | length))
15
+ | . + {coverage_sections: {
16
+ denominator: ($leaves | length), touched: ($touched | length),
17
+ touched_sections: $touched, skip: ($skipped | length), skipped_sections: $skipped,
18
+ legacy_skip: $legacy, gaps: $gaps,
19
+ human_only: ($b.human_only | length), human_only_sections: $b.human_only,
20
+ not_run_routes: ["deep", "dynamic", "vision"],
21
+ scope: "Static issue sections only (PASS excluded); SKIP counts unique leaf sections. Input-gap records remain separately visible."
22
+ }}'
23
+ }
@@ -0,0 +1,250 @@
1
+ """Derive leaf coverage and check baseline claims against their maintained sources."""
2
+ import argparse
3
+ import ast
4
+ import json
5
+ import re
6
+ from pathlib import Path
7
+
8
+ ROUTES = {'scan': 'covered_by_scan', 'deep': 'covered_by_pierre_deep_review',
9
+ 'dynamic': 'covered_by_dynamic', 'vision': 'covered_by_vision'}
10
+ SECTION = re.compile(r'(?<![\w.])([1-5](?:\.\d+)+)(?![\w.])')
11
+
12
+ POSITIVE_ONLY_SOURCES = {'dyn-capture-indicator', 'dyn-musickit-auth'}
13
+
14
+
15
+ def order(section):
16
+ return tuple(int(n) for n in section.split('.'))
17
+
18
+
19
+ def add(mapping, guideline, source):
20
+ for section in SECTION.findall(guideline):
21
+ mapping.setdefault(section, set()).add(source)
22
+
23
+
24
+ def scan_sources(skill):
25
+ scripts = skill / 'scripts'
26
+ slugs = dict((slug, int(number)) for number, slug in re.findall(
27
+ r'(\d+)\)\s+echo ([\w-]+)', (scripts / 'findings.sh').read_text()))
28
+ entry = (scripts / 'scan.sh').read_text()
29
+ # Only direct, literal source calls participate. A dormant scan-*.sh is not a check.
30
+ modules = re.findall(r'^\s*(?:source|\.) "\$SCRIPT_DIR/(lib/scan-[\w-]+\.sh)"', entry, re.M)
31
+ result = {}
32
+ for text in [entry] + [(scripts / name).read_text() for name in modules]:
33
+ text = '\n'.join(line for line in text.splitlines() if not line.lstrip().startswith('#'))
34
+ table = re.search(r"done <<'STATIC_GUIDELINE_TABLE'\n(.*?)\nSTATIC_GUIDELINE_TABLE", text, re.S)
35
+ if table:
36
+ for slug, guideline, evidence in re.findall(
37
+ r'^([\w-]+)\|([1-5](?:\.\d+)+)\|(source|metadata|resource)$', table[1], re.M):
38
+ if slug in slugs:
39
+ add(result, guideline, '§%d' % slugs[slug])
40
+ chunks = re.split(r'set_rule "([\w-]*)"', text)
41
+ for index in range(1, len(chunks), 2):
42
+ slug = chunks[index]
43
+ if slug not in slugs:
44
+ continue
45
+ for message in re.findall(r'\b(?:fail|warn|pass)\s+"((?:[^"\\]|\\.)*)"', chunks[index + 1]):
46
+ add(result, message, '§%d' % slugs[slug])
47
+ return result, len(slugs)
48
+
49
+
50
+ def table_sources(path, dynamic=False):
51
+ result, ids = {}, set()
52
+ for line in path.read_text().splitlines():
53
+ cells = [cell.strip() for cell in line.split('|')]
54
+ if dynamic and len(cells) >= 6 and re.fullmatch(r'D\d+[a-z]?', cells[1]):
55
+ names = re.findall(r'`(dyn-[\w-]+)', cells[2])
56
+ for name in names:
57
+ if name != 'dyn-install':
58
+ add(result, cells[3], name)
59
+ ids.add(name)
60
+ elif not dynamic and len(cells) >= 5 and re.fullmatch(r'S\d+', cells[1]):
61
+ name = 'vision-' + cells[1]
62
+ add(result, cells[2], name)
63
+ ids.add(name)
64
+ return result, ids
65
+
66
+
67
+ def semantic_input_kinds(skill):
68
+ folder = skill / 'scripts/semantic'
69
+ tree = ast.parse((folder / 'collect.py').read_text())
70
+ function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'input_kinds')
71
+ # The collector returns literal kind lists; extract the actual return values.
72
+ kinds = {item.value for node in ast.walk(function) if isinstance(node, ast.Return)
73
+ for value in ast.walk(node) if isinstance(value, ast.List)
74
+ for item in value.elts if isinstance(item, ast.Constant) and isinstance(item.value, str)}
75
+ tree = ast.parse((folder / 'review_v4.py').read_text())
76
+ declaration = next(node for node in tree.body if isinstance(node, ast.Assign)
77
+ and any(isinstance(target, ast.Name) and target.id == 'HOST_INPUT_KINDS' for target in node.targets))
78
+ return kinds, set(ast.literal_eval(declaration.value))
79
+
80
+
81
+ def deep_check_errors(check, prose, cases, local_kinds, host_kinds):
82
+ prefix = 'deep-%d' % check['number']
83
+ errors = []
84
+ procedure = re.search(r'^### %d — .*?(?=^### |^---$|\Z)' % check['number'], prose, re.M | re.S)
85
+ if not procedure or check['question'] not in procedure[0] or len(procedure[0].strip().splitlines()) < 3:
86
+ errors.append(prefix + ' has no matching executable review procedure')
87
+ if not any(c.get('check_number') == check['number'] and c.get('check_key') == check['key']
88
+ and c.get('guideline') == check['guideline'] and c.get('text', '').strip()
89
+ and c.get('expected') in ('finding', 'no_signal', 'insufficient_evidence') for c in cases):
90
+ errors.append(prefix + ' has no matching labeled semantic fixture')
91
+ inputs = check.get('evidence_inputs', [])
92
+ if not inputs:
93
+ errors.append(prefix + ' has no declared evidence inputs')
94
+ for kind in inputs:
95
+ if kind not in local_kinds and not (kind in host_kinds and check.get('requires_vision')
96
+ and 'host_' + kind.replace('-', '_') in check.get('required_context', [])):
97
+ errors.append(prefix + ' cannot obtain evidence input: ' + kind)
98
+ return errors
99
+
100
+
101
+ def deep_sources(skill, catalog):
102
+ result, errors = {}, []
103
+ refs = skill / 'references'
104
+ prose = (refs / 'pierre-deep-review.md').read_text()
105
+ case_path = skill.parents[1] / 'corpus/synthetic/semantic-v4/cases.json'
106
+ try:
107
+ cases = json.loads(case_path.read_text())['cases']
108
+ local_kinds, host_kinds = semantic_input_kinds(skill)
109
+ except (OSError, ValueError, KeyError, StopIteration) as exc:
110
+ cases, local_kinds, host_kinds = [], set(), set()
111
+ errors.append('cannot validate semantic review inputs: ' + str(exc))
112
+ for check in catalog['checks']:
113
+ problems = deep_check_errors(check, prose, cases, local_kinds, host_kinds) if check['number'] >= 32 else []
114
+ errors.extend(problems)
115
+ if not problems:
116
+ add(result, check['guideline'], 'deep-%d' % check['number'])
117
+ return result, errors
118
+
119
+
120
+ def sources(skill):
121
+ scan, vectors = scan_sources(skill)
122
+ refs = skill / 'references'
123
+ catalog = json.loads((refs / 'review-catalog.json').read_text())
124
+ deep, deep_errors = deep_sources(skill, catalog)
125
+ dynamic, dynamic_ids = table_sources(refs / 'simulator-dynamic-review.md', True)
126
+ vision, vision_ids = table_sources(refs / 'screenshot-vision-review.md')
127
+ text = (skill / 'scripts/dynamic.sh').read_text()
128
+ body = re.search(r'dyn_catalogue\(\) \{(.*?)\n\}', text, re.S)
129
+ registered = set(re.findall(r'\bdyn-[\w-]+', body[1] if body else '')) - {'dyn-install'}
130
+ errors = deep_errors + ['dynamic table/catalog mismatch: ' + name for name in sorted(dynamic_ids ^ registered)]
131
+ numbers = [c['number'] for c in catalog['checks']]
132
+ keys = [c['key'] for c in catalog['checks']]
133
+ if len(numbers) != len(set(numbers)) or len(keys) != len(set(keys)):
134
+ errors.append('duplicate deep-review number/key')
135
+ return {'scan': scan, 'deep': deep, 'dynamic': dynamic, 'vision': vision}, {
136
+ 'static_vectors': vectors, 'deep_checks': len(numbers),
137
+ 'dynamic_checks': len(registered), 'vision_checks': len(vision_ids),
138
+ 'catalog_version': catalog['version']}, errors
139
+
140
+
141
+ def validate_baseline(base, evidence, errors):
142
+ all_sections = set(base['all_sections'])
143
+ if len(all_sections) != len(base['all_sections']):
144
+ errors.append('duplicate all_sections entry')
145
+ for field in ('not_counted', 'human_only'):
146
+ for section, reason in base[field].items():
147
+ if section not in all_sections or not isinstance(reason, str) or not reason.strip():
148
+ errors.append('%s invalid section/reason: %s' % (field, section))
149
+ for route, field in ROUTES.items():
150
+ entries = base[field]
151
+ if len(entries) != len(set(entries)):
152
+ errors.append('%s contains duplicate sections' % field)
153
+ for section in entries:
154
+ if section not in all_sections:
155
+ errors.append('%s unknown section: %s' % (field, section))
156
+ if section in base['human_only'] or section in base['not_counted']:
157
+ errors.append('%s excluded section claimed covered: %s' % (field, section))
158
+ if section not in evidence[route]:
159
+ errors.append('%s has no check source: %s' % (field, section))
160
+
161
+
162
+ def build_report(skill, base):
163
+ evidence, counts, errors = sources(skill)
164
+ validate_baseline(base, evidence, errors)
165
+ all_sections = set(base['all_sections'])
166
+ parents = {s for s in all_sections if any(t.startswith(s + '.') for t in all_sections)}
167
+ leaves = all_sections - parents - set(base['not_counted'])
168
+ if set(base['human_only']) - leaves:
169
+ errors.append('human_only contains non-leaf sections')
170
+ routes, combined, pointers = {}, set(), {}
171
+ for route, field in ROUTES.items():
172
+ # Invalid claims are shown as errors and never inflate the reported numerator.
173
+ touched = set(base[field]) & leaves & set(evidence[route])
174
+ touched -= set(base['human_only'])
175
+ routes[route] = {'covered': len(touched), 'sections': sorted(touched, key=order)}
176
+ combined |= touched
177
+ for section in touched:
178
+ pointers.setdefault(section, set()).update(evidence[route][section])
179
+ partial = sorted((s for s in pointers if pointers[s] <= POSITIVE_ONLY_SOURCES), key=order)
180
+ return dict(counts, denominator=len(leaves), covered=len(combined), touched=len(combined),
181
+ positive_only=len(partial), positive_only_sections=partial,
182
+ source_details=source_details(pointers),
183
+ percentage=round(100 * len(combined) / len(leaves)) if leaves else 0,
184
+ human_only=len(base['human_only']), human_only_sections=base['human_only'],
185
+ not_counted_count=len(base['not_counted']), not_counted=base['not_counted'],
186
+ parent_sections_count=len(parents), parent_sections=sorted(parents, key=order),
187
+ covered_sections=sorted(combined, key=order),
188
+ uncovered_sections=sorted(leaves - combined, key=order),
189
+ sources={s: sorted(pointers[s]) for s in sorted(pointers, key=order)},
190
+ routes=routes, errors=errors)
191
+
192
+
193
+ def source_details(pointers):
194
+ partial = 'partial (positive-only observation)'
195
+ normal = 'maintained check; evidence-dependent'
196
+ return {section: {'scope': partial if checks <= POSITIVE_ONLY_SOURCES else normal,
197
+ 'sources': [{'check': check, 'scope': partial if check in POSITIVE_ONLY_SOURCES else normal}
198
+ for check in sorted(checks)]}
199
+ for section, checks in sorted(pointers.items(), key=lambda pair: order(pair[0]))}
200
+
201
+
202
+ def summary_line(report):
203
+ return ('Coverage inventory: {covered}/{denominator} leaf sections ({percentage}%); '
204
+ '{touched} touched, {positive_only} positive-only; '
205
+ '{static_vectors} static vectors, {deep_checks} deep-review checks, '
206
+ '{dynamic_checks} dynamic checks, {vision_checks} vision checks, '
207
+ '{human_only} human-only sections.').format(**report)
208
+
209
+
210
+ def markdown(report):
211
+ lines = ['# Guideline section coverage', '',
212
+ 'Generated by `skills/appstore-precheck/scripts/coverage-sections.sh --markdown`.', '',
213
+ summary_line(report), '',
214
+ 'This percentage counts sections touched by maintained checks, not automated verification of all requirements.',
215
+ 'Routes overlap; advisory and vision checks require their evidence and may SKIP on a particular run.', '',
216
+ '| Route | Leaf sections |', '|---|---:|']
217
+ lines += ['| %s | %s |' % (route, entry['covered']) for route, entry in report['routes'].items()]
218
+ lines += ['', '## Covered sections and check sources', '', '| Section | Sources | Scope |', '|---|---|---|']
219
+ lines += ['| %s | %s | %s |' % (s, ', '.join(v), report['source_details'][s]['scope'])
220
+ for s, v in report['sources'].items()]
221
+ lines += ['', '## Not audited', '', 'Uncovered sections: ' + ', '.join(report['uncovered_sections']) + '.', '',
222
+ 'Human-only sections require external evidence or a human decision:', '']
223
+ lines += ['- %s: %s' % (s, reason) for s, reason in report['human_only_sections'].items()]
224
+ lines += ['', '## Denominator exclusions', '',
225
+ 'Parents (not inherited by their children): ' + ', '.join(report['parent_sections']) + '.', '']
226
+ lines += ['- %s: %s' % (s, reason) for s, reason in report['not_counted'].items()]
227
+ lines += ['', 'Cross-validation errors: %d.' % len(report['errors'])]
228
+ lines += ['- ' + e for e in report['errors']]
229
+ return '\n'.join(lines) + '\n'
230
+
231
+
232
+ def main():
233
+ parser = argparse.ArgumentParser(description=__doc__)
234
+ group = parser.add_mutually_exclusive_group()
235
+ group.add_argument('--json', action='store_true')
236
+ group.add_argument('--markdown', action='store_true')
237
+ parser.add_argument('--baseline', type=Path)
238
+ args = parser.parse_args()
239
+ skill = Path(__file__).resolve().parents[2]
240
+ try:
241
+ base = json.loads((args.baseline or skill / 'guidelines-baseline.json').read_text())
242
+ report = build_report(skill, base)
243
+ except (OSError, ValueError, KeyError, TypeError) as exc:
244
+ parser.exit(1, 'coverage-sections: cannot validate inputs: %s\n' % exc)
245
+ print(json.dumps(report, indent=2, ensure_ascii=False) if args.json else markdown(report), end='\n' if args.json else '')
246
+ return 1 if report['errors'] else 0
247
+
248
+
249
+ if __name__ == '__main__':
250
+ raise SystemExit(main())
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env python3
2
+ """Run one opt-in demo login attempt without writing credentials to reports."""
3
+ import importlib.util
4
+ import json
5
+ import os
6
+ import pathlib
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+
12
+
13
+ _spec = importlib.util.spec_from_file_location("dyn_process", pathlib.Path(__file__).with_name("dyn-process.py"))
14
+ _process = importlib.util.module_from_spec(_spec)
15
+ _spec.loader.exec_module(_process)
16
+ _scrub_spec = importlib.util.spec_from_file_location('dyn_scrub', pathlib.Path(__file__).with_name('dyn-scrub.py'))
17
+ _scrub = importlib.util.module_from_spec(_scrub_spec)
18
+ _scrub_spec.loader.exec_module(_scrub)
19
+
20
+
21
+
22
+ MAESTRO_EXPR = "${"
23
+
24
+
25
+ def hierarchy(udid, dirname, env):
26
+ result = _process.run(["maestro", "--device", udid, "hierarchy"],
27
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
28
+ timeout=45, cwd=dirname, env=env)
29
+ if result.returncode:
30
+ raise ValueError("Hierarchy unavailable")
31
+ tree = json.loads(result.stdout.decode("utf-8", "replace"))
32
+ # Selectors stay in memory; redact values without erasing secure-field labels.
33
+ values = set()
34
+ def visit(obj):
35
+ if isinstance(obj, dict):
36
+ attrs = obj.get("attributes", {})
37
+ if isinstance(attrs, dict):
38
+ values.update(_scrub.scrub_text(v.strip()) for k, v in attrs.items()
39
+ if k in ("text", "accessibilityText") and isinstance(v, str))
40
+ for child in obj.get("children", []):
41
+ visit(child)
42
+ elif isinstance(obj, list):
43
+ for child in obj:
44
+ visit(child)
45
+ visit(tree)
46
+ return values
47
+
48
+
49
+ def settings(bundle):
50
+ keys = {'user': ('USERNAME', ''), 'password': ('PASSWORD', ''), 'success': ('SUCCESS_TEXT', ''),
51
+ 'failure': ('FAILURE_TEXT', ''), 'user_field': ('USER_FIELD', 'Email'),
52
+ 'password_field': ('PASSWORD_FIELD', 'Password'), 'submit': ('SUBMIT', 'Sign In')}
53
+ values = {key: os.getenv('PRECHECK_DEMO_' + name, default) for key, (name, default) in keys.items()}
54
+ if not all(values.values()):
55
+ raise ValueError('demo credentials or selectors unavailable')
56
+ if os.getenv('PRECHECK_DEMO_AUTHORIZED_TEST') != '1' or os.getenv('PRECHECK_DEMO_ENVIRONMENT') not in ('test', 'sandbox'):
57
+ raise ValueError('demo login requires an authorized test/sandbox environment')
58
+ if any(MAESTRO_EXPR in value for value in list(values.values()) + [bundle]):
59
+ raise ValueError('demo values contain a Maestro expression; login not attempted')
60
+ return values
61
+
62
+
63
+ def flow(bundle, values):
64
+ return ('appId: ' + json.dumps(bundle) + '\n---\n' +
65
+ '- tapOn: ' + json.dumps('^' + re.escape(values['user_field']) + '$') + '\n' +
66
+ '- inputText: ' + json.dumps(values['user']) + '\n' +
67
+ '- tapOn: ' + json.dumps('^' + re.escape(values['password_field']) + '$') + '\n' +
68
+ '- inputText: ' + json.dumps(values['password']) + '\n' +
69
+ '- tapOn: ' + json.dumps('^' + re.escape(values['submit']) + '$') + '\n')
70
+
71
+
72
+ def drive(udid, bundle, values, dirname):
73
+ path = pathlib.Path(dirname) / 'login.yaml'; path.write_text(flow(bundle, values)); path.chmod(0o600)
74
+ env = dict(os.environ, MAESTRO_CLI_NO_ANALYTICS='1')
75
+ before = hierarchy(udid, dirname, env)
76
+ controls = {values['user_field'], values['password_field'], values['submit']}
77
+ if len(before) < 4 or not controls.issubset(before) or values['success'] in before or values['success'] == values['failure']:
78
+ return 'SKIP\tlogin start state/selectors are ambiguous or unavailable'
79
+ command = ['maestro', '--device', udid, 'test', '--debug-output', str(path.parent / 'debug'),
80
+ '--test-output-dir', str(path.parent / 'output'), str(path)]
81
+ result = _process.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45, cwd=dirname, env=env)
82
+ if result.returncode:
83
+ return 'SKIP\tMaestro could not drive login; selectors or driver unavailable'
84
+ after = hierarchy(udid, dirname, env)
85
+ if len(after) < 4 or (values['success'] in after and values['failure'] in after):
86
+ return 'SKIP\tlogin postcondition ambiguous or accessibility evidence insufficient'
87
+ if values['success'] in after:
88
+ return 'PASS\tdemo start/action/new success selector observed; backend scope requires review'
89
+ if values['failure'] in after:
90
+ return 'FINDING\texplicit login rejection observed after the submitted demo attempt'
91
+ return 'SKIP\tneither success nor failure selector observed'
92
+
93
+
94
+ def attempt(udid, bundle):
95
+ try:
96
+ values = settings(bundle)
97
+ with tempfile.TemporaryDirectory(prefix='precheck-demo-') as temporary:
98
+ os.chmod(temporary, 0o700)
99
+ return drive(udid, bundle, values, temporary)
100
+ except (OSError, subprocess.SubprocessError, ValueError):
101
+ return 'SKIP\tdemo prerequisites, driver or hierarchy unavailable; no conclusion'
102
+
103
+
104
+ def main():
105
+ if len(sys.argv) != 3:
106
+ return 'SKIP\tinternal demo driver arguments missing'
107
+ return attempt(*sys.argv[1:])
108
+
109
+
110
+ if __name__ == '__main__':
111
+ print(main())
@@ -30,6 +30,20 @@ dyn_cmd() {
30
30
  "$@"
31
31
  }
32
32
 
33
+ # Per-step wall-clock caps for teardown and the simulator UI calls. A cap is enforced by
34
+ # lib/dyn-process.py (its own process group, up to 15s of TERM grace on top), so the four
35
+ # teardown steps of two devices stay inside ~120s (4 x (15s + 15s grace)) even if CoreSimulator wedges.
36
+ : "${DYN_TEARDOWN_STEP_TIMEOUT:=15}"
37
+ : "${DYN_UI_TIMEOUT:=20}"
38
+ DYN_DEVICE_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
39
+
40
+ # dyn_cmd_bounded <secs> <argv…> — dyn_cmd with a wall-clock cap (124 on expiry).
41
+ dyn_cmd_bounded() {
42
+ local secs="$1"; shift
43
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "$*"; return 0; fi
44
+ python3 "$DYN_DEVICE_LIB_DIR/dyn-process.py" --timeout "$secs" -- "$@"
45
+ }
46
+
33
47
  # dyn_pick_runtime -> the newest available iOS runtime identifier.
34
48
  dyn_pick_runtime() {
35
49
  [[ "$DYN_DRY_RUN" == 1 ]] && { echo "com.apple.CoreSimulator.SimRuntime.iOS-PLAN"; return 0; }
@@ -52,8 +66,15 @@ dyn_pick_device_type() {
52
66
 
53
67
  # dyn_device_create <name> <device-type> <runtime> -> udid (stdout), or "" on failure.
54
68
  dyn_device_create() {
55
- if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "xcrun simctl create $1 $2 $3"; echo "UDID-PLAN-${1##*-}"; return 0; fi
56
- xcrun simctl create "$1" "$2" "$3" 2>/dev/null
69
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then
70
+ dyn_plan "xcrun simctl create $1 $2 $3"
71
+ [[ -z "${DYN_OWNED_LEDGER:-}" ]] || printf '%s\n' "UDID-PLAN-${1##*-}" >> "$DYN_OWNED_LEDGER"
72
+ echo "UDID-PLAN-${1##*-}"; return 0
73
+ fi
74
+ local created
75
+ created="$(xcrun simctl create "$1" "$2" "$3" 2>/dev/null)" || return 1
76
+ if [[ -n "${DYN_OWNED_LEDGER:-}" && -n "$created" ]]; then printf '%s\n' "$created" >> "$DYN_OWNED_LEDGER"; fi
77
+ printf '%s\n' "$created"
57
78
  }
58
79
 
59
80
  # dyn_device_boot <udid> — boot and wait until the device is usable.
@@ -86,10 +107,17 @@ dyn_device_container() {
86
107
  # dyn_device_teardown <udid> — shutdown + delete. ONLY for a device this run created.
87
108
  dyn_device_teardown() {
88
109
  [[ -n "${1:-}" ]] || return 0
89
- dyn_cmd xcrun simctl shutdown "$1" >/dev/null 2>&1 || true
90
- dyn_cmd xcrun simctl delete "$1" >/dev/null 2>&1 || true
110
+ if [[ -n "${DYN_OWNED_LEDGER:-}" ]]; then
111
+ [[ ! -L "$DYN_OWNED_LEDGER" ]] && dyn_ledger_has "$DYN_OWNED_LEDGER" "$1" || return 0
112
+ fi
113
+ dyn_cmd_bounded "$DYN_TEARDOWN_STEP_TIMEOUT" xcrun simctl shutdown "$1" >/dev/null 2>&1 || true
114
+ dyn_cmd_bounded "$DYN_TEARDOWN_STEP_TIMEOUT" xcrun simctl delete "$1" >/dev/null 2>&1
91
115
  }
92
116
 
93
117
  # dyn_device_appearance <udid> light|dark ; dyn_device_content_size <udid> <size>
94
118
  dyn_device_appearance() { dyn_cmd xcrun simctl ui "$1" appearance "$2" >/dev/null 2>&1 || true; }
95
119
  dyn_device_content_size() { dyn_cmd xcrun simctl ui "$1" content_size "$2" >/dev/null 2>&1 || true; }
120
+
121
+ # dyn_ledger_has <file> <line> — exact whole-line membership; a missing file has nothing.
122
+ dyn_ledger_has() { [[ -f "$1" ]] && grep -qxF -- "$2" "$1"; }
123
+