appstore-precheck 1.18.0 → 1.20.0

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 (70) hide show
  1. package/CHANGELOG.md +256 -0
  2. package/README.md +108 -39
  3. package/bin/cli.js +8 -0
  4. package/package.json +2 -2
  5. package/skills/appstore-precheck/SKILL.md +99 -157
  6. package/skills/appstore-precheck/guidelines-baseline.json +285 -36
  7. package/skills/appstore-precheck/guidelines-fingerprints.json +319 -93
  8. package/skills/appstore-precheck/references/finding-commentary.md +93 -0
  9. package/skills/appstore-precheck/references/methodology.md +81 -26
  10. package/skills/appstore-precheck/references/optional-review.md +56 -0
  11. package/skills/appstore-precheck/references/pierre-deep-review.md +323 -44
  12. package/skills/appstore-precheck/references/review-catalog.json +740 -0
  13. package/skills/appstore-precheck/references/screenshot-vision-review.md +8 -8
  14. package/skills/appstore-precheck/references/simulator-dynamic-review.md +398 -54
  15. package/skills/appstore-precheck/references/typesafe-example.json +239 -0
  16. package/skills/appstore-precheck/references/typesafe.md +216 -0
  17. package/skills/appstore-precheck/scripts/app-discover.sh +138 -0
  18. package/skills/appstore-precheck/scripts/artifact-review.sh +10 -0
  19. package/skills/appstore-precheck/scripts/augment-json.py +29 -0
  20. package/skills/appstore-precheck/scripts/build-run.sh +5 -0
  21. package/skills/appstore-precheck/scripts/coverage-sections.sh +6 -0
  22. package/skills/appstore-precheck/scripts/dynamic-run.sh +400 -0
  23. package/skills/appstore-precheck/scripts/dynamic.sh +329 -0
  24. package/skills/appstore-precheck/scripts/evidence.sh +49 -15
  25. package/skills/appstore-precheck/scripts/findings.sh +76 -26
  26. package/skills/appstore-precheck/scripts/framework-detect.sh +101 -0
  27. package/skills/appstore-precheck/scripts/guideline-cite.sh +4 -1
  28. package/skills/appstore-precheck/scripts/lib/artifact-review.py +518 -0
  29. package/skills/appstore-precheck/scripts/lib/asc-client.py +293 -0
  30. package/skills/appstore-precheck/scripts/lib/build-evidence.py +50 -0
  31. package/skills/appstore-precheck/scripts/lib/build-exec.py +50 -0
  32. package/skills/appstore-precheck/scripts/lib/build-plan.py +106 -0
  33. package/skills/appstore-precheck/scripts/lib/build-plan.sh +15 -0
  34. package/skills/appstore-precheck/scripts/lib/build-run.py +177 -0
  35. package/skills/appstore-precheck/scripts/lib/coverage-run.sh +23 -0
  36. package/skills/appstore-precheck/scripts/lib/coverage-sections.py +244 -0
  37. package/skills/appstore-precheck/scripts/lib/dyn-bundle.sh +185 -0
  38. package/skills/appstore-precheck/scripts/lib/dyn-demo-login.py +111 -0
  39. package/skills/appstore-precheck/scripts/lib/dyn-device.sh +123 -0
  40. package/skills/appstore-precheck/scripts/lib/dyn-explore.py +312 -0
  41. package/skills/appstore-precheck/scripts/lib/dyn-geometry.sh +75 -0
  42. package/skills/appstore-precheck/scripts/lib/dyn-guideline-capture.py +301 -0
  43. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.py +112 -0
  44. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.sh +23 -0
  45. package/skills/appstore-precheck/scripts/lib/dyn-hosts.sh +134 -0
  46. package/skills/appstore-precheck/scripts/lib/dyn-process.py +75 -0
  47. package/skills/appstore-precheck/scripts/lib/dyn-quorum.sh +90 -0
  48. package/skills/appstore-precheck/scripts/lib/dyn-scrub.py +79 -0
  49. package/skills/appstore-precheck/scripts/lib/dyn-signals.sh +120 -0
  50. package/skills/appstore-precheck/scripts/lib/guideline-text.sh +23 -5
  51. package/skills/appstore-precheck/scripts/lib/metadata-review.py +369 -0
  52. package/skills/appstore-precheck/scripts/lib/optin-scan.sh +73 -0
  53. package/skills/appstore-precheck/scripts/lib/optional-records.py +60 -0
  54. package/skills/appstore-precheck/scripts/lib/png-uniform.py +115 -0
  55. package/skills/appstore-precheck/scripts/lib/runtime-blocking.py +26 -0
  56. package/skills/appstore-precheck/scripts/lib/safe_write.py +61 -0
  57. package/skills/appstore-precheck/scripts/lib/scan-guidelines.sh +199 -0
  58. package/skills/appstore-precheck/scripts/lib/static-guidelines.py +341 -0
  59. package/skills/appstore-precheck/scripts/lib/static-reader.py +39 -0
  60. package/skills/appstore-precheck/scripts/metadata-review.sh +4 -0
  61. package/skills/appstore-precheck/scripts/opt-in-review.py +160 -0
  62. package/skills/appstore-precheck/scripts/runtime-review.sh +5 -0
  63. package/skills/appstore-precheck/scripts/scan.sh +132 -21
  64. package/skills/appstore-precheck/scripts/semantic/__init__.py +1 -0
  65. package/skills/appstore-precheck/scripts/semantic/client.py +95 -0
  66. package/skills/appstore-precheck/scripts/semantic/collect.py +165 -0
  67. package/skills/appstore-precheck/scripts/semantic/engine.py +320 -0
  68. package/skills/appstore-precheck/scripts/semantic/questions.py +167 -0
  69. package/skills/appstore-precheck/scripts/semantic/review_v4.py +81 -0
  70. package/skills/appstore-precheck/scripts/semantic-review.py +61 -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,244 @@
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
+ chunks = re.split(r'set_rule "([\w-]*)"', text)
35
+ for index in range(1, len(chunks), 2):
36
+ slug = chunks[index]
37
+ if slug not in slugs:
38
+ continue
39
+ for message in re.findall(r'\b(?:fail|warn|pass)\s+"((?:[^"\\]|\\.)*)"', chunks[index + 1]):
40
+ add(result, message, '§%d' % slugs[slug])
41
+ return result, len(slugs)
42
+
43
+
44
+ def table_sources(path, dynamic=False):
45
+ result, ids = {}, set()
46
+ for line in path.read_text().splitlines():
47
+ cells = [cell.strip() for cell in line.split('|')]
48
+ if dynamic and len(cells) >= 6 and re.fullmatch(r'D\d+[a-z]?', cells[1]):
49
+ names = re.findall(r'`(dyn-[\w-]+)', cells[2])
50
+ for name in names:
51
+ if name != 'dyn-install':
52
+ add(result, cells[3], name)
53
+ ids.add(name)
54
+ elif not dynamic and len(cells) >= 5 and re.fullmatch(r'S\d+', cells[1]):
55
+ name = 'vision-' + cells[1]
56
+ add(result, cells[2], name)
57
+ ids.add(name)
58
+ return result, ids
59
+
60
+
61
+ def semantic_input_kinds(skill):
62
+ folder = skill / 'scripts/semantic'
63
+ tree = ast.parse((folder / 'collect.py').read_text())
64
+ function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'input_kinds')
65
+ # The collector returns literal kind lists; extract the actual return values.
66
+ kinds = {item.value for node in ast.walk(function) if isinstance(node, ast.Return)
67
+ for value in ast.walk(node) if isinstance(value, ast.List)
68
+ for item in value.elts if isinstance(item, ast.Constant) and isinstance(item.value, str)}
69
+ tree = ast.parse((folder / 'review_v4.py').read_text())
70
+ declaration = next(node for node in tree.body if isinstance(node, ast.Assign)
71
+ and any(isinstance(target, ast.Name) and target.id == 'HOST_INPUT_KINDS' for target in node.targets))
72
+ return kinds, set(ast.literal_eval(declaration.value))
73
+
74
+
75
+ def deep_check_errors(check, prose, cases, local_kinds, host_kinds):
76
+ prefix = 'deep-%d' % check['number']
77
+ errors = []
78
+ procedure = re.search(r'^### %d — .*?(?=^### |^---$|\Z)' % check['number'], prose, re.M | re.S)
79
+ if not procedure or check['question'] not in procedure[0] or len(procedure[0].strip().splitlines()) < 3:
80
+ errors.append(prefix + ' has no matching executable review procedure')
81
+ if not any(c.get('check_number') == check['number'] and c.get('check_key') == check['key']
82
+ and c.get('guideline') == check['guideline'] and c.get('text', '').strip()
83
+ and c.get('expected') in ('finding', 'no_signal', 'insufficient_evidence') for c in cases):
84
+ errors.append(prefix + ' has no matching labeled semantic fixture')
85
+ inputs = check.get('evidence_inputs', [])
86
+ if not inputs:
87
+ errors.append(prefix + ' has no declared evidence inputs')
88
+ for kind in inputs:
89
+ if kind not in local_kinds and not (kind in host_kinds and check.get('requires_vision')
90
+ and 'host_' + kind.replace('-', '_') in check.get('required_context', [])):
91
+ errors.append(prefix + ' cannot obtain evidence input: ' + kind)
92
+ return errors
93
+
94
+
95
+ def deep_sources(skill, catalog):
96
+ result, errors = {}, []
97
+ refs = skill / 'references'
98
+ prose = (refs / 'pierre-deep-review.md').read_text()
99
+ case_path = skill.parents[1] / 'corpus/synthetic/semantic-v4/cases.json'
100
+ try:
101
+ cases = json.loads(case_path.read_text())['cases']
102
+ local_kinds, host_kinds = semantic_input_kinds(skill)
103
+ except (OSError, ValueError, KeyError, StopIteration) as exc:
104
+ cases, local_kinds, host_kinds = [], set(), set()
105
+ errors.append('cannot validate semantic review inputs: ' + str(exc))
106
+ for check in catalog['checks']:
107
+ problems = deep_check_errors(check, prose, cases, local_kinds, host_kinds) if check['number'] >= 32 else []
108
+ errors.extend(problems)
109
+ if not problems:
110
+ add(result, check['guideline'], 'deep-%d' % check['number'])
111
+ return result, errors
112
+
113
+
114
+ def sources(skill):
115
+ scan, vectors = scan_sources(skill)
116
+ refs = skill / 'references'
117
+ catalog = json.loads((refs / 'review-catalog.json').read_text())
118
+ deep, deep_errors = deep_sources(skill, catalog)
119
+ dynamic, dynamic_ids = table_sources(refs / 'simulator-dynamic-review.md', True)
120
+ vision, vision_ids = table_sources(refs / 'screenshot-vision-review.md')
121
+ text = (skill / 'scripts/dynamic.sh').read_text()
122
+ body = re.search(r'dyn_catalogue\(\) \{(.*?)\n\}', text, re.S)
123
+ registered = set(re.findall(r'\bdyn-[\w-]+', body[1] if body else '')) - {'dyn-install'}
124
+ errors = deep_errors + ['dynamic table/catalog mismatch: ' + name for name in sorted(dynamic_ids ^ registered)]
125
+ numbers = [c['number'] for c in catalog['checks']]
126
+ keys = [c['key'] for c in catalog['checks']]
127
+ if len(numbers) != len(set(numbers)) or len(keys) != len(set(keys)):
128
+ errors.append('duplicate deep-review number/key')
129
+ return {'scan': scan, 'deep': deep, 'dynamic': dynamic, 'vision': vision}, {
130
+ 'static_vectors': vectors, 'deep_checks': len(numbers),
131
+ 'dynamic_checks': len(registered), 'vision_checks': len(vision_ids),
132
+ 'catalog_version': catalog['version']}, errors
133
+
134
+
135
+ def validate_baseline(base, evidence, errors):
136
+ all_sections = set(base['all_sections'])
137
+ if len(all_sections) != len(base['all_sections']):
138
+ errors.append('duplicate all_sections entry')
139
+ for field in ('not_counted', 'human_only'):
140
+ for section, reason in base[field].items():
141
+ if section not in all_sections or not isinstance(reason, str) or not reason.strip():
142
+ errors.append('%s invalid section/reason: %s' % (field, section))
143
+ for route, field in ROUTES.items():
144
+ entries = base[field]
145
+ if len(entries) != len(set(entries)):
146
+ errors.append('%s contains duplicate sections' % field)
147
+ for section in entries:
148
+ if section not in all_sections:
149
+ errors.append('%s unknown section: %s' % (field, section))
150
+ if section in base['human_only'] or section in base['not_counted']:
151
+ errors.append('%s excluded section claimed covered: %s' % (field, section))
152
+ if section not in evidence[route]:
153
+ errors.append('%s has no check source: %s' % (field, section))
154
+
155
+
156
+ def build_report(skill, base):
157
+ evidence, counts, errors = sources(skill)
158
+ validate_baseline(base, evidence, errors)
159
+ all_sections = set(base['all_sections'])
160
+ parents = {s for s in all_sections if any(t.startswith(s + '.') for t in all_sections)}
161
+ leaves = all_sections - parents - set(base['not_counted'])
162
+ if set(base['human_only']) - leaves:
163
+ errors.append('human_only contains non-leaf sections')
164
+ routes, combined, pointers = {}, set(), {}
165
+ for route, field in ROUTES.items():
166
+ # Invalid claims are shown as errors and never inflate the reported numerator.
167
+ touched = set(base[field]) & leaves & set(evidence[route])
168
+ touched -= set(base['human_only'])
169
+ routes[route] = {'covered': len(touched), 'sections': sorted(touched, key=order)}
170
+ combined |= touched
171
+ for section in touched:
172
+ pointers.setdefault(section, set()).update(evidence[route][section])
173
+ partial = sorted((s for s in pointers if pointers[s] <= POSITIVE_ONLY_SOURCES), key=order)
174
+ return dict(counts, denominator=len(leaves), covered=len(combined), touched=len(combined),
175
+ positive_only=len(partial), positive_only_sections=partial,
176
+ source_details=source_details(pointers),
177
+ percentage=round(100 * len(combined) / len(leaves)) if leaves else 0,
178
+ human_only=len(base['human_only']), human_only_sections=base['human_only'],
179
+ not_counted_count=len(base['not_counted']), not_counted=base['not_counted'],
180
+ parent_sections_count=len(parents), parent_sections=sorted(parents, key=order),
181
+ covered_sections=sorted(combined, key=order),
182
+ uncovered_sections=sorted(leaves - combined, key=order),
183
+ sources={s: sorted(pointers[s]) for s in sorted(pointers, key=order)},
184
+ routes=routes, errors=errors)
185
+
186
+
187
+ def source_details(pointers):
188
+ partial = 'partial (positive-only observation)'
189
+ normal = 'maintained check; evidence-dependent'
190
+ return {section: {'scope': partial if checks <= POSITIVE_ONLY_SOURCES else normal,
191
+ 'sources': [{'check': check, 'scope': partial if check in POSITIVE_ONLY_SOURCES else normal}
192
+ for check in sorted(checks)]}
193
+ for section, checks in sorted(pointers.items(), key=lambda pair: order(pair[0]))}
194
+
195
+
196
+ def summary_line(report):
197
+ return ('Coverage inventory: {covered}/{denominator} leaf sections ({percentage}%); '
198
+ '{touched} touched, {positive_only} positive-only; '
199
+ '{static_vectors} static vectors, {deep_checks} deep-review checks, '
200
+ '{dynamic_checks} dynamic checks, {vision_checks} vision checks, '
201
+ '{human_only} human-only sections.').format(**report)
202
+
203
+
204
+ def markdown(report):
205
+ lines = ['# Guideline section coverage', '',
206
+ 'Generated by `skills/appstore-precheck/scripts/coverage-sections.sh --markdown`.', '',
207
+ summary_line(report), '',
208
+ 'This percentage counts sections touched by maintained checks, not automated verification of all requirements.',
209
+ 'Routes overlap; advisory and vision checks require their evidence and may SKIP on a particular run.', '',
210
+ '| Route | Leaf sections |', '|---|---:|']
211
+ lines += ['| %s | %s |' % (route, entry['covered']) for route, entry in report['routes'].items()]
212
+ lines += ['', '## Covered sections and check sources', '', '| Section | Sources | Scope |', '|---|---|---|']
213
+ lines += ['| %s | %s | %s |' % (s, ', '.join(v), report['source_details'][s]['scope'])
214
+ for s, v in report['sources'].items()]
215
+ lines += ['', '## Not audited', '', 'Uncovered sections: ' + ', '.join(report['uncovered_sections']) + '.', '',
216
+ 'Human-only sections require external evidence or a human decision:', '']
217
+ lines += ['- %s: %s' % (s, reason) for s, reason in report['human_only_sections'].items()]
218
+ lines += ['', '## Denominator exclusions', '',
219
+ 'Parents (not inherited by their children): ' + ', '.join(report['parent_sections']) + '.', '']
220
+ lines += ['- %s: %s' % (s, reason) for s, reason in report['not_counted'].items()]
221
+ lines += ['', 'Cross-validation errors: %d.' % len(report['errors'])]
222
+ lines += ['- ' + e for e in report['errors']]
223
+ return '\n'.join(lines) + '\n'
224
+
225
+
226
+ def main():
227
+ parser = argparse.ArgumentParser(description=__doc__)
228
+ group = parser.add_mutually_exclusive_group()
229
+ group.add_argument('--json', action='store_true')
230
+ group.add_argument('--markdown', action='store_true')
231
+ parser.add_argument('--baseline', type=Path)
232
+ args = parser.parse_args()
233
+ skill = Path(__file__).resolve().parents[2]
234
+ try:
235
+ base = json.loads((args.baseline or skill / 'guidelines-baseline.json').read_text())
236
+ report = build_report(skill, base)
237
+ except (OSError, ValueError, KeyError, TypeError) as exc:
238
+ parser.exit(1, 'coverage-sections: cannot validate inputs: %s\n' % exc)
239
+ print(json.dumps(report, indent=2, ensure_ascii=False) if args.json else markdown(report), end='\n' if args.json else '')
240
+ return 1 if report['errors'] else 0
241
+
242
+
243
+ if __name__ == '__main__':
244
+ raise SystemExit(main())
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env bash
2
+ # lib/dyn-bundle.sh — read the INSTALLED bundle (what `xcrun simctl get_app_container
3
+ # <udid> <bundle-id> app` returns) and report what it establishes, executing nothing:
4
+ # dyn-shipped-bundle[:KEY] installed Info.plist vs the repo Info.plist; one line per
5
+ # NS*UsageDescription key the installed plist declares
6
+ # (a complete per-key test of the static purpose-string
7
+ # claim), one FINDING per key the repo declares and the
8
+ # installed plist lacks, and a keyless drift summary.
9
+ # dyn-shipped-sdk DTXcode / DTSDKName: the toolchain that built THIS bundle
10
+ # (what ITMS-90725 reads), versus the LastUpgradeCheck proxy.
11
+ # dyn-shipped-links otool -L on the executable: a /System/Library/PrivateFrameworks
12
+ # link is decisive for 2.5.1; absence is only partial.
13
+ # The build configuration is NOT read from the plist: it comes from the .app's parent
14
+ # directory name (app-discover.sh), because a plist cannot tell Debug from Release.
15
+ # Sourced by dynamic-run.sh. Bash 3.2. plutil on macOS; XML fallback for CI fixtures.
16
+
17
+ # --- plist readers ------------------------------------------------------------------
18
+ # plutil on macOS (a real .app carries BINARY plists); an XML fallback for CI fixtures
19
+ # and for a Mac without Xcode tools. DYN_NO_PLUTIL=1 forces the fallback (tests use it
20
+ # to run the ubuntu path on macOS). The fallback first puts every tag on its own line
21
+ # (`sed 's/>/>\n/g'`), so one-line `<key>K</key><string>v</string>` pairs and
22
+ # pretty-printed plists parse identically.
23
+ _dyn_have_plutil() { [[ -z "${DYN_NO_PLUTIL:-}" ]] && command -v plutil >/dev/null 2>&1; }
24
+ _dyn_plist_tokens() { sed 's/>/>\
25
+ /g' "$1" 2>/dev/null | sed -E 's/^[[:space:]]+//' | grep -v '^$'; }
26
+
27
+ # dyn_plist_keys <plist> -> top-level keys, one per line, sorted.
28
+ dyn_plist_keys() {
29
+ local f="$1"
30
+ [[ -f "$f" ]] || return 0
31
+ if _dyn_have_plutil && plutil -convert json -o - "$f" >/dev/null 2>&1; then
32
+ plutil -convert json -o - "$f" 2>/dev/null | jq -r 'keys[]' 2>/dev/null | sort
33
+ else
34
+ _dyn_plist_tokens "$f" | awk '
35
+ /<dict>/ { depth++; next }
36
+ /<\/dict>/ { depth--; next }
37
+ /<array>/ { arr++; next }
38
+ /<\/array>/ { arr--; next }
39
+ depth == 1 && arr == 0 && /<\/key>/ { sub(/<\/key>.*/, ""); print }
40
+ ' | sort
41
+ fi
42
+ }
43
+
44
+ # dyn_plist_string <plist> <key> -> string value or "" (empty for a non-string or a missing key).
45
+ dyn_plist_string() {
46
+ local f="$1" k="$2" v=""
47
+ [[ -f "$f" ]] || { printf ''; return; }
48
+ if _dyn_have_plutil; then v="$(plutil -extract "$k" raw -o - "$f" 2>/dev/null)" || v=""; fi
49
+ if [[ -z "$v" ]]; then
50
+ v="$(_dyn_plist_tokens "$f" | awk -v K="$k</key>" '
51
+ state == 2 { sub(/<\/string>.*/, ""); print; exit }
52
+ state == 1 { if ($0 ~ /^<string>/) state = 2; else exit; next }
53
+ $0 == K { state = 1 }
54
+ ')"
55
+ fi
56
+ printf '%s' "$v"
57
+ }
58
+
59
+ # dyn_plist_array_strings <plist> <key> -> the string members of an array value, one per line.
60
+ dyn_plist_array_strings() {
61
+ local f="$1" k="$2"
62
+ [[ -f "$f" ]] || return 0
63
+ if _dyn_have_plutil && plutil -extract "$k" json -o - "$f" >/dev/null 2>&1; then
64
+ plutil -extract "$k" json -o - "$f" 2>/dev/null | jq -r '.[]? | strings' 2>/dev/null
65
+ else
66
+ _dyn_plist_tokens "$f" | awk -v K="$k</key>" '
67
+ on && /<\/array>/ { exit }
68
+ on && /<\/string>/ { sub(/<\/string>.*/, ""); print; next }
69
+ $0 == K { on = 1 }
70
+ '
71
+ fi
72
+ }
73
+
74
+ # dyn_plist_array_has_int <plist> <key> <int> -> 0 when the array value contains the integer.
75
+ dyn_plist_array_has_int() {
76
+ local f="$1" k="$2" want="$3"
77
+ [[ -f "$f" ]] || return 1
78
+ if _dyn_have_plutil && plutil -extract "$k" json -o - "$f" >/dev/null 2>&1; then
79
+ plutil -extract "$k" json -o - "$f" 2>/dev/null | jq -e --argjson w "$want" 'index($w) != null' >/dev/null 2>&1
80
+ else
81
+ _dyn_plist_tokens "$f" | awk -v K="$k</key>" -v W="$want</integer>" '
82
+ on && /<\/array>/ { exit }
83
+ on && $0 == W { found = 1; exit }
84
+ $0 == K { on = 1 }
85
+ END { exit found ? 0 : 1 }
86
+ '
87
+ fi
88
+ }
89
+
90
+ # dyn_bundle_plist_lines <installed-plist> <repo-plist|""> -> transcript lines.
91
+ dyn_bundle_plist_lines() {
92
+ local inst="$1" repo="${2:-}" k v g only_repo only_inst n_inst n_diff
93
+ [[ -f "$inst" ]] || { echo "DYNAMIC-SKIP: 5.1.1 [dyn-shipped-bundle] — installed bundle has no readable Info.plist"; return 0; }
94
+ # One complete per-key observation for every purpose string the installed plist declares.
95
+ while IFS= read -r k; do
96
+ case "$k" in NS*UsageDescription) ;; *) continue ;; esac
97
+ v="$(dyn_plist_string "$inst" "$k")"
98
+ g="5.1.1"; [[ "$k" == NSUserTrackingUsageDescription ]] && g="5.1.2"
99
+ if [[ -n "$v" ]]; then
100
+ printf 'DYNAMIC-PASS: %s [dyn-shipped-bundle:%s] — installed Info.plist declares %s ("%s")\n' "$g" "$k" "$k" "$(printf '%s' "$v" | cut -c1-80)"
101
+ else
102
+ printf 'DYNAMIC-FINDING: %s [dyn-shipped-bundle:%s] — installed Info.plist has %s but it is EMPTY (the validator treats an empty purpose string as missing)\n' "$g" "$k" "$k"
103
+ fi
104
+ done < <(dyn_plist_keys "$inst")
105
+ n_inst="$(dyn_plist_keys "$inst" | grep -c .)"
106
+ if [[ -n "$repo" && -f "$repo" ]]; then
107
+ only_repo="$(comm -23 <(dyn_plist_keys "$repo") <(dyn_plist_keys "$inst"))"
108
+ only_inst="$(comm -13 <(dyn_plist_keys "$repo") <(dyn_plist_keys "$inst") | grep -vE '^(DT|BuildMachine|CFBundleSupportedPlatforms|MinimumOSVersion|UIDeviceFamily|CFBundleInfoDictionaryVersion|CFBundleNumericVersion|LSRequiresIPhoneOS|UIRequiredDeviceCapabilities|CFBundleDevelopmentRegion|CFBundlePackageType|CFBundleShortVersionString|CFBundleVersion|CFBundleName|CFBundleDisplayName|CFBundleExecutable|CFBundleIdentifier|UILaunchScreen|UISupportedInterfaceOrientations)' || true)"
109
+ while IFS= read -r k; do
110
+ [[ -n "$k" ]] || continue
111
+ case "$k" in NS*UsageDescription)
112
+ g="5.1.1"; [[ "$k" == NSUserTrackingUsageDescription ]] && g="5.1.2"
113
+ printf 'DYNAMIC-FINDING: %s [dyn-shipped-bundle:%s] — %s is in the repo Info.plist but NOT in the installed bundle (a build setting or target-specific plist dropped it)\n' "$g" "$k" "$k" ;;
114
+ esac
115
+ done <<< "$only_repo"
116
+ n_diff="$(printf '%s\n%s\n' "$only_repo" "$only_inst" | grep -c .)"
117
+ printf 'DYNAMIC-PASS: 5.1.1 [dyn-shipped-bundle] — installed Info.plist has %s keys; %s key(s) differ from the repo Info.plist%s%s\n' \
118
+ "$n_inst" "$n_diff" \
119
+ "$([[ -n "$only_repo" ]] && printf ' (only in repo: %s)' "$(printf '%s' "$only_repo" | tr '\n' ' ' | sed 's/ $//')")" \
120
+ "$([[ -n "$only_inst" ]] && printf ' (only in bundle: %s)' "$(printf '%s' "$only_inst" | tr '\n' ' ' | sed 's/ $//')")"
121
+ else
122
+ printf 'DYNAMIC-PASS: 5.1.1 [dyn-shipped-bundle] — installed Info.plist has %s keys (no repo Info.plist to compare against)\n' "$n_inst"
123
+ fi
124
+ }
125
+
126
+ # dyn_bundle_privacy_note <installed-app-dir> -> short note on PrivacyInfo.xcprivacy presence.
127
+ dyn_bundle_privacy_note() {
128
+ local app="$1"
129
+ if [[ -f "$app/PrivacyInfo.xcprivacy" ]]; then echo "PrivacyInfo.xcprivacy present in the bundle"
130
+ else echo "no PrivacyInfo.xcprivacy at the bundle root"; fi
131
+ }
132
+
133
+ # dyn_bundle_sdk_line <installed-plist> -> transcript line for dyn-shipped-sdk.
134
+ # Floor: iOS 26 SDK == DTXcode >= 2600 (ITMS-90725 since 2026-04-28).
135
+ dyn_bundle_sdk_line() {
136
+ local inst="$1" xc sdk xb
137
+ xc="$(dyn_plist_string "$inst" DTXcode)"; sdk="$(dyn_plist_string "$inst" DTSDKName)"; xb="$(dyn_plist_string "$inst" DTXcodeBuild)"
138
+ if [[ -z "$xc" || ! "$xc" =~ ^[0-9]+$ ]]; then
139
+ echo "DYNAMIC-SKIP: 2.1 [dyn-shipped-sdk] — installed Info.plist carries no DTXcode; the build toolchain cannot be read from this bundle"
140
+ return 0
141
+ fi
142
+ if (( 10#$xc >= 2600 )); then
143
+ printf 'DYNAMIC-PASS: 2.1 [dyn-shipped-sdk] — installed Info.plist: DTXcode=%s%s%s (built with the iOS 26 SDK or later)\n' "$xc" "${xb:+ DTXcodeBuild=$xb}" "${sdk:+ DTSDKName=$sdk}"
144
+ else
145
+ printf 'DYNAMIC-FINDING: 2.1 [dyn-shipped-sdk] — installed Info.plist: DTXcode=%s%s (pre-26 toolchain; App Store uploads have required the iOS 26 SDK since April 2026)\n' "$xc" "${sdk:+ DTSDKName=$sdk}"
146
+ fi
147
+ }
148
+
149
+ # dyn_bundle_links_line <installed-app-dir> -> transcript line for dyn-shipped-links.
150
+ # Xcode 16+ Debug builds put the app's code in <Executable>.debug.dylib and leave a thin
151
+ # stub as the main executable, so the stub links almost nothing; the dylib is read too
152
+ # when present, and the line says which binaries were read.
153
+ dyn_bundle_links_line() {
154
+ local app="$1" exe out n priv read_list dbg
155
+ exe="$(dyn_plist_string "$app/Info.plist" CFBundleExecutable)"
156
+ [[ -n "$exe" && -f "$app/$exe" ]] || { echo "DYNAMIC-SKIP: 2.5.1 [dyn-shipped-links] — executable not found in the installed bundle"; return 0; }
157
+ command -v otool >/dev/null 2>&1 || { echo "DYNAMIC-SKIP: 2.5.1 [dyn-shipped-links] — otool not available; linked frameworks could not be read"; return 0; }
158
+ out="$(otool -L "$app/$exe" 2>/dev/null)" || { echo "DYNAMIC-SKIP: 2.5.1 [dyn-shipped-links] — otool -L failed on the installed executable"; return 0; }
159
+ read_list="$exe"
160
+ dbg="$app/$exe.debug.dylib"
161
+ if [[ -f "$dbg" ]]; then
162
+ out="$out"$'\n'"$(otool -L "$dbg" 2>/dev/null)"; read_list="$exe + $exe.debug.dylib (Debug build: the code lives in the dylib)"
163
+ fi
164
+ n="$(printf '%s\n' "$out" | grep -c '^[[:space:]]')"
165
+ priv="$(printf '%s\n' "$out" | grep -E 'PrivateFrameworks/' | sed -E 's/^[[:space:]]+//; s/ \(.*//' | sort -u | head -3)"
166
+ if [[ -n "$priv" ]]; then
167
+ printf 'DYNAMIC-FINDING: 2.5.1 [dyn-shipped-links] — otool -L %s: links a private framework: %s\n' "$read_list" "$(printf '%s' "$priv" | tr '\n' ' ' | sed 's/ $//')"
168
+ else
169
+ printf 'DYNAMIC-PASS: 2.5.1 [dyn-shipped-links] — otool -L %s: %s linked libraries, none under /System/Library/PrivateFrameworks (linkage only; private selectors are not visible here)\n' "$read_list" "$n"
170
+ fi
171
+ }
172
+
173
+ # dyn_config_from_dir <app-path> -> debug | release | unknown, from the PARENT DIRECTORY
174
+ # NAME only (Debug-iphonesimulator / Release-iphonesimulator). Never from the plist: a
175
+ # plist cannot tell the configurations apart, and this value gates the qualifier.
176
+ dyn_config_from_dir() {
177
+ case "$(basename "$(dirname "$1")")" in
178
+ Debug-iphonesimulator) echo debug ;;
179
+ Release-iphonesimulator) echo release ;;
180
+ *) echo unknown ;;
181
+ esac
182
+ }
183
+
184
+ # dyn_plist_supports_ipad <plist> -> 0 when UIDeviceFamily contains 2.
185
+ dyn_plist_supports_ipad() { dyn_plist_array_has_int "$1" UIDeviceFamily 2; }