Avoid common App Store and Google Play rejections. Open playbook and pre-submission guard with 117 documented rejection patterns and fixes, privacy manifest and Data safety checks, 95 tracked deadlines (EU AI Act, DSA, COPPA, age laws), and a skill for AI coding agents.
Shell accessibilityai-agentsandroidapp-review-guidelinesapp-storeapp-store-connectapp-store-rejectionapp-store-reviewclaude-codecoppadata-safetyeu-ai-actgdprgoogle-playgoogle-play-policyiosmobile-complianceplay-consolepre-submission-checklistprivacy-manifest
Release 2.0.0 for every coding assistant and every app layout (#1002)
Mirza Iqbal9ab170eb6300
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 12918ed..dfa7422 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -96,6 +96,14 @@ bash agent-os/hooks/app-store-compliance-guard-test.sh- The doc, the JSON taxonomy, and the guard stay consistent with each other.- A short description of what changed and why.+## Cutting a release++1. Set the new version in `VERSION`, in the `version` field of `data/rejection-patterns.json` and `data/regulatory-deadlines.json`, and in `version` and `date-released` of `CITATION.cff`. `python3 scripts/validate.py` fails until all four agree.+2. Rename `## Unreleased` in `CHANGELOG.md` to the version and date, and start a new empty `## Unreleased` above it.+3. After the pull request is merged, tag the merge commit `v<version>` and publish a GitHub release whose notes are that changelog section.++Use a major version when a change breaks something people rely on, such as a licence change or a new exit code.+## LicenseBy contributing you agree that your contributions are licensed under the OpenRoots Agent License 2.3, the licence in `LICENSE`, and that the copyright notice and licence reference stay intact in every copy. If you used an AI tool to produce a contribution, say so in the pull request and name the tool, as Section 8.4 of the licence requires.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b06b0b4..0cfe9e8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -27,7 +27,9 @@ jobs:run: bash agent-os/hooks/app-store-compliance-guard-test.sh- name: Installer test suite- run: bash scripts/install-test.sh+ run: |+ bash scripts/install-test.sh+ bash scripts/install-harness-test.sh- name: Every link, path, script and flag named in the docs existsrun: |@@ -46,6 +48,11 @@ jobs:- name: Release audit testrun: bash scripts/release-audit-test.sh+ - name: Privacy manifest validator and citation verifier tests+ run: |+ bash scripts/validate-privacy-manifest-test.sh+ bash scripts/verify-citations-test.sh+- name: Timeline and deadline checker testsrun: |python3 scripts/test-generate-timeline.pydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5f7882..e08c064 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,39 +4,129 @@ All notable changes to this playbook are recorded here. The format follows Keep## Unreleased+Nothing yet.++## 2.0.0 (2026-10-16)++This release changes the licence and the release audit's exit codes, so it is a major version. Everything below landed since 1.0.0.++### Thanks++- Omar Albeik ([@omaralbeik](https://github.com/omaralbeik)) found that the sanctions section still listed Syria as an embargoed territory after the OFAC program ended, and opened [#967](https://github.com/mjmirza/app-store-compliance/pull/967) with the correction. His fix landed in [#1001](https://github.com/mjmirza/app-store-compliance/pull/1001), where he is a co-author. Developers shipping to Syria now get the rules that actually apply instead of a block that no longer exists.+### Changed+- Shell tools are matched against an exact name list, which adds `runInTerminal` and `run_in_terminal`. An MCP tool whose name merely contains terminal or shell is no longer scanned.- The default branch is now `main`. The CI trigger, the README badge and SECURITY.md follow it, and the bot branch ruleset excludes whichever branch is the default.- The bot PR gate. The workflow from #442 closed every PR whose branch looked bot-generated, which caught the owner's own Jules scheduled tasks. It is replaced by a gate that closes only pull requests from bot accounts not on the allowlist (Jules, Copilot, Dependabot, GitHub Actions), without deleting the branch. Owner-run bot PRs stay open, land on the project board as Backlog through the auto-add workflow, and are reviewed by hand. The eleven Jules PRs closed on 14 September 2026 had their branches deleted by the old workflow and cannot be reopened.### Added-- Guard app root detection, two edges left open by #612. A React Native or Expo app with no app.json or app.config is now its own app when its package.json lists react-native or expo under dependencies and it owns an ios or android folder, so a member whose native folder holds no project file yet no longer pools into its sibling (#655). A dev or peer dependency never counts, and a native-module library with peerDependencies stays a library. A directory linked into the tree from outside it is followed one level when its target carries an app marker, unless the link is named like a vendored folder (vendor, build, node_modules and the other names the scan already skips), and scanned through its target as its own app (#657). A link back into the tree, to an ancestor, or to itself is skipped, and the target is read without following any further link, so a cycle cannot hang the scan. A linked ios or android platform folder is still not followed. A nested bare Xcode or Android project under a root framework app stays part of the root scan, now pinned by a test, because no boundary separates a demo from a shipping app without guessing from folder names (#656). A linked app is scanned beside the project, never in place of it, so a clean linked app cannot hide the project's own findings, and an empty project root beside a linked app is not reported as NOT CHECKED, unless a framework app under it still needs its native folders, which keeps NOT CHECKED. A linked Unity, MAUI, Tauri, Cordova or Capacitor app is followed too, and two links to one app scan it once. 13 new test cases, 302 total, green on bash 5 and macOS bash 3.2.+- A bare Xcode or Android app under a root framework app (Expo, React Native, Flutter, Capacitor), with its own Info.plist or AndroidManifest.xml and no root build file that names it, is scanned as its own app. It counts as an app only with an `.xcodeproj` that builds an application (or names no product type) or an Android application module, so a library or a local native module stays with the app that uses it, and it splits off only when the root has its own project for that platform, so a managed Expo root keeps its checks. A native host that embeds React Native, Expo, Flutter or Capacitor (Swift, Objective-C, Kotlin or Java code, a Podfile or a Gradle file naming it, Cordova plugins included, in Objective-C or Swift, an `RCTAppDelegate`, an Expo app delegate, `import React` with a React surface view, or an Android `ReactActivity` or `ReactNativeHost`) is brownfield and stays in the root scan, so its over-the-air updater and other framework findings still count. A native app that does split off, and the root it left, both keep every framework check the pooled tree showed (a Capacitor root's UIWebView check, or a Cordova `config.xml` inside the split app, for example), exactly as when they were scanned as one. The root and its split native apps are also scanned together as in 1.0.0, and any finding the separate scans did not list at the same severity is added once, so a critical finding is never dropped beside a high one with the same id, so evidence that spans both (a shared source file and the split app) still counts. A project in a folder named exactly demo, example, sample or playground (or the plural) stays in the root scan, so its findings still count (#656).+- Install for every major AI coding tool. `install.sh --tool codex|gemini|opencode|cursor|copilot|grok|qwen|kimi|droid|auggie|windsurf` installs the guard, the skill and, where the tool supports it, the `/app-store-audit` command, and registers the hook in that tool's own config, merged with every other setting and backed up. `--tool all` installs into every tool it finds. Each install ends with `Install verified.` only after it feeds a submit command to the hook in that tool's own payload format and sees it blocked. OpenCode gets a plugin, because it has no hook config, written to both `plugins/` (current OpenCode) and `plugin/` (OpenCode before 1.0, which reads only that folder). Checked live on this machine. The real Codex CLI and the real Qwen Code 0.25.1 each stopped a submit command with the guard's findings. The real Gemini CLI 0.22.5 and OpenCode 0.14.1 loaded the hook and the plugin, and their model call could not run here (no Gemini licence on the account, no free OpenCode model available), so their blocking is proven by feeding each tool's own payload to the installed hook. 203 tests in `scripts/install-harness-test.sh`, in CI.+- GitHub Copilot in every place it runs. `--tool copilot` covers Copilot CLI and Copilot in VS Code with one file that carries both hook formats. `--tool copilot-repo --repo <app>` writes the hook into the app's own `.github/hooks` for the Copilot cloud agent and JetBrains, with nothing written to your home folder.+- Kimi Code gets one marked block appended to its config (`$KIMI_CODE_HOME/config.toml` when that is set), and the rest of that file, which can hold API keys, is never rewritten or printed. Uninstall restores the file exactly. A config that already defines `hooks` inline, as a table or as a quoted key, or with an escaped quoted key, or that would not stay valid TOML (on a fresh append and on a repair of its own block), is left unchanged and the block to add by hand is printed, because TOML cannot mix the two forms. Factory Droid keeps using `settings.json` when its hooks already live there, because Droid ignores them once `hooks.json` exists.+- The guard reads the request format of Grok, Factory Droid, Augment Auggie, Windsurf, VS Code, Kiro and Goose, and finds the project folder from each tool's own field.+- A version you can see. `VERSION` holds 2.0.0, `install.sh --version` prints the checkout's version, every install records it next to the skill, and `doctor` prints the installed one and says when the checkout is newer.+- On Windows (Git Bash, MSYS, Cygwin) the installer registers the hook for both Bash and PowerShell, and `doctor` proves a PowerShell submit command is blocked.+- Guard app root detection, two edges left open by #612. A React Native or Expo app with no app.json or app.config is now its own app when its package.json lists react-native or expo under dependencies and it owns an ios or android folder, so a member whose native folder holds no project file yet no longer pools into its sibling (#655). A dev or peer dependency never counts, and a native-module library with peerDependencies stays a library. A directory linked into the tree from outside it is followed one level when its target carries an app marker, unless the link is named like a vendored folder (vendor, build, node_modules and the other names the scan already skips), and scanned through its target as its own app (#657). A link back into the tree, to an ancestor, or to itself is skipped, and the target is read without following any further link, so a cycle cannot hang the scan. A linked ios or android platform folder is still not followed. How a nested bare Xcode or Android project under a root framework app is scanned is covered by the #656 entry above. A linked app is scanned beside the project, never in place of it, so a clean linked app cannot hide the project's own findings, and an empty project root beside a linked app is not reported as NOT CHECKED, unless a framework app under it still needs its native folders, which keeps NOT CHECKED. A linked Unity, MAUI, Tauri, Cordova or Capacitor app is followed too, and two links to one app scan it once. 13 new test cases, 302 total, green on bash 5 and macOS bash 3.2.- README first-run path. A Start here table routes four kinds of reader to one action each, with the time it takes. The two-command check comes first, followed by what each last line of the guard means. The install section lists everything it writes and the undo command before the paste block. New short sections cover troubleshooting and the five words a newcomer has to know. Driven by 40 persona walks (a second model as 24 readers, and two reviewers who ran every README command in a throwaway home folder).-- `scripts/check-docs.py`. Fails CI when a Markdown file names a link, heading anchor, image, repo path, script or flag that does not exist. 9 tests prove it fails on each kind.+- `scripts/check-docs.py`. Fails CI when a Markdown file names a link, heading anchor, image, repo path, script or flag that does not exist. 11 tests prove it fails on each kind.- The guard ends every run with a verdict. `CLEAR.` when no critical risk was found, `NOT CHECKED.` with exit 1 when the folder holds no iOS or Android project (an empty folder and an Expo app with no native folders used to look like a clean pass), and a `Next.` line after `BLOCKED.`. As a hook it still never blocks a project it could not scan.- `monitor.py --full`. A live report over 25 items now opens with a count per track and shows the first 10 (3,503 lines became 194). `--json` is never cut.- The checklist opens with the two checks that stop most rejections and says how long a full pass takes. CONTRIBUTING explains how to fix a wrong citation.-- README. A second approval proof, a developer's App Store Connect approval mail shared with thanks for the playbook, stored as assets/app-store-approval-thanks.png with the sender's name removed.-- One command install for Claude Code. `scripts/install.sh` copies the guard, the skill (now with `.citation-allowlist`) and the `/app-store-audit` command, adds one PreToolUse hook entry to settings.json while keeping every other key and writing a backup, then runs the guard against a sample app that must be blocked. `doctor` checks an existing install, `uninstall` removes it, `--dry-run` writes nothing. The check runs the registered command string itself, so an entry on the wrong matcher, behind a comment, or with an unquoted path fails it. A settings.json that is read-only, not valid JSON, or repeats a key is never rewritten. Before this the install was a prose prompt with no settings example and no way to tell whether it worked. 27 tests, in CI.+- One command install for Claude Code. `scripts/install.sh` copies the guard, the skill (now with `.citation-allowlist`) and the `/app-store-audit` command, adds one PreToolUse hook entry to settings.json while keeping every other key and writing a backup, then runs the guard against a sample app that must be blocked. `doctor` checks an existing install, `uninstall` removes it, `--dry-run` writes nothing. The check runs the registered command string itself, so an entry on the wrong matcher, behind a comment, or with an unquoted path fails it. A settings.json that is read-only, not valid JSON, or repeats a key is never rewritten. Before this the install was a prose prompt with no settings example and no way to tell whether it worked. 62 tests, in CI.- Apple, September 2026. The EU App Tracking Transparency alternative prompt from iOS 27.2 (the only version in Germany, France, Italy, Poland, and Romania), multiseat subscription purchases enabled by default with Volume Purchasing on 22 October 2026 as deadline APPLE-MULTISEAT-VOLUME-PURCHASING, Bundles and Suites, the 27 August tax and price updates, and the 27.2 betas. Each read from Apple's own post on 30 September 2026.- The validator fails a deadline whose `affected_repository_sections` names a file that does not exist. Four entries pointed at a missing by-app-type file and now point at social-and-user-generated-content.md.- The two deadlines of 1 October 2026 (Play US alternative billing reporting, Apple EU unified terms) carry `absorbed_into`.-- Validator deadline rules (#660). `scripts/validate.py` fails an entry whose effective date is after its mandatory date or whose mandatory date is after its enforcement date, and fails a deadline that passed more than 7 days ago with no `absorbed_into`. Inside the 7 days it warns. `scripts/test-validate.py` pins both with eight cases. AGENTS.md records the policy for a postponed, withdrawn, or narrowed deadline.- Guard scan time (#658). The guard prints `Scan time. Ns` after the summary, and past 45 seconds it names the hook timeout setting to raise. The threshold reads APP_STORE_GUARD_SLOW_SECS. The time sits on its own line because the gauntlet compares the summary line across interpreter tiers. Five new cases, 189 total.- The three deadlines of 30 September 2026 (Android developer verification sideloading leg, Play organization registration for regulated categories, Play package name registration) carry `absorbed_into`.-- iPhone Duo readiness (#724). Deadline APPLE-IPHONE-DUO-LAUNCH (pre-order 16 October 2026, ships 23 October 2026), PLATFORM-MECHANICS section 1.8 covering the Xcode 27.1 build, size classes and scene bounds, reserved regions around the cameras and the fold, arrangement views, vertical bars, camera direction, and the App Store asset status (specifications published, uploads not yet open, no Duo-specific review rule published), plus three pre-submission checklist items. Sourced from Apple's newsroom, developer documentation, and HIG pages.+- iPhone Duo readiness (#724). Deadline APPLE-IPHONE-DUO-LAUNCH (pre-order 16 October 2026, ships 23 October 2026), PLATFORM-MECHANICS section 1.8 covering the Xcode 27.1 build, size classes and scene bounds, reserved regions around the cameras and the fold, arrangement views, vertical bars, camera direction, and the App Store asset status (specifications published, Duo uploads open since 5 October 2026, no Duo-specific review rule published), plus three pre-submission checklist items. Sourced from Apple's newsroom, developer documentation, and HIG pages.- Project board at github.com/users/mjmirza/projects/3 with the roadmap, one issue per dated deadline milestone through May 2027, and the guard limits from #614 as tracked enhancements. Labels for area, priority, type, and platform on the repo. README links to it from Contributing.- September 2026 gap analysis, docs/GAP-ANALYSIS-2026-09.md. 22 rejection patterns (Apple social media declaration gate, Sign in with Apple relay domain, RESCIND_CONSENT, external purchase link region gating, Live Activities, On-Demand Resources deprecation, removed App Store Connect age-rating endpoints, Rosetta sunset, Play chargeback liability, donation links, organization registration, package registration, Contact Picker and location button and geofence rules for API 37, ACCESS_LOCAL_NETWORK, R8 optimization, Restore Credentials, generative AI NCII controls, anonymous chat minor blocking, unrated apps, developer account enrollment readiness), 20 regulatory deadlines (US ADA Title II and HHS 504 extensions, FTC COPPA age-verification policy, UK DUAA, ICO storage guidance, DMCCA subscriptions, under-16 ban, Ofcom app stores report, EU AI Act marking retrofit, Product Liability Directive, Data Act switching, eIDAS wallet, CSAM derogation expiry, Korea PIPA, China AI companion measures, Singapore OSRAA, India Consent Managers, Japan APPI), 16 new guard checks with 16 gauntlet cases, and an account and program readiness section in the pre-submission checklist.- Apple, September 2026. The April 2027 SDK 27 upload floor as deadline APPLE-SDK-27-REQ (month only, tracked as 1 April 2027), the 19 August App Store Connect form rules (international phone format for the App Review contact, first in-app purchase of each type submitted with a new app version), the 9 September screenshot specifications for iPhone Duo, iPhone 18 Pro and Pro Max, Apple Watch Ultra 4 and Series 12, and four matching pre-submission checklist items. The Rosetta sunset pattern now records both Apple notices, which disagree on whether macOS 26 or macOS 27 is the last release with Rosetta.- Licence. The whole repository moved from a dual MIT and CC BY 4.0 grant to the OpenRoots Agent License 2.3 (via ORA 1.0 on 24 August 2026, then 2.3 on 27 August 2026). One licence now covers code, docs, data, the skill, and the guard. Releases before 24 August 2026 keep MIT and CC BY 4.0 irrevocably. LICENSE is a pointer to the canonical text at openroots.org.+- docs/GLOBAL-REGULATORY-2026.md section 2.7 and data/rejection-patterns.json BOTH-SUBSCRIPTION-HARD-CANCEL. US subscription cancellation (negative option) coverage was completely absent. Live-verified the federal FTC click-to-cancel rule's vacatur by the Eighth Circuit (8 July 2025) and its reopened rulemaking (ANPRM, 11 March 2026), documented that California, New York, and Massachusetts have their own binding negative-option statutes regardless, and that the FTC retains Section 5 and ROSCA authority. Added a matching guard check and detection recipe for a subscription flow that requires a phone call, mail, or an in-person visit to cancel.+- AGENTS.md. Release review guidelines for AI agents (a 14-item checklist) plus a strict source trust hierarchy and verification rules every monitor script follows before citing a claim as fact.+- scripts/monitor-regulatory.py. The Regulatory Intelligence Agent, tracking EU/UK/US/CA/AU/SG regulatory developments through a source trust hierarchy classifier, with its own test suite.+- scripts/monitor-android.py and docs/ANDROID-POLICY-MIGRATION.md. Android and Google Play requirements compliance monitoring, with its own test suite.+- scripts/monitor-ai-policy.py and docs/AI-POLICY-MIGRATION.md. Platform-specific generative AI policy monitoring (Apple and Google), with its own test suite.+- scripts/deadline-checker.py and data/regulatory-deadlines.json. A timezone-aware regulatory deadline checker over a 90-day window, wired into the guard hook automatically.+- scripts/release-audit.py. A release readiness compliance audit engine that writes RELEASE-READINESS-REPORT.md into the audited project (gitignored, never a committed fixture).+- scripts/accessibility-audit.py. A continuous accessibility compliance audit (VoiceOver, Dynamic Type, Reduce Motion, contrast, TalkBack, touch targets), runnable standalone and deliberately not wired into the guard hook.+- Mobile and web privacy compliance monitoring, folded into the guard hook and the pattern taxonomy.+- docs/MOBILE-SECURITY-2026.md. A mobile security requirements playbook and matching guard checks (secure storage, insecure backup, unsafe deep links).+- Brazil SPA fixed-odds betting license and Google Play Age Signals compliance checks in the guard hook and pattern taxonomy.+- Apple accessibility guard checks (VoiceOver, Dynamic Type, Reduce Motion, color contrast, haptics, keyboard focus) and privacy nutrition label checks.+- docs/EU-REGULATORY-2026.md. The EU legal hard rules with dated sources and Apple developer citations. the EU AI Act (Article 50 transparency by 2 August 2026, Article 4 AI literacy, Article 5 prohibited practices, Article 99 penalties, provider versus deployer), the Digital Markets Act (distribution channels, notarization, external purchase entitlement and disclosure sheet, the Core Technology Fee and Core Technology Commission, the 500 million euro anti-steering fine), DSA trader status (Apple removal from 17 February 2025), the European Accessibility Act (in force 28 June 2025, EN 301 549 and WCAG 2.1 AA), and the Apple 2025 and 2026 platform changes (age rating deadline 31 January 2026, Guideline 5.1.2(i) third-party-AI consent, the Declared Age Range API, mini apps 4.7, Xcode 26 SDK deadline 28 April 2026).+- docs/GLOBAL-REGULATORY-2026.md. The USA and other-global legal hard rules with dated sources. US COPPA and the amended rule, the state app-store age-verification laws, the external-link rules after the Epic injunction, US state privacy laws, plus the UK Online Safety Act and Children's Code, Australia, Brazil, Canada, South Korea, India, and other jurisdictions, and what Apple tells developers to do per region.+- An EU legal gate section in docs/PRE-SUBMISSION-CHECKLIST.md.+- Pointers from the Advanced 2026 legal layer and the README docs index to the new EU and global legal docs.+- docs/PLATFORM-MECHANICS-2026.md. The platform-mechanics and newer-policy hard rules with dated sources and Apple, Google, and statutory citations. Apple (macOS notarization with notarytool and stapler, Guideline 4.2 minimum functionality and 4.3 spam or duplicate with the June 2026 saturation tightening, the reader-app External Link Account Entitlement, the France ANSSI encryption declaration matrix, the content-rights declaration, visionOS App Motion and Developer Capture, the watchOS and tvOS 26 SDK deadline, In-App Events and Custom Product Pages and the submission-concurrency limit), Android (developer verification with the 30 September 2026 country deadlines, Foreground Service types, the Play Integrity move off SafetyNet, Play Billing Library v8 by 31 August 2026, target API 35 now and 36 by August 2026, disruptive-ads and interstitial rules, Health Connect, real-money games, and the Photo Picker and deletion-URL rules), and cross-cutting (CSAM and NCMEC reporting, UGC controls and the Google Play Child Safety Standards, accessibility as a review dimension, account-and-data deletion URLs, OFAC sanctions, ADA Title III, and PSD2 SCA and PCI DSS).+- A platform mechanics gate section in docs/PRE-SUBMISSION-CHECKLIST.md, and pointers to the new doc from the Advanced 2026 layer, the README docs index, the agent skill, and the audit command.### Fixed+- Workspace runners are scanned. `yarn workspace x <script>`, `pnpm --filter x`, `npm -w x` or `--prefix`, `bun --filter`, `turbo run`, `lerna run` and `nx run x:target` resolve the script or nx target in the package they name. Without a named package, `turbo`, `lerna` and `nx run-many` read every package, and a named package that cannot be found falls back to every package. The whole command is read as one runner, as in 1.0.0, with a plain `npm`, `pnpm` or `bun run` tried first so runner words inside its arguments never take over, and every runner in a compound command, a `$(...)` or backticks is read on its own too, so a later web build never masks an earlier submit script. The `bun ship`, `turbo ship`, `pnpm -r ship` and `nx ship mobile` shorthands and `nx run-many` or `nx affected` with `-t` or `--target` are read too. An nx command without `project:target` reads every package. An nx target whose options nest an object, such as `env`, is still read to its command. `bun run --filter x ship` and several `--filter` selectors in one command are read, as is lerna `--scope`, and a pnpm graph selector such as `web...` or `{apps/web}` is reduced to its package name. An exclusion-only filter such as `--filter '!docs'` reads every package. Recursive forms (`-r`, `--recursive`, `-ws`, `--workspaces`, `yarn workspaces foreach`) read every package, a scoped `@scope/name` matches only that package, and the root package.json always counts.+- Without jq or python3, a payload with more than one tool name field is scanned rather than trusted, so nested metadata cannot hide a Bash submit.+- A Tuist `Project.swift` purpose string counts as the key.+- The restore check now also covers a cross-platform purchase plugin app (1.0.0 checked only native StoreKit apps), where the plugin's purchase list call (getAvailablePurchases, queryPastPurchases) counts as the restore flow. A native StoreKit app still needs a real restore call, as in 1.0.0.+- The OpenCode plugin refuses a submit-looking command when the guard itself cannot run (missing file, crash, timeout), and logs the problem for other commands. It reads the command with quotes and backslashes removed and every whitespace run as one space, as the guard does. OpenCode loads both plugin folders, so a call one copy already checked is skipped by the other. Without node the plugin cannot be exercised, so the install ends with `Installed, but not fully verified.` instead of `Install verified.`+- Claude Code `doctor` fails when the registered hook is not a command handler or its timeout is under 30 seconds. Every non-Claude `doctor` says when this checkout is newer than the installed skill.+- A git commit whose message sits beside a `$(...)`, backtick, process or zsh `=(...)` substitution is scanned in full, so a submit run inside that substitution is never hidden as message text.+- An Android word inside a quoted argument, such as a lane parameter `notes:"test -p android"`, is text and never turns the Apple checks off. Each command in the line is read twice, once with quoted text kept and once with it blanked, and `#` comments dropped, on macOS bash 3.2 as on bash 5 (a test runs the guard under the system bash itself). A submit is recognised from the kept text, so a quoted lane name such as `fastlane "beta"` still counts, and its Android word only from the blanked text. Every submit must name Android itself, and any other command that is not known to be harmless keeps the Apple checks, so a harmless `echo -p android` beside an iOS lane never vouches for it. An Android build stays Android only when every other command beside it is known to be harmless (cd, echo, export, ls and similar) and holds no `$(...)`, backtick, process substitution or zsh `=(...)`. git is never on that list, because an alias, a configured diff helper, a filter or an fsmonitor hook can run anything, so a git command beside an Android build keeps the Apple checks on. Anything else, such as `npm run`, `make`, a script or `python3 upload.py`, may upload to Apple, so the Apple checks stay on. Any `ios`, `ipa` or Apple upload word anywhere in the command keeps them too, as before 2.0.0. On top of all this, the command must still pass the 1.0.0 Android rule (`build apk`, `assembleRelease`, `bundleRelease`, `run-android`, `--platform android` and the rest), so no command turns off the framework checks where 1.0.0 ran them. A real Android build in a repo that also holds an iOS app still skips the native Apple checks, by design. A flag form 1.0.0 did not know, such as `eas submit -p android`, still runs the Apple checks. A wrapped submit (`npm run`, `make`) is Android only when every command that is not known to be harmless names Android itself, so an `echo --platform android` beside `npm run ship` never turns the Apple checks off. A submit quoted inside a shell (`bash -c`, `sh -c`, `eval`, by path such as `/bin/bash`, or behind `env` or `sudo`) never takes an Android word from the outer arguments, because they never reach it. The same holds for a submit seen only inside quotes, such as one run by `python3 -c` or `ruby -e`.+- The trigger checks (is a camera, location or payment API used) read every source line raw, as in 1.0.0, so no comment rule can hide a live call, a Swift interpolation on a line led by `//` included, and a mention in a comment counts as it did in 1.0.0. Only the account deletion and ATT authorization implementation checks drop comments (the restore check reads source raw, as in 1.0.0), line by line with no string state, so a misread quote can never hide the lines after it. They drop block comment lines (the code after a closing `*/` on its line still counts), a trailing `//` and a closed `/* */` on the line, unless the rest of the line holds JSX or the marker sits inside a single, double or backtick quoted string (an escaped quote such as `\"` does not end the string, outside a Swift raw string, and a quote inside a JavaScript regex literal such as `/"/`, after an operator (`= ( , : & | ! ? { } ; + - * % < > ~ ^`) or `return`, is not a string quote). A removed inline comment leaves a separator, so the words on either side never join into a marker such as `account deletion`, so a deletion written only in a comment never counts and real code between two quoted markers always does. An HTML `<!--` opens a comment only at the start of a line or right after a tag, and one that never closes was a misread string, so the markup after it still counts.+- `InfoPlist.strings` is no longer read at all, so translated text can never stand in for StoreKit, a Restore Purchases control or any other implementation.+- With neither jq nor python3, a payload from a named tool that is not a shell (such as Read) stays quiet, the same as with a parser.+- A commit or gh message whose quote is left open at a line end spans lines in bash, so the whole command is scanned unmasked and a submit after it is never hidden.+- Kiro's PowerShell tool (`execute_pwsh`) is read like `execute_bash`.+- A purpose string in an XcodeGen include file, an Nx `project.json`, a Tuist helper under `Tuist/` or a Cordova `config.xml` counts, as in 1.0.0.+- A jq-only uninstall on Windows removes an owned hook under any matcher, so an old `Bash`-only entry no longer survives.+- Copilot `doctor` checks the Windows `powershell` handler against the exact command the installer writes, so an edited handler fails.+- When the guard cannot write its scan buffer beside its file list, it falls back to `/tmp` as before 2.0.0, so the source scan still runs.+- A git message is treated as text only for a plain `git commit`, `tag` or `notes` (with at most `-C <dir>`). A git alias or any other global option keeps the whole command scanned, because an alias can run its arguments.+- metadata-audit needs a Terms of Use or EULA link in the description, with a path naming terms, EULA, conditions or licence, or the whole word ToS, AGB or legal, and never a privacy page. Apple's standard EULA counts only as that page on apple.com, never as text inside another URL, and the word terms or EULA in the description or promotional text. A separate `terms_url` field, a privacy link, or a host that merely contains tos (photos.app) no longer satisfies it. With `--check-urls`, a malformed URL is reported instead of skipped.+- Two installs of one tool in different config folders (two `CODEX_HOME` or `QWEN_HOME` values) each own the shared skill. Uninstalling one keeps the skill for the other.+- Kimi uninstall restores the config byte for byte, trailing newlines and CRLF line endings included. A CRLF config is matched and stays CRLF on every platform, so a second install changes nothing.+- `--tool all` expands a `QWEN_HOME` written as `~\folder` the same way the installer does.+- The agent paste block in the README and the guard table in the skill list all twelve supported tools.+- The guard catches Grok Build's native shell tools (`run_terminal_command`, `run_terminal_cmd`, `monitor`, `bash`). Before, a real Grok session ran a submit command without any check. The Grok install matches all four, doctor tests the real payload, and install repairs an old `Bash`-only entry.+- A command segment that runs an Apple upload is never treated as Android only. An Android word must be the actual gradle task, flutter build verb or platform flag, never text inside another tool's argument.+- metadata-audit keeps the longest value when two files supply the same field, and reports the conflict instead of hiding an overlong name. Every combination of the conflicting values is audited too, across fields, up to 4096 combinations (the report says when it stopped early), so no pairing of a kept and an unkept value hides a rejection risk. A value in a nearer folder, a locale or on the command line overrides a conflict between files further up, and the last command line value for a field wins whatever alias named it. A locale also inherits a fastlane `default/` folder beside it, which wins over a file further up as in fastlane, and both values are audited, so a name kept only in `default/` is audited with the locale's own keywords, and `default/` itself is not audited as a listing when real locales sit beside it.+- A git or gh message is treated as text only inside its own command segment, so a later `bash -c` with a `-m` argument that runs a submit is still scanned.+- Android-only targeting is decided per submitting segment. A compound command that also uploads to Apple keeps every Apple check, and every `-p` or `--platform` form (`-p android`, `--platform=android`, `-p=android`) is recognised.+- Account deletion and the App Tracking Transparency prompt must appear in source or HTML. A mention in a `.strings`, plist or json file no longer satisfies them.+- Cursor `beforeShellExecution` always gets permission JSON on stdout (`allow`, or `deny` with exit 2), with the report on stderr. Before, an allowed submit printed prose, which Cursor treats as invalid.+- Single-quoted and bare keys in a managed Expo `app.config` file are read.+- With neither jq nor python3 installed, a Copilot `toolArgs` JSON string is parsed instead of passing unchecked.+- Uninstalling one tool no longer deletes the shared skill another tool still uses, in either install order.+- `doctor` and `install` check the hook's matcher, handler type, timeout and that it is not asynchronous (an async hook cannot block), not only its command, with python3 and with only jq. The Gemini audit command stays valid TOML when its paths hold Windows backslashes. Copilot follows `COPILOT_HOME`, as Copilot does. Install repairs a hook that would never run, and Kimi doctor tests the command written in `config.toml`.+- The Copilot hook carries a `powershell` handler for Windows that passes the guard's exit code through.+- On Windows, reinstalling widens a Bash-only Claude Code hook to `Bash|PowerShell`, and `doctor` checks that the matcher covers both.+- Auggie gets the guard's executable script path, as its hook docs require, instead of a shell command string.+- `doctor` fails when Qwen Code or Copilot has `disableAllHooks` set to true, because then no hook runs. A Copilot hooks file whose `version` is not the number 1 (`true` is not 1) is repaired and the repair is written even when the handlers are fine (Copilot rejects the whole file otherwise). `doctor` fails when Gemini CLI has `hooksConfig.enabled` set to false. A Cursor handler counts only as a command hook whose matcher takes the submit commands, and a Cursor `version` that is not a positive whole number is repaired. and a Copilot or VS Code handler whose `matcher` skips the shell tools counts as not registered, so a reinstall repairs it. A Kimi hook counts only with Kimi's own four keys and an integer timeout from 120 to 600, as the Kimi client accepts, so a reinstall repairs any other.+- The Qwen Code install, `doctor`, `uninstall` and `--tool all` follow `$QWEN_HOME` when it is set. A Qwen handler counts only with `"type": "command"` and a timeout Qwen gives at least 120 seconds (Qwen reads 1000 or more as milliseconds), so a reinstall repairs any other and `doctor` fails on it.+- `release-audit.py` run from the shared skill in `~/.agents` finds the guard installed under the tool's own folder.+- `metadata-audit.py` applies the Google rules when given `metadata/android` or one of its locale folders directly.+- The installed-layout release-audit test fixture includes `VERSION`, so all 19 of its tests run.+- A privacy purpose string kept only in `InfoPlist.strings` no longer counts. Apple reads the key from `Info.plist` or the `INFOPLIST_KEY_` build settings, and rejects an upload without it (ITMS-90683). That file only translates a key that already exists.+- Eight guard rules tightened after an adversarial review. A purpose string named only in a code comment no longer passes. App Tracking Transparency needs both the purpose string and the authorization call, and the finding names the missing half. A privacy manifest inside `Pods`, `node_modules` or another dependency folder no longer counts as the app's own. The restore check covers the framework purchase plugins. An Android-only build never meets an Apple finding. A temp folder that cannot be written gives NOT CHECKED, never CLEAR. A managed Expo app has its app config read. The text of a commit or pull request message is no longer scanned as a command.++- The guard silently let through submit commands from every AI coding tool except Claude Code and Codex. It accepted only the tool names Bash and PowerShell, so Gemini CLI (`run_shell_command`), OpenCode (`bash`) and Copilot CLI (`toolName` with `toolArgs`) never reached the scan. It now reads every one of those shapes on the jq and python3 tiers, and uses the `cwd` the tool sends when `CLAUDE_PROJECT_DIR` is not set. A non-shell tool such as a file write stays silent.+- A fastlane global option before the action or lane hid the submission. `fastlane --verbose deliver`, `fastlane --env production deliver` and `bundle exec fastlane --verbose pilot` all passed unchecked. Options are now dropped before matching, and `fastlane --version` still stays silent.+- A guard installed outside `~/.claude` skipped the deadline list and the privacy manifest validator, because it looked for them only there. It now also looks in the shared `~/.agents/skills` folder the other tools read.+- With jq and no python3, the installer collapsed a repeated key in settings.json, keeping only the last one, which could turn a deny rule into an allow. It now leaves such a file untouched and prints the block to paste, the same as the python3 path.+- The `/app-store-audit` command pointed at `~/.claude/rules/app-store-compliance.md`, a file no install creates. The reference is gone.+- Release audit. A scanner that failed or checked nothing still produced `CLEAR TO SUBMIT` and exit 0, and a high finding was approved as advisory. Now exit 0 is clear, exit 2 is blocked on a critical or high finding, and exit 3 is incomplete, with the scanner's own output shown. `--metadata <dir>` audits a pulled store listing, and without one the run says exactly what to pull. The guard is found next to an installed skill too, so the installed copy no longer aborts.+- Metadata audit. Every locale is audited on its own, so a short German name with a violation is no longer hidden behind a longer English one. `--platform google` applies the Google Play limits (title 30, short description 80, full description 4000) and drops the Apple-only rules. Every URL must be a real http or https address, an Apple listing needs a support URL, a Google listing needs a contact email, and a subscription needs a real Terms or EULA link, not the word terms. The link is found in any letter case, so `HTTPS://` counts like `https://`. fastlane's `review_information` and `trade_representative_contact_information` folders hold app review details, not a listing, so they are not audited as a locale. Their review notes are still audited for content, once, with the first listing of their own app, and they win over a locale's own review notes, which fastlane ignores, though both are audited, so two apps in one folder never share or overwrite each other's notes.+- The regulatory and privacy monitors trusted a source by substring, so `ftc.gov.attacker.invalid`, `[email protected]`, and an article merely titled with an agency name all counted as official and verified. Trust now comes only from the URL host, matched on a domain boundary, and a lower-trust item is verified only when an official host covers the same topic.+- The pre-submission checklist made every box a blocker, so an app with no login or no purchases could never finish it honestly. An item can now be marked not applicable with a one-line reason, except the privacy declaration and the privacy policy URL. Repository paths in it are now links, and SPKI, PKCE and PCI SAQ are explained at first use. The cross-platform frameworks doc now states the real detection depths and what the guard matches.+- Two test suites, the privacy manifest validator and the citation verifier, passed locally but never ran in CI. They do now. A guard test that scanned whatever folder it was started from now scans its own fixture.+- README. The first-run command quotes the app path, so a folder with a space in its name is scanned whole, and it says how to get the path by dragging the folder into the terminal.- Apple monitor keyword matching (#833). Keywords and patterns matched as substrings of the raw feed HTML, so "pla" hit "display" and "platforms", "att" hit "pattern" and "attention", and "dma" hit "admin". On the live feed, 86 items landed under License Agreement and 21 under App Tracking Transparency. Matching now runs on the visible text. Terms shorter than 8 characters match as whole words with an optional plural, and a version may follow ("WCAG2.2"). Longer terms still match inside identifiers such as `NSCameraUsageDescription` and `CLLocationManager`. License Agreement drops to 14 genuine agreement and terms posts, and "vulnerabilities" and "in-app purchasing" still match.-- AI policy monitor feed items are reduced to plain text before matching, so a keyword inside a link target no longer counts (adopts #954, with the test it lacked). Atom title, summary and content are stripped only when their type is html or xhtml, so a plain-text field keeps its angle brackets (RFC 4287 section 3.1.1). A MIME type such as text/html or application/xhtml+xml is honored, XHTML inline elements (span, b, a and the like) run on while every other element keeps a space around its text, and an entry's summary and content both count. A MIME parameter such as `; charset=utf-8` is ignored, binary content is not searched, script and style text never counts, an extension element from another namespace never stands in for the feed's own title or summary, an RSS title has its entities decoded but its angle brackets kept (in both monitors), and inline HTML tags join their text instead of splitting words. Both monitors strip comments and tags in one linear pass. A quote inside a comment can neither leak markup nor swallow the text after it, a `<!--` inside a quoted attribute is not read as a comment, and the endings browsers accept (`<!-->`, `<!--->`, `--!>`) close a comment the way a browser closes it. CDATA sections and `textarea` or `title` content stay visible text, an unterminated `<!x` declaration ends at the end of the input, and tag names and delimiters are matched as ASCII the way HTML does, so a non-breaking space or a dotless i cannot change what counts as visible.+- AI policy monitor feed items are reduced to plain text before matching, so a keyword inside a link target no longer counts (adopts #954, with the test it lacked). Atom title, summary and content are stripped only when their type is html or xhtml, so a plain-text field keeps its angle brackets (RFC 4287 section 3.1.1). A MIME type such as text/html or application/xhtml+xml is honored, XHTML inline elements (span, b, a and the like) run on while every other element keeps a space around its text, and an entry's summary and content both count. A MIME parameter such as `; charset=utf-8` is ignored, binary content is not searched, script and style text never counts in XHTML content, an extension element from another namespace never stands in for the feed's own title or summary, an RSS title has its entities decoded but its angle brackets kept (in both monitors), and inline HTML tags join their text instead of splitting words. Both monitors strip comments and tags in one linear pass. A quote inside a comment can neither leak markup nor swallow the text after it, a `<!--` inside a quoted attribute is not read as a comment, and the endings browsers accept (`<!-->`, `<!--->`, `--!>`) close a comment the way a browser closes it. CDATA sections and `textarea` or `title` content stay visible text, an unterminated `<!x` declaration ends at the end of the input, and tag names and delimiters are matched as ASCII the way HTML does, so a non-breaking space or a dotless i cannot change what counts as visible.- Accessibility audit (#834). A SwiftUI Button whose label shows an `Image(systemName:)` with no Text, Label or accessibility label is now reported as a possible icon-only Button under APPLE-ACCESSIBILITY-VOICEOVER, in the trailing closure, `label:` closure, and inline `label:` argument forms, written as `Button` or `SwiftUI.Button`, including `Button(role:) { action } label: { ... }` where the first closure is the action. The whole label closure counts, by design. The audit reads code without running it, so a Text anywhere in the label hides a possible icon-only Button and an unused Image can raise one. The README states this limit, and tests pin it. Swift regex literals in the #/.../# form are skipped, inside string interpolation too, and a backslash-escaped delimiter inside one does not end it early. Scanning stays fast on hostile input (nested Buttons, nested labels, nested modifiers, long chains of local bindings), and string interpolation of any depth is walked with an explicit stack instead of recursion. Only the Button's own modifier chain can supply the label, never a sibling on the same line, and a modifier with several trailing closures (`.contextMenu { } preview: { }`) does not end the chain early. A Button titled by a variable, a Button inside one or more parentheses, a spaced member dot, `#if` blocks between modifiers, escaped names in backticks, `.accessibility(label:)`, `.accessibility(hidden: true)`, `.accessibilityRepresentation` and `.accessibilityHidden((true))` are all read, and a label with `isEnabled: false` does not count. Comments, nested comments, raw strings and multiline strings are ignored, so a Button that only appears in text is not a control. The haptics rule fires only on a real `.onTapGesture` or `Button`, and is LOW and labelled advisory because neither WCAG 2.2 nor EN 301 549 requires haptics. An unknown `--rule` used to print Clean and exit 0. It now exits 2 and lists the known rules.- iPhone Duo App Store assets (#724). The docs said App Store Connect did not accept Duo screenshots yet. Apple opened Duo submissions and screenshots on 5 October 2026, with a product page badge for apps that upload them, and set April 2027 for Duo screenshots to become required for apps using the iOS 27.1 SDK or later, the scope Apple's screenshot specification page states. PLATFORM-MECHANICS section 1.8, the checklist, the gap analysis open item, and the Duo launch deadline now say so, and a new deadline APPLE-IPHONE-DUO-SCREENSHOTS-REQ (tracked as 1 April 2027, month only) carries the requirement. Read from Apple on 15 October 2026.- EU alternative payments. Under Attachment 14, in force 1 October 2026, an EU app may combine Apple In-App Purchase, alternative payment processing and out-of-app offers. The EU doc, the checklist and the DMA deadline still said they could not be mixed. They now state Apple's current terms. In-App Purchase is shown at the same time and at least as prominently, the chosen options stay in place across EU storefronts for 12 months, the entitlement is the StoreKit External Purchases or Offers Entitlement, and reporting runs through the External Purchase Server API on OS 26.4 or later. Ask to Buy is no longer listed as a lost capability, because Apple's page does not list it. The checks now include Apple's child safety rules (parental gates for minors, no out-of-app purchase on a website for Kids category apps, no out-of-app offers at all for the youngest users, higher age thresholds where a storefront sets them), the rule for apps that offer only alternatives, and the payment entitlement's own minimum OS versions. Read from Apple on 15 October 2026.@@ -52,7 +142,6 @@ All notable changes to this playbook are recorded here. The format follows Keep- `metadata-audit.py` on a folder with no listing files, or on a path that does not exist, exited 0. It exits 1 and names the files to add.- `release-audit.py` ran silently for about two minutes. It now labels its two steps and says how long the first takes.- README said four sibling monitors and listed eight commands, showed the manual audit as a relative path, and promised a "clear to submit" line the guard never printed.-- Guard submit detection (#836). In hook mode a custom fastlane lane (`fastlane ios beta`, `bundle exec fastlane release`), a Gradle Play Publisher task (`publishBundle`, `publishReleaseBundle`), `eas` with a flag before the subcommand, and a submit wrapped in a package script or a make target all passed with no scan. They are now matched, a lane by its name or by an upload action in its Fastfile block, a wrapper one level deep. A second attack pass added package manager options before `run` (`pnpm --dir`, `npm --prefix`), `make -f`, legacy `expo upload`, and a lane or Gradle task held in a shell variable, which is scanned because it cannot be read. Lane names are matched on whole words, so `restore_state` stays silent, and `npm install bundletool` no longer triggers a scan. 45 new tests pin what blocks and what stays silent. `gh workflow run` and deeper nesting remain out of reach (#837).- The guard ignored PowerShell tool payloads, so Claude Code on Windows never triggered it. It reads them now.- `guard.sh /missing/path` exited 0, which read as a clean pass for a path that was never scanned. It exits 1 and says the path is not a directory.@@ -60,7 +149,6 @@ All notable changes to this playbook are recorded here. The format follows Keep- The guard report printed every deadline in full, about 170 lines, ahead of the findings. It prints one line per open deadline and the command for the full list.- `verify-citations.py --files` with a path that does not exist printed "no URLs found" and exited 0. It exits 2 and says nothing was checked. The README step that ran it from the wrong directory is corrected.- The pre-submission checklist still described the Play Billing v8 and target API 36 floors as upcoming. Both are stated as in force since 31 August 2026 with the extension date.-- Bot PR review, 30 September 2026. The 97 scheduled Jules PRs opened since 19 September were triaged. 38 carried an empty commit. The other 59 were reruns of the same 12 jobs (the release audit branches add an untested report flag and a dated snapshot, and two of them rewrite a tracked doc on every run), each reviewed against master with tests run and added citations checked live. Four small parts were adopted with a test each. the Apple monitor keywords from #812, the pyenv-safe python lookup in the guard gauntlet from #810, the AI monitor word stems from #779, and the accessibility CI step from #819. Every PR was closed with its reason. No dated report was adopted. The reports again presented the monitors' sample announcements as verified findings, one stated the vacated FTC click to cancel rule as mandatory, one gave 17 February 2025 for the Digital Services Act where Article 93 says 2024, and two cited Apple API names that do not exist.- The deadline checker and the timeline counted days from the current time of day, so a deadline read as 1 day overdue on its own date and every upcoming count was one day short. Both now count whole UTC calendar days. The timeline generator accepts DEADLINES_FILE and TIMELINE_OUTPUT_FILE, so its tests no longer need to swap the real data file.- `monitor.py --simulate all` reached 24 of the 25 Apple tracks. The AI-related track matched none of its own sample text. It now matches, and the test counts all 25 tracks instead of spot-checking three.@@ -99,16 +187,12 @@ All notable changes to this playbook are recorded here. The format follows Keep- README, NOTICE, CITATION.cff, and CONTRIBUTING.md still described MIT, CC BY 4.0, or the retired ORA 1.0 sunset terms after the licence change. All four now state the same licence as LICENSE.- README listed no entry for docs/CROSS-PLATFORM-FRAMEWORKS.md, docs/PRIVACY-POLICY-MIGRATION.md, docs/SECURITY-POLICY-MIGRATION.md, docs/REGULATORY-TIMELINE.md, or the per-script test suites.- CHANGELOG claimed the README install prompt stars the repo and follows the author through the GitHub CLI. That step was removed in #140 and the prompt now explicitly forbids acting on the user's GitHub account.-- scripts/verify-citations.py and its 10-case gauntlet. A citation provenance verifier. An HTTP 200 is not proof a page is real, because developer.apple.com serves a byte-identical news index for any unknown article id. The verifier fetches a deliberately bogus control id per host and flags any citation whose content fingerprint matches that control. It separates bot-blocked 4xx and host-fault 5xx from genuine fabrication so the gate stays signal rather than noise. Found and fixed six dead or fabricated citations already present in the repo.- scripts/monitor-privacy.py and its test suite. Mobile and web privacy requirements monitoring across Apple, Google, and EU sources. Selected from eight competing implementations on citation integrity, the five-way majority version carried nine fabricated citations each.- scripts/monitor-security.py and its test suite. Seventeen mobile security requirements, matched against real API symbols in your code rather than prose keywords. Selected over a longer rival that detected nothing against a fixture of real API symbols.- scripts/generate-timeline.py and its test. Compiles a chronological regulatory timeline from data/regulatory-deadlines.json, cross-referenced into the playbook's own docs. Additive over deadline-checker.py, which only prints a rolling 90-day window.- scripts/accessibility-audit-test.sh. A test suite for the existing accessibility audit, proven to go red when a rule is mutated.- data/regulatory-deadlines.json. EU e-Evidence Regulation (EU) 2023/1543, applying 18 August 2026, and the Distance Marketing of Financial Services Directive (EU) 2023/2673 withdrawal button, applying 19 June 2026. Both verified against EUR-Lex.--### Fixed-- source.android.com/security/bulletin.xml returned 404. A live feed monitor-android.py and monitor-security.py fetched on every run, silently receiving nothing. Android Security Bulletins publish no RSS feed, so the dead call was removed and the canonical page cited instead.- masvs.owasp.org was a dead domain. Corrected to mas.owasp.org/MASVS.- Three developer.android.com paths returned 404 (privacy sandbox, Play Integrity deprecation guide, foldable devices). Corrected against live documentation.@@ -117,33 +201,10 @@ All notable changes to this playbook are recorded here. The format follows Keep- monitor.py mock announcements used realistic developer.apple.com/news links. Moved to the RFC 2606 .invalid TLD so a simulation fixture can never be mistaken for a real citation, which is how fabricated citations enter the corpus.- release-audit.py flagged its own generated readiness report as an affected file.- monitor-regulatory.py trust hierarchy strings drifted from AGENTS.md. Realigned.--### Added--- docs/GLOBAL-REGULATORY-2026.md section 2.7 and data/rejection-patterns.json BOTH-SUBSCRIPTION-HARD-CANCEL. US subscription cancellation (negative option) coverage was completely absent. Live-verified the federal FTC click-to-cancel rule's vacatur by the Eighth Circuit (8 July 2025) and its reopened rulemaking (ANPRM, 11 March 2026), documented that California, New York, and Massachusetts have their own binding negative-option statutes regardless, and that the FTC retains Section 5 and ROSCA authority. Added a matching guard check and detection recipe for a subscription flow that requires a phone call, mail, or an in-person visit to cancel.-- AGENTS.md. Release review guidelines for AI agents (a 14-item checklist) plus a strict source trust hierarchy and verification rules every monitor script follows before citing a claim as fact.-- scripts/monitor-regulatory.py. The Regulatory Intelligence Agent, tracking EU/UK/US/CA/AU/SG regulatory developments through a source trust hierarchy classifier, with its own test suite.-- scripts/monitor-android.py and docs/ANDROID-POLICY-MIGRATION.md. Android and Google Play requirements compliance monitoring, with its own test suite.-- scripts/monitor-ai-policy.py and docs/AI-POLICY-MIGRATION.md. Platform-specific generative AI policy monitoring (Apple and Google), with its own test suite.-- scripts/deadline-checker.py and data/regulatory-deadlines.json. A timezone-aware regulatory deadline checker over a 90-day window, wired into the guard hook automatically.-- scripts/release-audit.py. A release readiness compliance audit engine that writes RELEASE-READINESS-REPORT.md into the audited project (gitignored, never a committed fixture).-- scripts/accessibility-audit.py. A continuous accessibility compliance audit (VoiceOver, Dynamic Type, Reduce Motion, contrast, TalkBack, touch targets), runnable standalone and deliberately not wired into the guard hook.-- Mobile and web privacy compliance monitoring, folded into the guard hook and the pattern taxonomy.-- docs/MOBILE-SECURITY-2026.md. A mobile security requirements playbook and matching guard checks (secure storage, insecure backup, unsafe deep links).-- Brazil SPA fixed-odds betting license and Google Play Age Signals compliance checks in the guard hook and pattern taxonomy.-- Apple accessibility guard checks (VoiceOver, Dynamic Type, Reduce Motion, color contrast, haptics, keyboard focus) and privacy nutrition label checks.-- docs/EU-REGULATORY-2026.md. The EU legal hard rules with dated sources and Apple developer citations. the EU AI Act (Article 50 transparency by 2 August 2026, Article 4 AI literacy, Article 5 prohibited practices, Article 99 penalties, provider versus deployer), the Digital Markets Act (distribution channels, notarization, external purchase entitlement and disclosure sheet, the Core Technology Fee and Core Technology Commission, the 500 million euro anti-steering fine), DSA trader status (Apple removal from 17 February 2025), the European Accessibility Act (in force 28 June 2025, EN 301 549 and WCAG 2.1 AA), and the Apple 2025 and 2026 platform changes (age rating deadline 31 January 2026, Guideline 5.1.2(i) third-party-AI consent, the Declared Age Range API, mini apps 4.7, Xcode 26 SDK deadline 28 April 2026).-- docs/GLOBAL-REGULATORY-2026.md. The USA and other-global legal hard rules with dated sources. US COPPA and the amended rule, the state app-store age-verification laws, the external-link rules after the Epic injunction, US state privacy laws, plus the UK Online Safety Act and Children's Code, Australia, Brazil, Canada, South Korea, India, and other jurisdictions, and what Apple tells developers to do per region.-- An EU legal gate section in docs/PRE-SUBMISSION-CHECKLIST.md.-- Pointers from the Advanced 2026 legal layer and the README docs index to the new EU and global legal docs.-- docs/PLATFORM-MECHANICS-2026.md. The platform-mechanics and newer-policy hard rules with dated sources and Apple, Google, and statutory citations. Apple (macOS notarization with notarytool and stapler, Guideline 4.2 minimum functionality and 4.3 spam or duplicate with the June 2026 saturation tightening, the reader-app External Link Account Entitlement, the France ANSSI encryption declaration matrix, the content-rights declaration, visionOS App Motion and Developer Capture, the watchOS and tvOS 26 SDK deadline, In-App Events and Custom Product Pages and the submission-concurrency limit), Android (developer verification with the 30 September 2026 country deadlines, Foreground Service types, the Play Integrity move off SafetyNet, Play Billing Library v8 by 31 August 2026, target API 35 now and 36 by August 2026, disruptive-ads and interstitial rules, Health Connect, real-money games, and the Photo Picker and deletion-URL rules), and cross-cutting (CSAM and NCMEC reporting, UGC controls and the Google Play Child Safety Standards, accessibility as a review dimension, account-and-data deletion URLs, OFAC sanctions, ADA Title III, and PSD2 SCA and PCI DSS).-- A platform mechanics gate section in docs/PRE-SUBMISSION-CHECKLIST.md, and pointers to the new doc from the Advanced 2026 layer, the README docs index, the agent skill, and the audit command.--### Fixed-- 53 duplicate PRs from a scheduled bot regenerating the same ~11 features were deep-reviewed, deduplicated to one verified merge per feature, and closed with a recorded verdict naming the superseding merge. Two PRs were disqualified outright for citing fabricated Apple/Google announcement URLs (live-verified against the real sources); one was disqualified for a reproducible hang bug from wiring an unbounded directory scan into the guard hook with no timeout.- deadline-checker.py's regulatory-deadlines path resolution silently skipped the whole deadline section when the guard hook is installed under the flat `~/.claude/hooks/` layout instead of the nested repo layout. Now resolves under both.- The Brazil Digital ECA effective date was corrected from an unverified 2025-03-17 to the live-confirmed 2025-09-17.+- Seven scanner edge cases from the October review, each pinned by a test that failed first. The accessibility audit now reads a label closure wrapped in parentheses, such as `label: ({ Image(systemName: "trash") })`, so the icon-only Button is reported, and its Image rule scans comment-free code, so `// Example: Image("logo")` is no longer a finding, while a view that blanks only comment lines (the code after a leading block comment that closes on its line still counts, even when a second block comment follows it, and a line led by `*` counts as a comment only inside a block comment, so a multiplication continuation line is still read, and a line inside a Swift multiline string, an escaped triple quote or a raw `#"""` string included, is never read as a comment, and a triple quote inside a `//` comment, inline or on its own line, never opens one, and a block comment runs on only through lines that look like comment lines, so any other line is read as code, and a line holding a `\(` interpolation, or a raw string's `\#(`, is never blanked) is read beside it, so a Swift regex holding a quote (`/"/`) never hides the Image after it while a real Image beside a comment that names `accessibilityLabel` now is. The AI policy monitor prefers an Atom link with `rel="alternate"` or no rel over `rel="self"`, resolves an inherited `xml:base` against the feed's own URL into the absolute URL, reads the RSS Content module body in `content:encoded` for keyword matching, and picks the date as published, then updated, then the RSS 1.0 `dc:date`, whatever the element order. The Apple developer monitor joins inline markup the same way the AI policy monitor does, so `L<em>LM</em>` reads LLM.## 1.0.0 (2026-06-06)diff --git a/CITATION.cff b/CITATION.cffindex f1d5b90..1d9f4f6 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -5,6 +5,8 @@ type: softwareauthors:- alias: mjmirzaname: Mirza Iqbal+version: 2.0.0+date-released: '2026-10-16'repository-code: https://github.com/mjmirza/app-store-complianceurl: https://github.com/mjmirza/app-store-complianceabstract: >-diff --git a/README.md b/README.mdindex 330c456..cac726e 100644--- a/README.md+++ b/README.md@@ -32,22 +32,22 @@ Pick one row. The time shown is for that first step.| About to submit, and you can open a terminal | Run the two commands below | 2 minutes || Already rejected | Open [the appeal playbook](docs/MISTAKE-PATTERNS.md#the-appeal-playbook) | 10 minutes || Not a developer | Open [the checklist](docs/PRE-SUBMISSION-CHECKLIST.md) and do its first two checks | 5 minutes |-| Using Claude Code and want this on every submit | Go to [the install](#paste-this-into-claude-code-codex-or-any-ai-coding-tool) | 1 minute |+| Using an AI coding tool (Claude Code, Codex, Gemini CLI, GitHub Copilot, Cursor, Grok, Qwen, Kimi and more), and want this on every submit | Go to [the install](#install-it-into-your-ai-coding-tool) | 1 minute |The two commands. Needs git and bash. The first downloads this playbook. The second scans your app. Nothing is installed and nothing in your app is changed.```git clone https://github.com/mjmirza/app-store-compliance ~/repositories/app-store-compliance-bash ~/repositories/app-store-compliance/agent-os/hooks/app-store-compliance-guard.sh /path/to/your/app+bash ~/repositories/app-store-compliance/agent-os/hooks/app-store-compliance-guard.sh "/path/to/your/app"```-Replace only `/path/to/your/app`, with the folder that holds your Xcode project or your Android app. A small project scans in about a second, a large one can take up to a minute, and the guard prints the time it took. Findings print first, critical ones on top, each with the file and line that triggered it when there is one. The last lines tell you where you stand.+Replace only `/path/to/your/app`, with the folder that holds your Xcode project or your Android app. Keep the quotes, they keep a folder name with a space in it whole. To get the path without typing it, drag the folder from Finder or your file manager into the terminal window. A small project scans in about a second, a large one can take up to a minute, and the guard prints the time it took. Findings print first, critical ones on top, each with the file and line that triggered it when there is one. The last lines tell you where you stand.| Last line starts with | It means | Do next ||---|---|---|| `BLOCKED.` | A critical rejection risk was found | Fix each `[CRITICAL]` line using the `fix.` line under it, then run the same command again || `CLEAR.` | No critical risk in your code | Do the account and listing checks in [the checklist](docs/PRE-SUBMISSION-CHECKLIST.md) |-| `NOT CHECKED.` | No iOS or Android project was found in that folder. Run by hand this exits 1. As a hook it lets the command through | Point it at the right folder. Expo apps run `npx expo prebuild` first |+| `NOT CHECKED.` | No iOS or Android project was found in that folder, or the guard could not write its scan files. Run by hand this exits 1. As a hook it lets the command through | Point it at the right folder, and check the temp folder is writable. A managed Expo app with no native folders still gets its `app.json` or `app.config` read for purpose strings, the privacy manifest and Android permissions. Run `npx expo prebuild` to cover the native code too |## What you get@@ -61,47 +61,83 @@ A rejection costs a week. You submit, you wait days in review, you get a one linIf it saves you one rejection, it has paid for the ten minutes it takes to read.-## Paste this into Claude Code, Codex, or any AI coding tool+## Install it into your AI coding tool++This puts the check in front of every submit. Your agent runs the guard before any submit command, such as an upload to App Store Connect or Google Play, and stops the command when a critical rejection risk stands. For a one-time scan, skip this section and use Start here.++One command per tool, about a minute. Needs git and bash. Every tool other than Claude Code also needs python3.-This is for an always-on check in Claude Code. For a one-time scan, skip this section and use Start here. Copy the block below, paste it into your AI coding tool, and it installs the whole playbook and wires the guard into your flow.+```+git clone https://github.com/mjmirza/app-store-compliance ~/repositories/app-store-compliance+bash ~/repositories/app-store-compliance/scripts/install.sh --tool all+```-Read it before you paste it. This is everything it does.+`--tool all` installs into every supported tool it finds in your home folder. To pick one, pass its name instead.-- Clones this repo to `~/repositories/app-store-compliance`.-- Copies the guard, the skill, and one command into `~/.claude`.-- Adds one entry to `~/.claude/settings.json` and keeps every other key. When the file already existed, a dated backup is written next to it.-- Asks your agent to add one standing instruction to its own config.-- Step 6 makes network requests to check the playbook's sources.+| Tool | Command | What it gets | One thing to do after |+|---|---|---|---|+| Claude Code | `install.sh` | Hook, skill, `/app-store-audit` | Restart Claude Code |+| Codex CLI | `install.sh --tool codex` | Hook, skill | Run `/hooks` in Codex once and approve the new hook. Codex runs no new hook until you do |+| Gemini CLI | `install.sh --tool gemini` | Hook, skill, `/app-store-audit` | Restart Gemini CLI. The hook works from 0.22, the skill needs 0.24 or later |+| OpenCode | `install.sh --tool opencode` | Plugin, skill, `/app-store-audit` | Restart OpenCode |+| Cursor | `install.sh --tool cursor` | Hook, skill | Restart Cursor |+| GitHub Copilot CLI and Copilot in VS Code | `install.sh --tool copilot` | Hook, skill | Start a new Copilot CLI session and reload VS Code |+| GitHub Copilot cloud agent and Copilot in JetBrains | `install.sh --tool copilot-repo --repo "/path/to/your/app"` | Hook in your app's `.github/hooks` | Commit `.github/hooks` to your default branch. The cloud agent reads hooks only from there |+| Grok | `install.sh --tool grok` | Hook, skill | Start a new Grok session |+| Qwen Code | `install.sh --tool qwen` | Hook, skill, in `$QWEN_HOME` when it is set | Restart Qwen Code |+| Kimi Code | `install.sh --tool kimi` | Hook, skill | Restart Kimi Code |+| Factory Droid | `install.sh --tool droid` | Hook, skill | Start a new Droid session |+| Augment Auggie | `install.sh --tool auggie` | Hook, skill | Start a new Auggie session |+| Windsurf | `install.sh --tool windsurf` | Hook, skill | Restart Windsurf |-It never touches your GitHub account or your credentials. Undo it with `bash ~/repositories/app-store-compliance/scripts/install.sh uninstall`. If `settings.json` cannot be edited, the uninstall says so and you remove the one hook entry by hand. It ends by asking you to consider a star and showing you the link. Tapping it is always your call, never your agent's.+Every run ends with `Install verified.` only after it has fed a submit command to the hook in that tool's own payload format and seen it blocked. For OpenCode that check runs the plugin under node, so without node the run says `Installed, but not fully verified.` instead. If you see a `FAIL` line instead, fix that line and run the same command with `doctor` added.++What it writes, so you can check it.++- The guard, into that tool's own folder, for example `~/.codex/hooks/` or `~/.gemini/hooks/`.+- The skill. Claude Code reads it from `~/.claude/skills/`. Every other tool reads one shared copy in `~/.agents/skills/`.+- One hook entry in that tool's config (`~/.claude/settings.json`, `~/.codex/hooks.json`, `~/.gemini/settings.json`, `~/.cursor/hooks.json`, `~/.copilot/hooks/` or `$COPILOT_HOME/hooks/`), or for OpenCode one plugin file in `~/.config/opencode/plugins/`. Every other setting is kept, and a dated backup sits next to a file that already existed. A config that is not valid JSON or repeats a key is never rewritten. You get the exact block to paste instead.+- For Gemini CLI it also turns on `tools.enableHooks`, which Gemini needs before version 0.26 to run any hook.+- For Kimi Code it appends one marked `[[hooks]]` block to `~/.kimi-code/config.toml` (or `$KIMI_CODE_HOME/config.toml`) and never rewrites or prints the rest of that file, which can hold API keys. Uninstall removes exactly that block.+- For Factory Droid it writes to `~/.factory/settings.json` when your hooks already live there, because Droid ignores them once `~/.factory/hooks.json` exists.++#### Tools the installer does not wire, and what to do instead++Each of these was checked against its own documentation. Where a tool can block a command but its format could not be confirmed, you get the manual step rather than a guess.++| Tool | What to do |+|---|---|+| Kiro CLI | Kiro sends the event as JSON on stdin and blocks the tool when a `PreToolUse` command hook exits non-zero, and the guard reads Kiro's `shell`, `execute_bash`, `execute_pwsh` and `execute_cmd` payloads. The installer does not wire it yet. After `install.sh`, add `.kiro/hooks/app-store-compliance.json` to the project with `{"version":"v1","hooks":[{"name":"app-store-compliance","trigger":"PreToolUse","matcher":"^(shell\|execute_bash\|execute_pwsh\|execute_cmd)$","action":{"type":"command","command":"bash ~/.claude/hooks/app-store-compliance-guard.sh"}}]}`. Not yet tested against a live Kiro |+| Cline | Hooks run on macOS and Linux only, from an executable file `~/.cline/hooks/PreToolUse` that answers `{"cancel":true}`. Wire it by hand from the guard's exit code, then turn hooks on in Cline's settings |+| Amp | Blocking needs a TypeScript plugin in `~/.config/amp/plugins/`. Not installed automatically yet. Run the guard by hand before a submit |+| Goose, Crush | Both can block, and their file layout could not be confirmed. Run the guard by hand before a submit |+| Roo Code, Continue | No hook, only a deny list. Add the submit commands (`fastlane`, `xcrun altool`, `eas submit`, `gradle bundleRelease`) to Roo's `deniedCommands` or to the exclude list in Continue's `permissions.yaml` |+| Aider, Copilot for Xcode | No way to run a check before a command. Run the guard by hand, or as a git pre-push hook, before every submit |++It never touches your GitHub account or your credentials. Undo it with the same command and `uninstall`, for example `install.sh --tool gemini uninstall`. The shared skill stays until the last tool using it is removed.++### Or let your agent do it++Paste this into your AI coding tool. Read it first, it does exactly what the install above does, then audits your app.```-Set up the App Store Compliance Playbook from https://github.com/mjmirza/app-store-compliance so that from now on any iOS or Android app I build is automatically checked against Apple App Store and Google Play rejection rules before I submit it.+Set up the App Store Compliance Playbook from https://github.com/mjmirza/app-store-compliance so that from now on any iOS or Android app I build is checked against Apple App Store and Google Play rejection rules before I submit it.Steps:-1. Clone https://github.com/mjmirza/app-store-compliance into ~/repositories/app-store-compliance. If you cannot clone, read the files over the GitHub raw URLs instead.-2. If I use Claude Code, run the installer and show me its output. It copies the guard, the skill and the /app-store-audit command, adds one PreToolUse hook entry to settings.json (every other key is kept, a backup is written), then proves the guard blocks a sample app.- bash ~/repositories/app-store-compliance/scripts/install.sh- It must end with "Install verified." If it prints a FAIL line, fix that line and run- bash ~/repositories/app-store-compliance/scripts/install.sh doctor-3. If I use another tool (Codex, Cursor, or anything else), install by hand.- a. Copy agent-os/skill/SKILL.md, .citation-allowlist, and the docs/, data/, references/, templates/, and scripts/ folders into your agent's skills directory as app-store-compliance/.- b. Copy agent-os/hooks/app-store-compliance-guard.sh into your hooks directory and make it executable.- c. Register it to run before shell commands, with a timeout of at least 120 seconds (seconds, not milliseconds).- d. The guard reads the command from JSON on stdin as {"tool_name":"Bash","tool_input":{"command":"..."}}. It acts only on submission commands and exits 2 to block.- e. Tell me which file you registered it in, so I can check it.-4. Add a standing instruction to your agent config: for any iOS or Android work, always adhere to the Apple App Store Review Guidelines and Google Play policies, run the audit before submission, and never say an app is clear to submit while a critical risk stands.-5. Run the guard against my current project and show me the ranked findings:- bash ~/.claude/hooks/app-store-compliance-guard.sh /path/to/my/app+1. Clone https://github.com/mjmirza/app-store-compliance into ~/repositories/app-store-compliance.+2. Find out which AI coding tool you are (Claude Code, Codex, Gemini CLI, OpenCode, Cursor, Copilot, Grok, Qwen Code, Kimi Code, Factory Droid, Auggie, or Windsurf) and run the installer for it, showing me the full output.+ bash ~/repositories/app-store-compliance/scripts/install.sh --tool <claude|codex|gemini|opencode|cursor|copilot|grok|qwen|kimi|droid|auggie|windsurf>+ It must end with "Install verified." (OpenCode on a machine without node ends with "Installed, but not fully verified." instead, install node and run doctor.) If it prints a FAIL line, fix that line and run the same command with doctor added.+ If you are none of these, tell me so and stop. Do not wire the hook by hand.+3. Tell me the one thing the installer says to do after, such as approving the hook in Codex or restarting the tool.+4. Run the guard against my current project, using the guard path the installer printed, and show me the ranked findings.Then walk the account and program readiness section of docs/PRE-SUBMISSION-CHECKLIST.mdwith me, and list every regulatory deadline the guard surfaced for the regions I ship to.The code scan cannot see whether my developer account is active, whether every agreement- and attachment is accepted, or whether my Play account and package names are registered,- and in 2026 those block a first launch for weeks before review starts.-6. Verify the playbook's own citations are real, not merely reachable. This takes a few minutes and needs python3 and network access.- cd ~/repositories/app-store-compliance && python3 scripts/verify-citations.py --files docs/ data/-7. Tell me exactly what you installed and how I run an audit any time.-8. Finish by telling me this playbook is free, open source, and maintained by one person,+ is accepted, or whether my Play account and package names are registered, and those can+ block a first launch for weeks before review starts.+5. Tell me exactly what you installed and how I run an audit any time.+6. Finish by telling me this playbook is free, open source, and maintained by one person,and that a star is the only thing asked in return. Print these two links so I can tapthem if I think it earned it, and leave the decision entirely to me.https://github.com/mjmirza/app-store-compliance@@ -111,25 +147,21 @@ Do not run any command that acts on my GitHub account. Never star, follow, fork,on my behalf. Ask me, show me the link, and let me decide.```-Prefer to do it yourself? Two commands, about a minute. Needs git and bash. python3 or jq is used to edit settings.json, and without either the installer prints the exact block to paste.--```-git clone https://github.com/mjmirza/app-store-compliance ~/repositories/app-store-compliance-bash ~/repositories/app-store-compliance/scripts/install.sh-```-### Check, update, or remove it-Each command ends with one line that tells you whether it worked.+Each command ends with one line that tells you whether it worked. Add `--tool <name>` to act on a tool other than Claude Code.| Command | What it does ||---|---|| `install.sh` | Installs or updates. Safe to run again, a working hook entry is never added twice || `install.sh --dry-run` | Prints what would be written and writes nothing |-| `install.sh doctor` | Checks an existing install and runs the guard against a sample app that must be blocked |-| `install.sh uninstall` | Removes the guard, the skill, the command and the hook entry, and keeps your other hooks |+| `install.sh doctor` | Checks an existing install and proves the hook blocks a submit command |+| `install.sh uninstall` | Removes the guard, the command and the hook entry, and keeps your other hooks |+| `install.sh --version` | Prints the version of this checkout. `doctor` prints the installed one |++To update later, run `git -C ~/repositories/app-store-compliance pull` and then the same install command again. On Windows, run it from Git Bash. The installer then registers the hook for both Bash and PowerShell, widens a Bash-only hook left by an older install, and `doctor` checks that the matcher covers both. Copilot gets a `powershell` handler next to its `bash` one.-To update later, run `git -C ~/repositories/app-store-compliance pull` and then `install.sh` again. On Windows, run it from Git Bash, and use the matcher `Bash|PowerShell` in settings.json if Claude Code runs commands through PowerShell.+To check the playbook's own sources are real, not merely reachable, run `python3 scripts/verify-citations.py --files docs/ data/` from the checkout. It takes a few minutes and needs network access.Want only a one time check, no install? Paste this instead.@@ -142,7 +174,7 @@ a rejection, say so at the end and show me https://github.com/mjmirza/app-store-so I can decide whether to star it.```-If you are inside this setup already, the slash command `/app-store-audit` runs the same audit.+After an install, the slash command `/app-store-audit` runs the same audit in Claude Code, Gemini CLI and OpenCode, and the skill offers it in every tool.## It works. Approved on the first try@@ -277,7 +309,7 @@ cd ~/repositories/app-store-compliancepython3 scripts/monitor-regulatory.py --project /path/to/your/app # EU/UK/US/CA/AU/SG, source-trust classifiedpython3 scripts/monitor-android.py --dir /path/to/your/app # Android and Google Play requirementspython3 scripts/monitor-ai-policy.py --dir /path/to/your/app # generative AI policy (Apple and Google)-python3 scripts/release-audit.py /path/to/your/app # release readiness compliance audit+python3 scripts/release-audit.py /path/to/your/app --metadata ./metadata # release readiness compliance auditpython3 scripts/accessibility-audit.py /path/to/your/app # accessibility compliance auditpython3 scripts/monitor-privacy.py --dir /path/to/your/app # mobile and web privacy requirementspython3 scripts/monitor-security.py --dir /path/to/your/app # 17 mobile security requirements@@ -292,7 +324,7 @@ What to expect, measured on 30 September 2026.| `monitor-regulatory.py` | About 95 lines | No || `monitor-android.py`, `monitor-ai-policy.py` | About 205 and 95 lines | Only with `--output-docs <path>` or `--pr-output <path>` || `monitor-privacy.py`, `monitor-security.py` | About 27 lines each | Only with `--output-docs <path>` or `--pr-output <path>` |-| `release-audit.py` | About two minutes. It checks the playbook itself first, then your app | `RELEASE-READINESS-REPORT.md` in your app folder |+| `release-audit.py` | About two minutes. It checks the playbook itself first, then your app. Pass `--metadata <dir>` with your pulled listing. Exit 0 is clear, 2 is blocked on a critical or high finding, 3 is incomplete because a scan failed or the listing was not audited | `RELEASE-READINESS-REPORT.md` in your app folder || `generate-timeline.py` | The open deadlines, then one completion line | Rewrites `docs/REGULATORY-TIMELINE.md` in the playbook folder || `deadline-checker.py` | About 175 lines of detail. Add `--brief` for one line per open deadline | No |@@ -328,8 +360,11 @@ python3 scripts/deadline-checker.py| The install ends with a `FAIL` line | The line names the problem. Fix it, then run `install.sh doctor` || `settings.json` was not changed | It was read-only, not valid JSON, or neither python3 nor jq is installed. The installer printed the block to paste by hand || The guard does not fire in Claude Code | Restart Claude Code once, then run `install.sh doctor` |+| The guard does not fire in Codex | Run `/hooks` in Codex and approve the app-store-compliance hook. Codex runs no new or changed hook until you approve it. Then run `install.sh --tool codex doctor` |+| The guard does not fire in Gemini CLI | Restart Gemini CLI. Check that `tools.enableHooks` is true in `~/.gemini/settings.json`. Then run `install.sh --tool gemini doctor` |+| The install for any tool other than Claude Code says python3 is needed | Install python3, then run the same command again || `verify-citations.py` seems stuck | It checks about 300 links over the network and prints at the end. Give it a few minutes |-| A demo or example app inside your app is scanned with it | A nested Xcode or Android project under a React Native, Expo, Flutter, or Capacitor root stays part of the root's scan, because nothing tells a demo from a shipping app. To scan the nested app alone, point the guard at its folder |+| A demo or example app inside your app is scanned with it | A nested Xcode or Android project in a folder named exactly demo, example, sample, or playground (or the plural) stays part of the root's scan. Any other nested app (an `.xcodeproj` or an Android application module) with its own Info.plist or AndroidManifest.xml, that no root build file names, is scanned as its own app when the root has its own project for that platform. A native host that embeds the framework stays with the root, and a split app keeps every framework check the pooled tree showed. To scan a nested app alone, point the guard at its folder || `accessibility-audit.py` says Clean | It is a static scan. It computes no contrast ratio for icons and other non-text elements and does not check focus order in custom controls. It reads a Button label without running the code, so anything written inside the label counts, shown or not. A Text, a Label, or the word accessibilityLabel anywhere in it hides a possible icon-only Button, and an Image(systemName:) that is never shown can still raise one. Regex literals are skipped only in the #/.../# form, not bare /.../. Test those with VoiceOver, TalkBack, and Accessibility Inspector |## Words used here@@ -369,7 +404,7 @@ python3 scripts/deadline-checker.py| `docs/REGULATORY-TIMELINE.md` | Chronological global regulatory timeline, generated by `scripts/generate-timeline.py` from the deadline database || `docs/GAP-ANALYSIS-2026-09.md` | September 2026 gap analysis. what changed on Apple, Google Play, and in law since the previous sweep, what developers report in public, and what the playbook added or corrected || `docs/MOBILE-SECURITY-2026.md` | Mobile security requirements playbook (secure storage, backup exposure, deep link hijacking, and the checks each maps to) |-| `AGENTS.md` | Release review guidelines for AI agents, plus the source trust hierarchy and verification rules every monitor script follows before citing a claim as fact |+| `AGENTS.md` | Release review guidelines for AI agents, plus the source trust hierarchy and verification rules every monitor script follows before citing a claim as fact. A monitor's corroboration is keyword based, so read the cited official source before acting || `data/rejection-patterns.json` | Machine readable taxonomy of rejection patterns with detection signals and fixes. Drives the guard || `data/detection-recipes.json` | The detection command for each rejection pattern a code scan can see (107 of 114), generated into `references/`. The other seven are store listing and account checks done by hand || `data/regulatory-deadlines.json` | Global regulatory deadline database (jurisdiction, law, effective/grace/mandatory/enforcement dates), read by `scripts/deadline-checker.py` |@@ -380,16 +415,18 @@ python3 scripts/deadline-checker.py| `scripts/monitor-security.py` | Monitors 17 mobile security requirements, matching real API symbols in your code || `scripts/generate-timeline.py` | Compiles a chronological regulatory timeline from the deadline database || `scripts/monitor.py` | Monitors 25 Apple developer requirements tracks, maps announcements to tracks, identifies affected files, generates migration tasks, estimates release impact, and drafts pull requests |-| `scripts/*-test.sh`, `scripts/test-*.py` | One test suite per script (guard, monitors, audits, deadline checker, timeline, citation verifier, metadata audit). CI runs every one of them on every push |+| `scripts/*-test.sh`, `scripts/test-*.py` | One test suite per script (guard, monitors, audits, deadline checker, timeline, citation verifier, metadata audit). CI runs every one of them on every push to main and on every pull request || `scripts/monitor-regulatory.py` | The Regulatory Intelligence Agent. tracks EU/UK/US/CA/AU/SG regulatory developments through a source trust hierarchy classifier || `scripts/monitor-android.py` | Android and Google Play requirements compliance monitor || `scripts/monitor-ai-policy.py` | Platform-specific generative AI policy monitor (Apple and Google) || `scripts/deadline-checker.py` | Prints every regulatory deadline inside a rolling 90-day window, timezone-aware. Runs automatically as part of the guard |-| `scripts/release-audit.py` | Release readiness compliance audit engine, writes `RELEASE-READINESS-REPORT.md` into the audited project |+| `scripts/release-audit.py` | Release readiness compliance audit engine, writes `RELEASE-READINESS-REPORT.md` into the audited project. Runs the guard and the listing audit, and `--metadata <dir>` points the listing audit at a pulled metadata folder. Exit 0 is clear. Exit 2 is blocked on a critical or high finding. Exit 3 is incomplete, a scan failed or did not check the app || `scripts/accessibility-audit.py` | Continuous accessibility compliance audit (VoiceOver, Dynamic Type, Reduce Motion, contrast, TalkBack, touch targets). Runnable standalone, deliberately not wired into the guard hook || `scripts/validate.py` | Validates that `data/rejection-patterns.json`, `data/detection-recipes.json`, and `data/regulatory-deadlines.json` stay internally consistent. Runs in CI || `scripts/generate-references.py` | Regenerates `references/` from the pattern and recipe data, so the reference tree never drifts from the taxonomy |-| `scripts/metadata-audit.py` | Audits the live store listing (name, subtitle, keywords, description, URLs) against the metadata rejection rules, with a propose and re validate loop. A large share of rejections live in the listing, not the code |+| `scripts/metadata-audit.py` | Audits the live store listing (name, subtitle, keywords, description, URLs) against the metadata rejection rules, with a propose and re validate loop. Every locale folder is audited on its own, filled from a fastlane `default/` folder and parent folders like fastlane does, and each finding names its locale. `--platform google` applies the Google Play limits and rules, and a fastlane `android` folder gets them automatically. It checks that every URL is a real http or https address, that an Apple listing has a support URL, and that a Google listing has a contact email. A large share of rejections live in the listing, not the code |+| `scripts/install.sh` | One command install for Claude Code, and with `--tool` for Codex, Gemini CLI, OpenCode, Cursor, Copilot, Grok, Qwen Code, Kimi Code, Factory Droid, Auggie and Windsurf. `doctor` proves the hook blocks a submit command, `uninstall` removes it, `--version` prints the version |+| `scripts/install_harness.py` | The part of the install for the tools other than Claude Code. Merges each tool's own config file and writes the OpenCode plugin || `scripts/pull-metadata.sh` | Pulls the live App Store Connect listing into a metadata directory via the asc CLI, with the Play API path documented || `references/` | A structured, AI loadable reference tree. Rules by category (metadata, privacy, payments, design, performance, entitlements, safety, Android) and guidelines by app type, each with a detection command, generated from the taxonomy. Load the slices that match the task || `templates/REVIEW-NOTES-TEMPLATE.md` | A fill in the blanks App Store review notes template, the six sections that clear most 2.1 rejections |diff --git a/VERSION b/VERSIONnew file mode 100644index 0000000..227cea2--- /dev/null+++ b/VERSION@@ -0,0 +1 @@+2.0.0diff --git a/agent-os/commands/app-store-audit.md b/agent-os/commands/app-store-audit.mdindex a9a97e9..e4258ea 100644--- a/agent-os/commands/app-store-audit.md+++ b/agent-os/commands/app-store-audit.md@@ -42,5 +42,4 @@ bash ~/.claude/hooks/app-store-compliance-guard.sh <project-path>- Skill. `~/.claude/skills/app-store-compliance/`- Guard. `~/.claude/hooks/app-store-compliance-guard.sh`-- Rule. `~/.claude/rules/app-store-compliance.md`- Public playbook. https://github.com/mjmirza/app-store-compliancediff --git a/agent-os/hooks/app-store-compliance-guard-test.sh b/agent-os/hooks/app-store-compliance-guard-test.shindex 6345eb1..1d258c4 100755--- a/agent-os/hooks/app-store-compliance-guard-test.sh+++ b/agent-os/hooks/app-store-compliance-guard-test.sh@@ -941,7 +941,7 @@ rm -rf "$D"# 94 a 5MB payload that is valid JSON with the command up front is scanned, well under the capD="$(mk_ios_bad)"BIG="$(mktemp)"; { printf '{"tool_name":"Bash","tool_input":{"command":"npx eas submit --platform ios","description":"'; head -c 5000000 /dev/zero | tr '\0' 'x'; printf '"}}'; } > "$BIG"-OUT="$(bash "$GUARD" < "$BIG" 2>&1)"; RC=$?; rm -f "$BIG"+OUT="$(CLAUDE_PROJECT_DIR="$D" bash "$GUARD" < "$BIG" 2>&1)"; RC=$?; rm -f "$BIG"echo "$OUT" | grep -q 'App Store Compliance Guard' && [ "$RC" -eq 2 ] && ok "610-32 5MB valid payload is scanned" || bad "610-32 5MB valid payload is scanned (rc=$RC bytes=${#OUT})"rm -rf "$D"@@ -1575,7 +1575,7 @@ OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?echo "$OUT" | grep -q "^Project\. $D$" && ! echo "$OUT" | grep -q '^App\. ' && ok "655-4 react-native as a dev dependency only never makes an app" || bad "655-4 react-native as a dev dependency only never makes an app (rc=$RC)"rm -rf "$D"-# 656 documented limit, pinned. a bare Xcode project with its own Info.plist under a root Expo app stays part of the root scan+# 656 a bare Xcode project in an examples folder under a root Expo app stays part of the root scanD="$(mktemp -d)"; mkdir -p "$D/ios/App" "$D/examples/NativeDemo/Demo.xcodeproj" "$D/examples/NativeDemo/Demo"printf '{"expo":{"name":"root"}}' > "$D/app.json"printf '<plist><dict></dict></plist>' > "$D/ios/App/Info.plist"@@ -1898,6 +1898,1235 @@ OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?[ "$RC" -eq 0 ] && echo "$OUT" | grep -q '^CLEAR' && ok "c4-2 a plain Dart package beside a native app does not stop CLEAR" || bad "c4-2 a plain Dart package beside a native app does not stop CLEAR (rc=$RC)"rm -rf "$D"+# Harness payloads (2.0.0). Codex, Gemini CLI, Cursor, Copilot CLI and OpenCode each send the shell command+# in their own shape. Each must reach the scan on the jq and python3 tiers, and a non-shell tool must stay silent.+D="$(mk_ios_bad)"+NOJQ="$(mktemp -d)"; for b in bash grep sed awk find xargs tr head mktemp cat rm printf wc sort uniq cut plutil python3 xmllint dirname basename date env; do p="$([ "$b" = python3 ] && pyenv which python3 2>/dev/null || command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$NOJQ/$b"; done+harness_payload() { python3 -c '+import json, sys+kind, cmd, cwd = sys.argv[1], sys.argv[2], sys.argv[3]+shapes = {+ "codex": {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": cmd}, "cwd": cwd},+ "gemini": {"hook_event_name": "BeforeTool", "tool_name": "run_shell_command", "tool_input": {"command": cmd}, "cwd": cwd},+ "cursor": {"hook_event_name": "beforeShellExecution", "command": cmd, "cwd": cwd},+ "copilot-str": {"toolName": "bash", "toolArgs": json.dumps({"command": cmd}), "cwd": cwd},+ "copilot-obj": {"toolName": "bash", "toolArgs": {"command": cmd}, "cwd": cwd},+ "grok": {"hookEventName": "PreToolUse", "toolName": "run_terminal_command", "toolInput": {"command": cmd}, "cwd": cwd},+ "grok-cmd": {"hookEventName": "PreToolUse", "toolName": "run_terminal_cmd", "toolInput": {"command": cmd}, "cwd": cwd},+ "grok-monitor": {"hookEventName": "PreToolUse", "toolName": "monitor", "toolInput": {"command": cmd}, "cwd": cwd},+ "grok-bash": {"hookEventName": "PreToolUse", "toolName": "bash", "toolInput": {"command": cmd}, "cwd": cwd},+ "grok-readfile": {"hookEventName": "PreToolUse", "toolName": "read_file", "toolInput": {"command": cmd, "path": "x"}, "cwd": cwd},+ "droid": {"hook_event_name": "PreToolUse", "tool_name": "Execute", "tool_input": {"command": cmd}, "cwd": cwd},+ "auggie": {"hook_event_name": "PreToolUse", "tool_name": "launch-process", "tool_input": {"command": cmd}, "workspace_roots": [cwd]},+ "windsurf": {"agent_action_name": "pre_run_command", "tool_info": {"command_line": cmd, "cwd": cwd}},+ "vscode": {"hook_event_name": "PreToolUse", "tool_name": "runInTerminal", "tool_input": {"command": cmd}, "cwd": cwd},+ "kiro": {"hook_event_name": "preToolUse", "tool_name": "execute_bash", "tool_input": {"command": cmd}, "cwd": cwd},+ "goose": {"hook_event_name": "PreToolUse", "tool_name": "shell", "tool_input": {"command": cmd}, "working_dir": cwd},+ "grok-read": {"hookEventName": "PreToolUse", "toolName": "Read", "toolInput": {"command": cmd, "path": "x"}, "cwd": cwd},+ "windsurf-read": {"agent_action_name": "pre_read_code", "tool_info": {"file_path": cmd, "cwd": cwd}},+ "opencode": {"tool_name": "bash", "tool_input": {"command": cmd}, "cwd": cwd},+ "write": {"tool_name": "Write", "tool_input": {"command": cmd, "file_path": "x"}, "cwd": cwd},+ "gemini-write": {"tool_name": "write_file", "tool_input": {"command": cmd}, "cwd": cwd},+ "copilot-edit": {"toolName": "edit", "toolArgs": json.dumps({"command": cmd}), "cwd": cwd},+}+print(json.dumps(shapes[kind]))' "$1" "$2" "$3"; }+SUB="fastlane deliver"+for tier in "$PATH" "$NOJQ"; do+ tn="${tier##*/}"; [ "$tier" = "$PATH" ] && tn=jq+ for kind in codex gemini cursor copilot-str copilot-obj opencode grok grok-cmd grok-monitor grok-bash droid auggie windsurf vscode kiro goose; do+ RC="$( cd /tmp && harness_payload "$kind" "$SUB" "$D" | env -u CLAUDE_PROJECT_DIR PATH="$tier" bash "$GUARD" >/dev/null 2>&1; echo $? )"+ [ "$RC" = "2" ] && ok "h-$kind blocks a submit command and scans the payload cwd (tier=$tn)" || bad "h-$kind blocks a submit command and scans the payload cwd (tier=$tn rc=$RC)"+ done+ for kind in write gemini-write copilot-edit grok-read grok-readfile windsurf-read; do+ OUT="$( cd /tmp && harness_payload "$kind" "$SUB" "$D" | env -u CLAUDE_PROJECT_DIR PATH="$tier" bash "$GUARD" 2>&1 )"; RC=$?+ [ "$RC" = "0" ] && [ -z "$OUT" ] && ok "h-$kind a non-shell tool stays silent (tier=$tn)" || bad "h-$kind a non-shell tool stays silent (tier=$tn rc=$RC)"+ done+ RC="$( cd /tmp && harness_payload codex "ls -la" "$D" | env -u CLAUDE_PROJECT_DIR PATH="$tier" bash "$GUARD" >/dev/null 2>&1; echo $? )"+ [ "$RC" = "0" ] && ok "h-ordinary an ordinary command stays silent (tier=$tn)" || bad "h-ordinary an ordinary command stays silent (tier=$tn rc=$RC)"+done+# CLAUDE_PROJECT_DIR still wins over the payload cwd, so Claude Code behaves exactly as before.+CLEAN="$(mk_ios_clean)"+RC="$( harness_payload codex "$SUB" "$D" | CLAUDE_PROJECT_DIR="$CLEAN" bash "$GUARD" >/dev/null 2>&1; echo $? )"+[ "$RC" = "0" ] && ok "h-precedence CLAUDE_PROJECT_DIR wins over the payload cwd" || bad "h-precedence CLAUDE_PROJECT_DIR wins over the payload cwd (rc=$RC)"+# A payload cwd that is not a directory falls back to the working directory.+RC="$( cd "$CLEAN" && harness_payload codex "$SUB" "/nonexistent/x" | env -u CLAUDE_PROJECT_DIR bash "$GUARD" >/dev/null 2>&1; echo $? )"+[ "$RC" = "0" ] && ok "h-badcwd a missing payload cwd falls back to the working directory" || bad "h-badcwd a missing payload cwd falls back to the working directory (rc=$RC)"+rm -rf "$CLEAN" "$NOJQ"+# fastlane global options before the action or lane must not hide a submission.+for c in "fastlane --verbose deliver" "fastlane --env production deliver" "bundle exec fastlane --verbose pilot" "fastlane --capture_output ios release" "fastlane -v upload_to_testflight"; do+ RC="$(hook_rc "$c" "$D")"+ [ "$RC" = "2" ] && ok "fl-opt blocks. $c" || bad "fl-opt blocks. $c (rc=$RC)"+done+for c in "fastlane --version" "fastlane --help" "fastlane --env production tests"; do+ RC="$(hook_rc "$c" "$D")"+ [ "$RC" = "0" ] && ok "fl-opt silent. $c" || bad "fl-opt silent. $c (rc=$RC)"+done+rm -rf "$D"++# ===== Rule precision round (October 2026 review). each case failed on the guard before its fix =====+rr_run() { OUT="$(bash "$GUARD" "$1" 2>&1)"; RC=$?; }+rr_has() { printf '%s\n' "$OUT" | grep -q -e "$1"; }+rr_hook() { # $1 command, $2 project dir. sets OUT (stdout and stderr) and RC+ OUT="$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"Bash","tool_input":{"command":sys.argv[1]}}))' "$1" | CLAUDE_PROJECT_DIR="$2" bash "$GUARD" 2>&1)"; RC=$?+}+mk_rr_ios() { # $1 Info.plist dict body, $2 Swift source+ local d; d="$(mktemp -d)"; mkdir -p "$d/App"+ printf '<plist><dict>%s<key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' "$1" > "$d/App/Info.plist"+ printf '%s' "$PLIST_EMPTY" > "$d/App/PrivacyInfo.xcprivacy"+ printf '%s\nlet policy = "https://realbackend.io/privacy-policy"\n' "$2" > "$d/App/X.swift"+ echo "$d"+}++# A02 a usage-description key or a deletion call that exists only in a comment satisfies nothing+D="$(mk_rr_ios '' 'import AVFoundation+// NSCameraUsageDescription is set later+let dev = AVCaptureDevice.default(for: .video)')"+rr_run "$D"+rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && [ "$RC" -eq 2 ] && ok "rr-A02-1 a camera key named only in a Swift comment still raises the finding" || bad "rr-A02-1 a camera key named only in a Swift comment still raises the finding (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'class A { func signIn() {} }+// deleteAccount comes in the next release+/* func deleteUser() {} */')"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && ok "rr-A02-2 a deletion call that exists only in comments raises the finding" || bad "rr-A02-2 a deletion call that exists only in comments raises the finding (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AVFoundation+class A { func signIn() {} }+let dev = AVCaptureDevice.default(for: .video)+let endpoint = "https://api.realbackend.io/v1/deleteAccount" // removes the user')"+mkdir -p "$D/App.xcodeproj"; printf 'INFOPLIST_KEY_NSCameraUsageDescription = "Scan receipts";\n' > "$D/App.xcodeproj/project.pbxproj"+rr_run "$D"+! rr_has 'MISSING-USAGE-DESCRIPTION' && ! rr_has 'NO-ACCOUNT-DELETION' && ok "rr-A02-3 a build-setting key and a deletion URL before a trailing comment stay clean" || bad "rr-A02-3 a build-setting key and a deletion URL before a trailing comment stay clean (rc=$RC)"+rm -rf "$D"+D="$(mk_ios_clean)"; rr_run "$D"+! rr_has 'MISSING-USAGE-DESCRIPTION' && ! rr_has 'NO-ACCOUNT-DELETION' && [ "$RC" -eq 0 ] && ok "rr-A02-4 the clean iOS fixture stays clean" || bad "rr-A02-4 the clean iOS fixture stays clean (rc=$RC)"+rm -rf "$D"++# A02b a purpose string that exists only in InfoPlist.strings satisfies nothing, Apple reads Info.plist (ITMS-90683)+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/App/en.lproj"; printf '"NSCameraUsageDescription" = "Scan receipts";\n' > "$D/App/en.lproj/InfoPlist.strings"+rr_run "$D"+rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && [ "$RC" -eq 2 ] && ok "rr-A02-5 a camera key only in InfoPlist.strings still raises the finding" || bad "rr-A02-5 a camera key only in InfoPlist.strings still raises the finding (rc=$RC)"+rm -rf "$D"++# A02c a permission API named in a comment counts, as in 1.0.0. the system photo picker needs no permission+D="$(mk_rr_ios '' 'class A {}+// TODO maybe use AVCaptureDevice and CLLocationManager later+/* CNContactStore() */')"+rr_run "$D"+rr_has 'MISSING-USAGE-DESCRIPTION' && ok "rr-A02-6 a permission API named only in comments still counts, as in 1.0.0" || bad "rr-A02-6 a permission API named only in comments still counts, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import PhotosUI+let picker = PHPickerViewController(configuration: PHPickerConfiguration())')"+rr_run "$D"+! rr_has 'Photos used without' && ok "rr-A02-7 PHPickerViewController alone needs no photo library purpose string" || bad "rr-A02-7 PHPickerViewController alone needs no photo library purpose string (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import Photos+PHPhotoLibrary.requestAuthorization { _ in }')"+rr_run "$D"+rr_has 'Photos used without' && ok "rr-A02-8 PHPhotoLibrary access still needs the photo library purpose string" || bad "rr-A02-8 PHPhotoLibrary access still needs the photo library purpose string (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video) // camera for receipts')"+rr_run "$D"+rr_has 'Camera used without' && [ "$RC" -eq 2 ] && ok "rr-A02-9 a real camera call with a trailing comment still blocks" || bad "rr-A02-9 a real camera call with a trailing comment still blocks (rc=$RC)"+rm -rf "$D"++# A13 ATT needs both halves, the purpose string and the authorization call, and names the missing one+D="$(mk_rr_ios '<key>NSUserTrackingUsageDescription</key><string>Measure ads</string>' 'import AppsFlyerLib+let af = AppsFlyerLib.shared()')"+rr_run "$D"+rr_has 'APPLE-5.1.2-MISSING-ATT' && rr_has 'requestTrackingAuthorization call' && ! rr_has 'NSUserTrackingUsageDescription in Info.plist' && ok "rr-A13-1 a purpose string without the request call is flagged and the call is named" || bad "rr-A13-1 a purpose string without the request call is flagged and the call is named"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AppsFlyerLib+import AppTrackingTransparency+// NSUserTrackingUsageDescription+ATTrackingManager.requestTrackingAuthorization { _ in }')"+rr_run "$D"+rr_has 'APPLE-5.1.2-MISSING-ATT' && rr_has 'NSUserTrackingUsageDescription in Info.plist' && ! rr_has 'requestTrackingAuthorization call' && ok "rr-A13-2 the request call without a purpose string is flagged and the key is named" || bad "rr-A13-2 the request call without a purpose string is flagged and the key is named"+rm -rf "$D"+D="$(mk_rr_ios '<key>NSUserTrackingUsageDescription</key><string>Measure ads</string>' 'import AppsFlyerLib+import AppTrackingTransparency+ATTrackingManager.requestTrackingAuthorization { _ in AppsFlyerLib.shared().start() }')"+rr_run "$D"+! rr_has 'APPLE-5.1.2-MISSING-ATT' && ok "rr-A13-3 both halves present stays clean" || bad "rr-A13-3 both halves present stays clean"+rm -rf "$D"++# A10 a vendored privacy manifest is the SDK's, never the app's own+D="$(mk_rr_ios '' 'let d = UserDefaults.standard')"+rm -f "$D/App/PrivacyInfo.xcprivacy"+mkdir -p "$D/Pods/SomeSDK" "$D/.build/checkouts/Lib/Sources" "$D/node_modules/x/ios" "$D/ios/.symlinks/plugins/p/ios"+for v in Pods/SomeSDK .build/checkouts/Lib/Sources node_modules/x/ios ios/.symlinks/plugins/p/ios; do printf '%s' "$PLIST_EMPTY" > "$D/$v/PrivacyInfo.xcprivacy"; done+rr_run "$D"+rr_has 'APPLE-PRIVACY-MANIFEST-MISSING' && ok "rr-A10-1 vendored manifests alone do not count as the app manifest" || bad "rr-A10-1 vendored manifests alone do not count as the app manifest (rc=$RC)"+printf '%s' "$PLIST_EMPTY" > "$D/App/PrivacyInfo.xcprivacy"+rr_run "$D"+! rr_has 'APPLE-PRIVACY-MANIFEST-MISSING' && ok "rr-A10-2 an app manifest beside vendored ones stays clean" || bad "rr-A10-2 an app manifest beside vendored ones stays clean"+rm -rf "$D"+D="$(mktemp -d)"; mkdir -p "$D/ios/Runner" "$D/ios/.symlinks/plugins/permission_handler/ios" "$D/lib"+printf 'name: t\ndependencies:\n permission_handler: ^11.0.0\n' > "$D/pubspec.yaml"+printf "import 'package:permission_handler/permission_handler.dart';\nvoid main(){}\n" > "$D/lib/main.dart"+printf '<plist><dict></dict></plist>' > "$D/ios/Runner/Info.plist"+printf '%s' "$PLIST_EMPTY" > "$D/ios/.symlinks/plugins/permission_handler/ios/PrivacyInfo.xcprivacy"+rr_run "$D"+rr_has 'FLUTTER-PRIVACY-MANIFEST-MISSING' && ok "rr-A10-3 a Flutter plugin manifest under .symlinks is not the app manifest" || bad "rr-A10-3 a Flutter plugin manifest under .symlinks is not the app manifest"+rm -rf "$D"++# A12 framework IAP plugins need a restore call too, and their own restore APIs count+mk_rr_flutter_iap() { # $1 Dart body+ local d; d="$(mktemp -d)"; mkdir -p "$d/ios/Runner" "$d/lib"+ printf 'name: t\ndependencies:\n purchases_flutter: ^8.0.0\n' > "$d/pubspec.yaml"+ printf "import 'package:purchases_flutter/purchases_flutter.dart';\n%s\n" "$1" > "$d/lib/main.dart"+ printf '<plist><dict><key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' > "$d/ios/Runner/Info.plist"+ printf '%s' "$PLIST_EMPTY" > "$d/ios/Runner/PrivacyInfo.xcprivacy"+ echo "$d"+}+D="$(mk_rr_flutter_iap 'void buy() { Purchases.purchasePackage(p); }')"; rr_run "$D"+rr_has 'APPLE-RESTORE-PURCHASES-MISSING' && ok "rr-A12-1 RevenueCat purchases without restore are flagged" || bad "rr-A12-1 RevenueCat purchases without restore are flagged"+rm -rf "$D"+D="$(mk_rr_flutter_iap 'void buy() { Purchases.purchasePackage(p); }+void restore() { Purchases.restorePurchases(); }')"; rr_run "$D"+! rr_has 'APPLE-RESTORE-PURCHASES-MISSING' && ok "rr-A12-2 Purchases.restorePurchases counts as restore" || bad "rr-A12-2 Purchases.restorePurchases counts as restore"+rm -rf "$D"+mk_rr_unity_iap() { # $1 C# body+ local d; d="$(mktemp -d)"; mkdir -p "$d/ProjectSettings" "$d/Assets"+ printf 'm_EditorVersion: 2022.3.1f1\n' > "$d/ProjectSettings/ProjectVersion.txt"+ printf 'using UnityEngine.Purchasing;\nclass Shop { %s }\n' "$1" > "$d/Assets/Shop.cs"+ echo "$d"+}+D="$(mk_rr_unity_iap 'void Buy() { controller.InitiatePurchase("gems"); }')"; rr_run "$D"+rr_has 'APPLE-RESTORE-PURCHASES-MISSING' && ok "rr-A12-3 Unity IAP without restore is flagged" || bad "rr-A12-3 Unity IAP without restore is flagged"+rm -rf "$D"+D="$(mk_rr_unity_iap 'void Restore() { apple.RestoreTransactions(r => {}); }')"; rr_run "$D"+! rr_has 'APPLE-RESTORE-PURCHASES-MISSING' && ok "rr-A12-4 Unity RestoreTransactions counts as restore" || bad "rr-A12-4 Unity RestoreTransactions counts as restore"+rm -rf "$D"++# A09 an Android-only build command never meets a native Apple finding, an iOS command still does+D="$(mktemp -d)"; mkdir -p "$D/ios/Runner" "$D/android/app/src/main" "$D/lib"+printf 'name: t\n' > "$D/pubspec.yaml"; printf 'void main(){}\n' > "$D/lib/main.dart"+printf '<plist><dict></dict></plist>' > "$D/ios/Runner/Info.plist"+printf 'import AVFoundation\nlet dev = AVCaptureDevice.default(for: .video)\n' > "$D/ios/Runner/Cam.swift"+printf '<manifest xmlns:android="http://schemas.android.com/apk/res/android"></manifest>' > "$D/android/app/src/main/AndroidManifest.xml"+rr_hook "flutter build appbundle --release" "$D"+! rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && ! rr_has 'APPLE-EXPORT-COMPLIANCE' && ok "rr-A09-1 an Android-only build skips the native Apple checks" || bad "rr-A09-1 an Android-only build skips the native Apple checks (rc=$RC)"+for c in "./gradlew bundleRelease" "flutter build ipa"; do+ rr_hook "$c" "$D"+ case "$c" in+ *ipa) rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && [ "$RC" -eq 2 ] && ok "rr-A09-2 an iOS build still raises the Apple finding" || bad "rr-A09-2 an iOS build still raises the Apple finding (rc=$RC)" ;;+ *) ! rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && ok "rr-A09-3 a Gradle release bundle skips the native Apple checks" || bad "rr-A09-3 a Gradle release bundle skips the native Apple checks (rc=$RC)" ;;+ esac+done+rr_run "$D"+rr_has 'APPLE-5.1.1-MISSING-USAGE-DESCRIPTION' && ok "rr-A09-4 a standalone scan still covers both stores" || bad "rr-A09-4 a standalone scan still covers both stores"+rm -rf "$D"++# A24 an unusable mktemp falls back to /tmp, as before 2.0.0, so the scan still runs+# macOS mktemp ignores an unusable TMPDIR, so a PATH shim stands in. one fails, one hands back a path that cannot be written.+D="$(mk_ios_clean)"; SHIMS="$(mktemp -d)"; mkdir -p "$SHIMS/fail" "$SHIMS/bad"+printf '#!/bin/sh\nexit 1\n' > "$SHIMS/fail/mktemp"+printf '#!/bin/sh\necho /nonexistent/ascg-tmp/buffer\n' > "$SHIMS/bad/mktemp"+chmod +x "$SHIMS/fail/mktemp" "$SHIMS/bad/mktemp"+for s in fail bad; do+ OUT="$(PATH="$SHIMS/$s:$PATH" bash "$GUARD" "$D" 2>&1)"; RC=$?+ [ "$RC" -eq 0 ] && ! rr_has 'NOT CHECKED' && rr_has '^CLEAR' && ok "rr-A24-1 an unusable mktemp falls back to /tmp and still scans (mktemp $s)" || bad "rr-A24-1 an unusable mktemp falls back to /tmp and still scans (mktemp $s rc=$RC)"+ ERR="$(python3 -c 'import json; print(json.dumps({"tool_name":"Bash","tool_input":{"command":"xcrun altool --upload-app -f a.ipa"}}))' | PATH="$SHIMS/$s:$PATH" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+ ! printf '%s' "$ERR" | grep -q 'NOT CHECKED' && printf '%s' "$ERR" | grep -q 'App Store Compliance Guard' && ok "rr-A24-2 as a hook an unusable mktemp still scans through /tmp (mktemp $s)" || bad "rr-A24-2 as a hook an unusable mktemp still scans through /tmp (mktemp $s rc=$RC)"+done+rm -rf "$D" "$SHIMS"++# A11 a managed Expo app has its app config checked, and a critical config finding blocks+mk_rr_expo() { # $1 package.json, $2 app.json+ local d; d="$(mktemp -d)"+ printf '%s' "$1" > "$d/package.json"; printf '%s' "$2" > "$d/app.json"+ echo "$d"+}+D="$(mk_rr_expo '{"dependencies":{"expo":"51.0.0"}}' '{"expo":{"name":"x","android":{"permissions":["ACCESS_BACKGROUND_LOCATION"]}}}')"+rr_hook "eas submit -p android" "$D"+[ "$RC" -eq 2 ] && rr_has 'GOOGLE-PERM-BACKGROUND-LOCATION' && ok "rr-A11-1 background location in the Expo config blocks an Android submit" || bad "rr-A11-1 background location in the Expo config blocks an Android submit (rc=$RC)"+rr_hook "eas submit -p ios" "$D"+[ "$RC" -eq 0 ] && ! rr_has 'GOOGLE-PERM-BACKGROUND-LOCATION' && rr_has 'NOT CHECKED' && ok "rr-A11-2 an iOS-only submit skips the Android config check" || bad "rr-A11-2 an iOS-only submit skips the Android config check (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_expo '{"dependencies":{"expo":"51.0.0","expo-camera":"15.0.0"}}' '{"expo":{"name":"x","android":{"permissions":["android.permission.READ_SMS"]}}}')"+rr_run "$D"+[ "$RC" -eq 2 ] && rr_has 'GOOGLE-PERM-SMS-CALLLOG' && rr_has 'Camera module in the Expo app' && ok "rr-A11-3 a standalone scan reads the Expo config, SMS blocks and the camera string is named" || bad "rr-A11-3 a standalone scan reads the Expo config, SMS blocks and the camera string is named (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_expo '{"dependencies":{"expo":"51.0.0","expo-camera":"15.0.0","@react-native-async-storage/async-storage":"1.0.0"}}' '{"expo":{"name":"x","plugins":[["expo-camera",{"cameraPermission":"Scan receipts to log expenses"}]],"ios":{"privacyManifests":{"NSPrivacyAccessedAPITypes":[]}},"android":{"blockedPermissions":["android.permission.ACCESS_BACKGROUND_LOCATION","android.permission.READ_SMS"]}}}')"+rr_hook "eas submit -p android" "$D"+[ "$RC" -eq 0 ] && rr_has 'critical=0 high=0 medium=0' && rr_has 'NOT CHECKED' && ok "rr-A11-4 a clean Expo config with blockedPermissions stays clean and NOT CHECKED" || bad "rr-A11-4 a clean Expo config with blockedPermissions stays clean and NOT CHECKED (rc=$RC)"+rm -rf "$D"++# FP1 a commit or PR message is text, a real submit beside it is not+D="$(mk_ios_bad)"+for c in 'git commit -m "docs: mention eas build"' "git commit -am 'note the fastlane deliver lane'" 'gh pr create --title "Ship" --body "run eas submit -p ios after merge"' 'git tag -a v1 -m "eas submit done"'; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "rr-FP1 a message stays silent. $c" || bad "rr-FP1 a message stays silent. $c (rc=$RC bytes=${#OUT})"+done+for c in 'git commit -m x && eas submit -p ios' 'git commit -m "$(eas submit -p ios)"'; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ok "rr-FP1 a real submit beside a message blocks. $c" || bad "rr-FP1 a real submit beside a message blocks. $c (rc=$RC)"+done+rm -rf "$D"++# ===== Codex review round (October 2026). each case failed on the guard before its fix =====+FL="fast""lane"+cx_payload() { # $1 json shape, $2 command, $3 cwd, $4 tool name. prints one payload+ python3 -c '+import json, sys+kind, cmd, cwd, tool = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]+shapes = {+ "bash": {"tool_name": tool, "tool_input": {"command": cmd}, "cwd": cwd},+ "cursor": {"hook_event_name": "beforeShellExecution", "command": cmd, "cwd": cwd},+ "copilot-str": {"toolName": "bash", "toolArgs": json.dumps({"command": cmd}), "cwd": cwd},+}+print(json.dumps(shapes[kind]))' "$1" "$2" "$3" "${4:-Bash}"+}+CX_NOTOOLS="$(mktemp -d)"; for b in bash grep sed awk find xargs tr head tail mktemp cat rm printf wc sort uniq cut plutil xmllint dirname basename date env ls; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$CX_NOTOOLS/$b"; done++# CX1 a commit message exemption covers only the git segment, never a later command's arguments+D="$(mk_ios_bad)"+rr_hook "git commit -m safe; bash -c 'eval \"\$1\"' -m '$FL deliver'" "$D"+[ "$RC" -eq 2 ] && ok "cx1-1 a -m argument of a later bash -c segment is not blanked as a message" || bad "cx1-1 a -m argument of a later bash -c segment is not blanked as a message (rc=$RC)"+rr_hook "git commit -m \"wip; $FL deliver | later\" -m 'and && eas submit'" "$D"+[ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "cx1-2 separators inside a quoted commit message stay text" || bad "cx1-2 separators inside a quoted commit message stay text (rc=$RC bytes=${#OUT})"+rm -rf "$D"++# CX2 a compound command is classified per segment. any Apple upload keeps the Apple checks+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+for c in "./gradlew bundleRelease && $FL deliver" "$FL deliver && echo bundleRelease" "$FL pilot; ./gradlew assembleRelease"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && rr_has 'MISSING-USAGE-DESCRIPTION' && ! rr_has 'Command targets Android only' && ok "cx2 Apple checks stay on. $c" || bad "cx2 Apple checks stay on. $c (rc=$RC)"+done+rr_hook "./gradlew bundleRelease" "$D"+rr_has 'Command targets Android only' && ok "cx2 a plain Android build stays Android only" || bad "cx2 a plain Android build stays Android only (rc=$RC)"+# An Apple upload is never Android, and an Android word inside another tool's argument is not a gradle task or flag+for c in "$FL deliver output_path:bundleRelease" "$FL pilot upload ipa:app-bundleRelease.ipa" "$FL upload_to_testflight build:assembleRelease" "$FL --verbose deliver notes:run-android" "$FL deliver --platform android" "$FL testflight -p android"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && rr_has 'MISSING-USAGE-DESCRIPTION' && ! rr_has 'Command targets Android only' && ok "cx2b an Apple upload keeps the Apple checks. $c" || bad "cx2b an Apple upload keeps the Apple checks. $c (rc=$RC)"+done+for c in "./gradlew :app:bundleRelease" "./gradlew clean app:assembleRelease --stacktrace" "flutter build appbundle --release"; do+ rr_hook "$c" "$D"+ rr_has 'Command targets Android only' && ok "cx2b a real Android task stays Android only. $c" || bad "cx2b a real Android task stays Android only. $c (rc=$RC)"+done+rm -rf "$D"++# CX14 the platform flag forms 1.0.0 knew are Android only, the forms it did not know keep the Apple checks, as in 1.0.0+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+for c in "eas submit --platform android" "eas build --platform android --profile production"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 0 ] && rr_has 'Command targets Android only' && ok "cx14 Android only. $c" || bad "cx14 Android only. $c (rc=$RC)"+done+for c in "eas build -p android" "eas submit --platform=android" "eas build -p=android"; do+ rr_hook "$c" "$D"+ ! rr_has 'Command targets Android only' && rr_has 'NSCameraUsageDescription' && ok "cx14 the Apple checks still run, as in 1.0.0. $c" || bad "cx14 the Apple checks still run, as in 1.0.0. $c (rc=$RC)"+done+for c in "eas build -p ios" "eas build -p all" "eas submit --platform=android && eas submit --platform=ios"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ! rr_has 'Command targets Android only' && ok "cx14 not Android only. $c" || bad "cx14 not Android only. $c (rc=$RC)"+done+rm -rf "$D"++# CX3 a comment marker inside a string is not a comment. the code after it still counts+D="$(mk_rr_ios '' 'import AVFoundation+let help = """+/* Start a comment using this marker+"""+let camera = AVCaptureDevice.default(for: .video)')"+rr_run "$D"+rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "cx3-1 /* inside a Swift multiline string does not hide the camera call" || bad "cx3-1 /* inside a Swift multiline string does not hide the camera call (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import CoreLocation+let a = "x /* y", b = 1+let m = CLLocationManager()+let c = "z */ w"')"+mkdir -p "$D/Web"; printf 'const t = `\n/* not a comment\n`;\nconst cam = "AVCaptureDevice";\n' > "$D/Web/t.ts"+rr_run "$D"+rr_has 'Location used without' && rr_has 'Camera used without NSCameraUsageDescription' && ok "cx3-2 /* inside a one-line string and a template literal keeps the code" || bad "cx3-2 /* inside a one-line string and a template literal keeps the code (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'class A { func signIn() {} }+let x = 1 /* deleteAccount */+let y = "a" + "b" // deleteUser')"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && ok "cx3-3 a mid-line block comment still satisfies nothing" || bad "cx3-3 a mid-line block comment still satisfies nothing (rc=$RC)"+rm -rf "$D"++# CX3b a /* inside a Swift raw string #"..."#, a multiline raw string, or any number of # is text, not a comment+for src in 'let s = #"/* not a comment"#' 'let s = #"say "hi" /* not a comment"#' 'let s = #"\"/* not a comment"#' 'let s = ##"a "# /* not a comment"##' 'let s = #"""+/* not a comment+"""#' 'let s = ##"""+"""# /* still inside+"""##' 'let s = #"/*"#; let t = #"*/"#'; do+ D="$(mk_rr_ios '' "import AVFoundation+$src+let camera = AVCaptureDevice.default(for: .video)")"+ rr_run "$D"+ rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "cx3b raw string keeps the camera call. ${src%%$'\n'*}" || bad "cx3b raw string keeps the camera call. ${src%%$'\n'*} (rc=$RC)"+ rm -rf "$D"+done+D="$(mk_rr_ios '' 'import AVFoundation+/* AVCaptureDevice */')"+rr_run "$D"+rr_has 'Camera used without' && ok "cx3b a block comment naming AVCaptureDevice counts, as in 1.0.0" || bad "cx3b a block comment naming AVCaptureDevice counts, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AVFoundation+let s = #"raw"# /* AVCaptureDevice.default(for: .video) */')"+rr_run "$D"+rr_has 'Camera used without' && ok "cx3b a mid-line block comment counts as a trigger, as in 1.0.0" || bad "cx3b a mid-line block comment counts as a trigger, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'class A { func signIn() {} }+let s = #"\"# // deleteAccount')"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && ok "cx3b a backslash in a raw string does not turn a trailing comment into code" || bad "cx3b a backslash in a raw string does not turn a trailing comment into code (rc=$RC)"+rm -rf "$D"++# CX4 a translation or config file never satisfies an implementation check+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+mkdir -p "$D/App/en.lproj"; printf '/* TODO: deleteAccount */\n"title" = "deleteUser";\n' > "$D/App/en.lproj/InfoPlist.strings"+printf '{"deleteAccount": "soon"}\n' > "$D/App/flags.json"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && [ "$RC" -eq 2 ] && ok "cx4-1 deleteAccount in InfoPlist.strings or a json config satisfies nothing" || bad "cx4-1 deleteAccount in InfoPlist.strings or a json config satisfies nothing (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+mkdir -p "$D/www"; printf '<html><!-- deleteAccount --><script>function deleteAccount(){ api.del() }</script></html>\n' > "$D/www/index.html"+rr_run "$D"+! rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && ok "cx4-2 a real deletion function in inline HTML script still counts" || bad "cx4-2 a real deletion function in inline HTML script still counts (rc=$RC)"+rm -rf "$D"++# CX11 Cursor beforeShellExecution always gets permission JSON on stdout, the report on stderr+CLEAN="$(mk_ios_clean)"; D="$(mk_ios_bad)"; EMPTY="$(mktemp -d)"+ERRF="$(mktemp)"+OUTJ="$( cd /tmp && cx_payload cursor "$FL deliver" "$CLEAN" | env -u CLAUDE_PROJECT_DIR bash "$GUARD" 2>"$ERRF" )"; RC=$?+printf '%s' "$OUTJ" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("permission")=="allow" else 1)' && [ "$RC" -eq 0 ] && grep -q 'CLEAR' "$ERRF" && ok "cx11-1 an allowed Cursor submit prints permission allow JSON" || bad "cx11-1 an allowed Cursor submit prints permission allow JSON (rc=$RC out=${OUTJ:0:60})"+OUTJ="$( cd /tmp && cx_payload cursor "$FL deliver" "$D" | env -u CLAUDE_PROJECT_DIR bash "$GUARD" 2>"$ERRF" )"; RC=$?+printf '%s' "$OUTJ" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("permission")=="deny" and d.get("user_message") and d.get("agent_message") else 1)' && [ "$RC" -eq 2 ] && grep -q 'BLOCKED' "$ERRF" && ok "cx11-2 a blocked Cursor submit prints permission deny JSON and exits 2" || bad "cx11-2 a blocked Cursor submit prints permission deny JSON and exits 2 (rc=$RC out=${OUTJ:0:60})"+OUTJ="$( cd /tmp && cx_payload cursor "$FL deliver" "$EMPTY" | env -u CLAUDE_PROJECT_DIR bash "$GUARD" 2>"$ERRF" )"; RC=$?+printf '%s' "$OUTJ" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("permission")=="allow" else 1)' && [ "$RC" -eq 0 ] && grep -q 'NOT CHECKED' "$ERRF" && ok "cx11-3 a NOT CHECKED Cursor submit still prints valid JSON" || bad "cx11-3 a NOT CHECKED Cursor submit still prints valid JSON (rc=$RC out=${OUTJ:0:60})"+OUTJ="$( cd /tmp && cx_payload cursor "$FL deliver" "$CLEAN" | env CLAUDE_PROJECT_DIR="$CLEAN" PATH="$CX_NOTOOLS" bash "$GUARD" 2>"$ERRF" )"; RC=$?+[ "$OUTJ" = '{"permission":"allow"}' ] && [ "$RC" -eq 0 ] && ok "cx11-4 the no-tools tier also answers Cursor with JSON" || bad "cx11-4 the no-tools tier also answers Cursor with JSON (rc=$RC out=${OUTJ:0:60})"+rm -rf "$CLEAN" "$D" "$EMPTY" "$ERRF"++# CX16 a managed Expo config with single-quoted keys is read like a double-quoted one+D="$(mktemp -d)"; printf '{"dependencies":{"expo":"51.0.0"}}' > "$D/package.json"+printf "export default {\n expo: { android: { 'permissions': ['android.permission.READ_SMS'] } }\n};\n" > "$D/app.config.js"+rr_hook "eas submit -p android" "$D"+[ "$RC" -eq 2 ] && rr_has 'GOOGLE-PERM-SMS-CALLLOG' && ok "cx16-1 a single-quoted permissions key is read" || bad "cx16-1 a single-quoted permissions key is read (rc=$RC)"+printf "export default { expo: { android: { 'isAndroidBackgroundLocationEnabled': true } } };\n" > "$D/app.config.js"+rr_hook "eas submit -p android" "$D"+[ "$RC" -eq 2 ] && rr_has 'GOOGLE-PERM-BACKGROUND-LOCATION' && ok "cx16-2 a single-quoted background location flag is read" || bad "cx16-2 a single-quoted background location flag is read (rc=$RC)"+printf '{"dependencies":{"expo":"51.0.0","expo-camera":"15.0.0"}}' > "$D/package.json"+printf "export default { expo: { ios: { infoPlist: { 'NSCameraUsageDescription': 'Scan receipts' } } } };\n" > "$D/app.config.js"+rr_hook "eas submit -p ios" "$D"+! rr_has 'Camera module in the Expo app' && ok "cx16-3 a single-quoted camera purpose key is read" || bad "cx16-3 a single-quoted camera purpose key is read (rc=$RC)"+rm -rf "$D"++# CX17 with no jq and no python3, a Copilot toolArgs JSON string is still parsed (that tier reads no payload cwd)+D="$(mk_ios_bad)"+P_CS="$(cx_payload copilot-str "$FL deliver" "$D")"+OUT="$( cd /tmp && printf '%s' "$P_CS" | env CLAUDE_PROJECT_DIR="$D" PATH="$CX_NOTOOLS" bash "$GUARD" 2>&1 )"; RC=$?+[ "$RC" -eq 2 ] && printf '%s' "$OUT" | grep -q 'App Store Compliance Guard' && ok "cx17-1 a Copilot toolArgs string is parsed on the no-tools tier" || bad "cx17-1 a Copilot toolArgs string is parsed on the no-tools tier (rc=$RC bytes=${#OUT})"+P_CS="$(cx_payload copilot-str "ls -la" "$D")"+OUT="$( cd /tmp && printf '%s' "$P_CS" | env CLAUDE_PROJECT_DIR="$D" PATH="$CX_NOTOOLS" bash "$GUARD" 2>&1 )"; RC=$?+[ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "cx17-2 an ordinary Copilot command stays silent on the no-tools tier" || bad "cx17-2 an ordinary Copilot command stays silent on the no-tools tier (rc=$RC)"+rm -rf "$D"++# CX18 only real shell tool names carry a command. a read-only MCP tool named like a terminal is silent+D="$(mk_ios_bad)"+for tn in jq python3; do+ TP="$PATH"; [ "$tn" = python3 ] && { TP="$(mktemp -d)"; for b in bash grep sed awk find xargs tr head tail mktemp cat rm printf wc sort uniq cut plutil xmllint dirname basename date env ls python3; do p="$([ "$b" = python3 ] && pyenv which python3 2>/dev/null || command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$TP/$b"; done; }+ for t in mcp__terminal__explain_command mcp__shell__lint myTerminalHelper; do+ OUT="$( cd /tmp && cx_payload bash "$FL deliver" "$D" "$t" | env -u CLAUDE_PROJECT_DIR PATH="$TP" bash "$GUARD" 2>&1 )"; RC=$?+ [ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "cx18 $t stays silent (tier=$tn)" || bad "cx18 $t stays silent (tier=$tn rc=$RC)"+ done+ for t in run_in_terminal runInTerminal PowerShell execute_cmd; do+ RC="$( cd /tmp && cx_payload bash "$FL deliver" "$D" "$t" | env -u CLAUDE_PROJECT_DIR PATH="$TP" bash "$GUARD" >/dev/null 2>&1; echo $? )"+ [ "$RC" = "2" ] && ok "cx18 $t is scanned (tier=$tn)" || bad "cx18 $t is scanned (tier=$tn rc=$RC)"+ done+ [ "$tn" = python3 ] && rm -rf "$TP"+done+rm -rf "$D" "$CX_NOTOOLS"++# 656 a bare native project under a root framework app is its own app, unless a root build file pulls it in+mk_fw_root_plus_native() {+ local d; d="$(mktemp -d)"; mkdir -p "$d/ios/App" "$d/native/Legacy/Legacy.xcodeproj" "$d/native/Legacy/Legacy"+ printf '{"expo":{"name":"root"}}' > "$d/app.json"+ printf '<plist><dict><key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' > "$d/ios/App/Info.plist"+ printf '%s' "$PLIST_EMPTY" > "$d/ios/App/PrivacyInfo.xcprivacy"+ printf 'let policy="https://root.example.io/privacy-policy"\n' > "$d/ios/App/R.swift"+ printf 'X=1;\n' > "$d/native/Legacy/Legacy.xcodeproj/project.pbxproj"+ printf '<plist><dict></dict></plist>' > "$d/native/Legacy/Legacy/Info.plist"+ printf 'import CoreLocation\nlet m=CLLocationManager()\n' > "$d/native/Legacy/Legacy/L.swift"+ echo "$d"+}+D="$(mk_fw_root_plus_native)"+OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?+[ "$(echo "$OUT" | grep -c '^App\. ')" -eq 2 ] && echo "$OUT" | grep -q "^App\. $D/native/Legacy$" && [ "$RC" -eq 2 ] && ok "i656-1 a bare Xcode project under a root Expo app is scanned on its own" || bad "i656-1 a bare Xcode project under a root Expo app is scanned on its own (rc=$RC sections=$(echo "$OUT" | grep -c '^App\. '))"+mkdir -p "$D/ios/App.xcworkspace"; printf '<Workspace><FileRef location="group:../native/Legacy/Legacy.xcodeproj"></FileRef></Workspace>\n' > "$D/ios/App.xcworkspace/contents.xcworkspacedata"+OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?+! echo "$OUT" | grep -q '^App\. ' && [ "$RC" -eq 2 ] && ok "i656-2 a nested project the root workspace references stays merged" || bad "i656-2 a nested project the root workspace references stays merged (rc=$RC)"+rm -rf "$D"+D="$(mk_fw_root_plus_native)"; rm -rf "$D/native"+mkdir -p "$D/android/app" "$D/libs/legacy/src/main"+printf "include ':app', ':legacy'\nproject(':legacy').projectDir = new File('../libs/legacy')\n" > "$D/android/settings.gradle"+printf 'apply plugin: "com.android.application"\n' > "$D/android/app/build.gradle"+printf 'apply plugin: "com.android.application"\nandroid { defaultConfig { targetSdkVersion 36 } }\n' > "$D/libs/legacy/build.gradle"+printf '<manifest/>' > "$D/libs/legacy/src/main/AndroidManifest.xml"+OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?+! echo "$OUT" | grep -q '^App\. ' && ok "i656-3 an Android project the root settings.gradle includes stays merged" || bad "i656-3 an Android project the root settings.gradle includes stays merged (rc=$RC sections=$(echo "$OUT" | grep -c '^App\. '))"+rm -f "$D/android/settings.gradle"+OUT="$(bash "$GUARD" "$D" 2>&1)"; RC=$?+echo "$OUT" | grep -q "^App\. $D/libs/legacy$" && ok "i656-4 the same Android project with no shared build file is its own app" || bad "i656-4 the same Android project with no shared build file is its own app (rc=$RC)"+rm -rf "$D"++# R3 round 3 review. every input below is one where main scanned or reported, and the branch must too+FL="fast""lane"+# R3-1 a git message that sits inside a command substitution is never blanked+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+rr_hook "git commit -m safe \$(bash -c 'eval \"\$1\"' -m '$FL deliver')" "$D"+[ "$RC" -eq 2 ] && rr_has 'Camera used without' && ok "r3-1 a submit inside a command substitution in a git commit is scanned" || bad "r3-1 a submit inside a command substitution in a git commit is scanned (rc=$RC)"+BT='`'+rr_hook "git commit -m safe ${BT}bash -c 'eval \"\$1\"' -m '$FL deliver'${BT}" "$D"+[ "$RC" -eq 2 ] && ok "r3-1b a submit inside a backtick substitution in a git commit is scanned" || bad "r3-1b a submit inside a backtick substitution in a git commit is scanned (rc=$RC)"+# R3-2 a wrapped Apple upload (npm run, make) keeps the Apple checks next to an Android build+printf '{"scripts":{"submit-ios":"%s deliver","ship":"%s deliver"}}\n' "$FL" "$FL" > "$D/package.json"+printf 'ship:\n\t%s deliver\n' "$FL" > "$D/Makefile"+GW="./gradle""w bundle""Release"+for c in "$GW && npm run submit-ios" "$GW && npm run ship" "$GW && make ship" "$GW && make ship-ios"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && rr_has 'Camera used without' && ! rr_has 'Command targets Android only' && ok "r3-2 Apple checks stay on. $c" || bad "r3-2 Apple checks stay on. $c (rc=$RC)"+done+rr_hook "$GW" "$D"+rr_has 'Command targets Android only' && ok "r3-2b a plain Android build next to a package.json stays Android only" || bad "r3-2b a plain Android build next to a package.json stays Android only (rc=$RC)"+rm -rf "$D"+# R3-3 the comment stripper never drops compiled code after an escaped raw delimiter, a regex literal, or a Rust raw string+for src in 'let text = #"""+\#"""#+/*+"""#' 'let pattern = #/[/*]/#' 'let pattern = /[/*]/' 'let s = "a" + #"\#"/*"#'; do+ D="$(mk_rr_ios '' "import AVFoundation+$src+let camera = AVCaptureDevice.default(for: .video)")"+ rr_run "$D"+ rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r3-3 the camera call survives. ${src%%$'\n'*}" || bad "r3-3 the camera call survives. ${src%%$'\n'*} (rc=$RC)"+ rm -rf "$D"+done+for rs in 'let s = r#"+/*+"#;' 'let p = r"C:\"; let q = "/*";' 'let b = br#"x"#; let q = r"\"; let t = "/*";'; do+ D="$(mk_rr_ios '' 'import AVFoundation')"+ printf '%s\nlet camera = "AVCaptureDevice";\n' "$rs" > "$D/App/lib.rs"+ rr_run "$D"+ rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r3-3 a Rust raw string keeps the code after it. ${rs%%$'\n'*}" || bad "r3-3 a Rust raw string keeps the code after it. ${rs%%$'\n'*} (rc=$RC)"+ rm -rf "$D"+done+D="$(mk_rr_ios '' 'import AVFoundation+/* a real+ * multiline AVCaptureDevice comment */')"+rr_run "$D"+rr_has 'Camera used without' && ok "r3-3b a mention inside a block comment counts as a trigger, as in 1.0.0" || bad "r3-3b a mention inside a block comment counts as a trigger, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AVFoundation+/* an unmarked line inside a block counts as code, as in 1.0.0+ AVCaptureDevice.default(for: .video) */')"+rr_run "$D"+rr_has 'Camera used without' && ok "r3-3c an unmarked line inside a block counts, as in 1.0.0" || bad "r3-3c an unmarked line inside a block counts, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+# R3-4 translation text never proves StoreKit or a restore control+D="$(mk_rr_ios '' 'import Stripe')"+mkdir -p "$D/App/en.lproj"; printf '"help" = "StoreKit";\n"restore" = "Restore Purchases";\n' > "$D/App/en.lproj/InfoPlist.strings"+rr_run "$D"+rr_has 'APPLE-3.1.1-EXTERNAL-PAYMENT' && [ "$RC" -eq 2 ] && ok "r3-4 StoreKit named only in InfoPlist.strings does not hide an external payment SDK" || bad "r3-4 StoreKit named only in InfoPlist.strings does not hide an external payment SDK (rc=$RC)"+rm -rf "$D"+# R3-8 the no-parser fallback stays quiet for a read tool, like jq and python3 do+D="$(mk_ios_bad)"+NOP="$(mktemp -d)"; for b in bash grep sed awk find xargs tr head mktemp cat rm printf wc sort uniq cut plutil xmllint dirname basename date; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$NOP/$b"; done+OUT="$(printf '{"tool_name":"Read","tool_input":{"command":"%s deliver"}}' "$FL" | PATH="$NOP" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "r3-8 a Read payload stays quiet without jq or python3" || bad "r3-8 a Read payload stays quiet without jq or python3 (rc=$RC bytes=${#OUT})"+OUT="$(printf '{"tool_name":"Bash","tool_input":{"command":"%s deliver"}}' "$FL" | PATH="$NOP" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && ok "r3-8b a Bash payload is still scanned without jq or python3" || bad "r3-8b a Bash payload is still scanned without jq or python3 (rc=$RC)"+OUT="$(printf '{"toolName":"run_terminal_command","toolInput":{"command":"%s deliver"}}' "$FL" | PATH="$NOP" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && ok "r3-8c a Grok payload is still scanned without jq or python3" || bad "r3-8c a Grok payload is still scanned without jq or python3 (rc=$RC)"+OUT="$(printf '{"tool_info":{"command_line":"%s deliver"}}' "$FL" | PATH="$NOP" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && ok "r3-8d a Windsurf payload with no tool name is still scanned without jq or python3" || bad "r3-8d a Windsurf payload with no tool name is still scanned without jq or python3 (rc=$RC)"+rm -rf "$D" "$NOP"+# R3-M a clean nested native project never takes the scan away from a managed Expo root with no native folder+D="$(mktemp -d)"; mkdir -p "$D/src" "$D/native/Legacy/Legacy.xcodeproj" "$D/native/Legacy/Legacy"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf 'export function signIn(){}\nexport function createAccount(){}\n' > "$D/src/auth.ts"+printf 'X=1;\n' > "$D/native/Legacy/Legacy.xcodeproj/project.pbxproj"+printf '<plist><dict><key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' > "$D/native/Legacy/Legacy/Info.plist"+printf '%s' "$PLIST_EMPTY" > "$D/native/Legacy/Legacy/PrivacyInfo.xcprivacy"+printf 'let x = 1\n' > "$D/native/Legacy/Legacy/L.swift"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && [ "$RC" -eq 2 ] && ok "r3-M a managed Expo root keeps its account deletion finding beside a clean native child" || bad "r3-M a managed Expo root keeps its account deletion finding beside a clean native child (rc=$RC)"+rm -rf "$D"++# R4 round 4 review. each input is one where main scanned or reported, or a real submit went unchecked+FL="fast""lane"+GW="./gradle""w bundle""Release"+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+# R4-1 a git alias or any git global option other than -C keeps the whole command scanned+rr_hook "git -c 'alias.ship=!f() { eval \"\$3\"; }; f' ship commit -m '$FL deliver'" "$D"+[ "$RC" -eq 2 ] && ok "r4-1 a git alias that runs its argument is scanned" || bad "r4-1 a git alias that runs its argument is scanned (rc=$RC)"+rr_hook "git -C . commit -m 'release notes for $FL deliver'" "$D"+[ "$RC" -eq 0 ] && ok "r4-1b a plain git -C commit message stays text" || bad "r4-1b a plain git -C commit message stays text (rc=$RC)"+# R4-2 only a known harmless command may sit beside an Android build and keep it Android only+mkdir -p "$D/scripts"; printf 'import os\nos.system("%s deliver")\n' "$FL" > "$D/scripts/upload.py"+printf '%s deliver\n' "$FL" > "$D/scripts/upload.sh"+for c in "$GW && python3 scripts/upload.py" "$GW && node scripts/upload.js" "$GW && ruby scripts/upload.rb" "$GW && scripts/upload.sh" "$GW && ./upload" "$GW && deno run up.ts"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ! rr_has 'Command targets Android only' && ok "r4-2 Apple checks stay on. $c" || bad "r4-2 Apple checks stay on. $c (rc=$RC)"+done+for c in "$GW && echo done" "cd android && $GW" "export X=1; $GW" "$GW; ls"; do+ rr_hook "$c" "$D"+ rr_has 'Command targets Android only' && ok "r4-2b stays Android only. $c" || bad "r4-2b stays Android only. $c (rc=$RC)"+done+rm -rf "$D"+# R4-3 an empty or project-less ios folder never counts as the root's own platform+D="$(mktemp -d)"; mkdir -p "$D/src" "$D/ios" "$D/native/Legacy/Legacy.xcodeproj" "$D/native/Legacy/Legacy"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf 'export function signIn(){}\nexport function createAccount(){}\n' > "$D/src/auth.ts"+printf 'X=1;\n' > "$D/native/Legacy/Legacy.xcodeproj/project.pbxproj"+printf '<plist><dict><key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' > "$D/native/Legacy/Legacy/Info.plist"+printf '%s' "$PLIST_EMPTY" > "$D/native/Legacy/Legacy/PrivacyInfo.xcprivacy"+printf 'let x = 1\n' > "$D/native/Legacy/Legacy/L.swift"+rr_run "$D"+rr_has 'APPLE-5.1.1-NO-ACCOUNT-DELETION' && [ "$RC" -eq 2 ] && ok "r4-3 an empty ios folder does not split the native child off a managed Expo root" || bad "r4-3 an empty ios folder does not split the native child off a managed Expo root (rc=$RC)"+rm -rf "$D"+# R4-4 a // inside a JavaScript or Swift regex literal is not a comment+for src in 'const pattern = /[//]/; const camera = "AVCaptureDevice";' 'const u = x.replace(/https?:\/\//, ""); const camera = "AVCaptureDevice";'; do+ D="$(mk_rr_ios '' 'import AVFoundation')"+ printf '%s\n' "$src" > "$D/App/bridge.js"+ rr_run "$D"+ rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r4-4 the code after a regex survives. $src" || bad "r4-4 the code after a regex survives. $src (rc=$RC)"+ rm -rf "$D"+done+D="$(mk_rr_ios '' 'import AVFoundation+ // AVCaptureDevice on its own line+let x = 1')"+rr_run "$D"+rr_has 'Camera used without' && ok "r4-4b a whole-line comment counts as a trigger, as in 1.0.0" || bad "r4-4b a whole-line comment counts as a trigger, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+# R4-7 the no-parser fallback trusts a tool name only when the payload names exactly one+D="$(mk_ios_bad)"+NOP="$(mktemp -d)"; for b in bash grep sed awk find xargs tr head mktemp cat rm printf wc sort uniq cut plutil xmllint dirname basename date; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$NOP/$b"; done+OUT="$(printf '{"metadata":{"tool_name":"Read"},"tool_name":"Bash","tool_input":{"command":"%s deliver"}}' "$FL" | PATH="$NOP" CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && ok "r4-7 a nested tool_name never hides a Bash submit without jq or python3" || bad "r4-7 a nested tool_name never hides a Bash submit without jq or python3 (rc=$RC)"+rm -rf "$D" "$NOP"+# R4-9 workspace runners resolve the selected package's script+D="$(mktemp -d)"; mkdir -p "$D/apps/x/App"+printf '{"name":"root","private":true,"workspaces":["apps/*"]}\n' > "$D/package.json"+printf '{"name":"x","scripts":{"ship-it":"%s deliver"}}\n' "$FL" > "$D/apps/x/package.json"+printf '{"name":"x","targets":{"ship-it":{"executor":"nx:run-commands","options":{"command":"%s deliver"}}}}\n' "$FL" > "$D/apps/x/project.json"+printf '<plist><dict></dict></plist>' > "$D/apps/x/App/Info.plist"; mkdir -p "$D/apps/x/App.xcodeproj"; printf 'X=1;\n' > "$D/apps/x/App.xcodeproj/project.pbxproj"+printf 'import AVFoundation\nlet d = AVCaptureDevice.default(for: .video)\n' > "$D/apps/x/App/A.swift"+for c in "yarn workspace x ship-it" "pnpm --filter x ship-it" "pnpm --filter x run ship-it" "npm -w x run ship-it" "npm --prefix apps/x run ship-it" "turbo run ship-it" "npx turbo run ship-it --filter=x" "nx run x:ship-it" "npx nx run x:ship-it" "lerna run ship-it" "bun --filter x run ship-it"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ok "r4-9 a workspace runner is scanned. $c" || bad "r4-9 a workspace runner is scanned. $c (rc=$RC)"+done+rr_hook "yarn workspace x lint" "$D"+[ "$RC" -eq 0 ] && [ -z "$OUT" ] && ok "r4-9b a workspace runner with a harmless script stays quiet" || bad "r4-9b a workspace runner with a harmless script stays quiet (rc=$RC)"+mkdir -p "$D/apps/web"; printf '{"name":"web","scripts":{"build":"next build"}}\n' > "$D/apps/web/package.json"+printf '{"name":"x","scripts":{"ship-it":"%s deliver","build":"eas build -p ios"}}\n' "$FL" > "$D/apps/x/package.json"+for c in "pnpm --filter web build" "yarn workspace web build" "npm --prefix apps/web run build" "npm -w web run build"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 0 ] && ok "r4-9c a named web package never inherits the mobile package script. $c" || bad "r4-9c a named web package never inherits the mobile package script. $c (rc=$RC)"+done+rr_hook "pnpm --filter x build" "$D"+[ "$RC" -eq 2 ] && ok "r4-9d the named mobile package build script is scanned" || bad "r4-9d the named mobile package build script is scanned (rc=$RC)"+rm -rf "$D"++# R4P the persona review on real monorepo layouts+# R4P-1 a local Expo native module (an Android library) never becomes its own app+D="$(mktemp -d)"; mkdir -p "$D/android/app/src/main" "$D/modules/pay/android/src/main/java"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf '{"dependencies":{"expo":"52","react-native":"0.76"}}' > "$D/package.json"+printf 'apply plugin: "com.android.application"\nandroid { defaultConfig { targetSdkVersion 36 } }\n' > "$D/android/app/build.gradle"+printf '<manifest/>' > "$D/android/app/src/main/AndroidManifest.xml"+printf 'apply plugin: "com.android.library"\n' > "$D/modules/pay/android/build.gradle"+printf '<manifest/>' > "$D/modules/pay/android/src/main/AndroidManifest.xml"+printf 'import com.stripe.android.Stripe\n' > "$D/modules/pay/android/src/main/java/Pay.kt"+rr_run "$D"+! rr_has '^App\. ' && ok "r4p-1 a local native library module stays with the app that uses it" || bad "r4p-1 a local native library module stays with the app that uses it (rc=$RC)"+rm -rf "$D"+# R4P-2 a Tuist Project.swift purpose string counts as the key+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+printf 'let project = Project(name: "App", targets: [.target(name: "App", infoPlist: .extendingDefault(with: ["NSCameraUsageDescription": "Scan receipts to log expenses"]))])\n' > "$D/Project.swift"+rr_run "$D"+! rr_has 'Camera used without' && ok "r4p-2 a camera key set in Tuist Project.swift counts" || bad "r4p-2 a camera key set in Tuist Project.swift counts (rc=$RC)"+rm -rf "$D"+# R4P-3 only a folder named exactly like demo or sample is a demo. resample and sample-store are real apps+for name in resample sample-store; do+ D="$(mktemp -d)"; mkdir -p "$D/ios/Main" "$D/apps/$name/Store.xcodeproj" "$D/apps/$name/Store"+ printf '{"expo":{"name":"root"}}' > "$D/app.json"+ printf '<plist><dict><key>NSLocationWhenInUseUsageDescription</key><string>Show nearby stores</string></dict></plist>' > "$D/ios/Main/Info.plist"+ mkdir -p "$D/ios/Main.xcodeproj"; printf 'X=1;\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+ printf 'X=1;\n' > "$D/apps/$name/Store.xcodeproj/project.pbxproj"+ printf '<plist><dict></dict></plist>' > "$D/apps/$name/Store/Info.plist"+ printf 'import CoreLocation\nlet m = CLLocationManager()\n' > "$D/apps/$name/Store/S.swift"+ rr_run "$D"+ rr_has "^App\. $D/apps/$name$" && ok "r4p-3 apps/$name is scanned as its own app" || bad "r4p-3 apps/$name is scanned as its own app (rc=$RC)"+ rm -rf "$D"+done+# R4P-4 a native StoreKit app needs a real restore call. a plugin's purchase list does not count+D="$(mk_rr_ios '' 'import StoreKit+let p: SKProduct? = nil+func load() { getAvailablePurchases() }')"+rr_run "$D"+rr_has 'APPLE-RESTORE-PURCHASES-MISSING' && ok "r4p-4 a StoreKit app with only getAvailablePurchases still needs Restore Purchases" || bad "r4p-4 a StoreKit app with only getAvailablePurchases still needs Restore Purchases (rc=$RC)"+rm -rf "$D"++# R5 round 5 review+FL="fast""lane"+GW="./gradle""w bundle""Release"+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+# R5-1 a harmless-looking command beside an Android build is trusted only without any substitution, and git is never trusted+for c in "$GW && echo \"\$(python3 scripts/upload.py)\"" "$GW && echo \`./up.sh\`" "$GW && git upload" "$GW && cat <(./up.sh)"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ! rr_has 'Command targets Android only' && ok "r5-1 Apple checks stay on. $c" || bad "r5-1 Apple checks stay on. $c (rc=$RC)"+done+rm -rf "$D"+# R5-2 a // or /* inside a regex never hides code, even with a space before it+for src in 'const pattern = /[ //]/; const camera = "AVCaptureDevice";' 'const pattern = /[ /*]/; const camera = "AVCaptureDevice"; /* tail */' 'const s = "a\+/* not a comment";+const camera = "AVCaptureDevice";'; do+ D="$(mk_rr_ios '' 'import AVFoundation')"+ printf '%s\n' "$src" > "$D/App/bridge.js"+ rr_run "$D"+ rr_has 'Camera used without NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r5-2 the code survives. ${src%%$'\n'*}" || bad "r5-2 the code survives. ${src%%$'\n'*} (rc=$RC)"+ rm -rf "$D"+done+# R5-3 an option in a later command never scopes the runner. the root package script still counts+D="$(mktemp -d)"; mkdir -p "$D/apps/web" "$D/App"+printf '{"name":"root","scripts":{"ship":"%s deliver"}}\n' "$FL" > "$D/package.json"+printf '{"name":"web","scripts":{"ship":"echo web"}}\n' > "$D/apps/web/package.json"+printf '<plist><dict></dict></plist>' > "$D/App/Info.plist"; mkdir -p "$D/App.xcodeproj"; printf 'X=1;\n' > "$D/App.xcodeproj/project.pbxproj"+printf 'import AVFoundation\nlet d = AVCaptureDevice.default(for: .video)\n' > "$D/App/A.swift"+rr_hook "npm run ship && echo --prefix apps/web" "$D"+[ "$RC" -eq 2 ] && ok "r5-3 a later echo --prefix never hides the root script" || bad "r5-3 a later echo --prefix never hides the root script (rc=$RC)"+# R5-5 recursive runners read every package, and a scoped name matches in full+printf '{"name":"root"}\n' > "$D/package.json"; mkdir -p "$D/apps/mob"+printf '{"name":"@mobile/web","scripts":{"ship":"%s deliver"}}\n' "$FL" > "$D/apps/mob/package.json"+for c in "npm --workspaces run ship" "npm run ship --workspaces" "pnpm -r run ship" "pnpm --recursive run ship" "yarn workspaces foreach run ship" "pnpm --filter @mobile/web ship"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ok "r5-5 scanned. $c" || bad "r5-5 scanned. $c (rc=$RC)"+done+rr_hook "pnpm --filter @other/web ship" "$D"+[ "$RC" -eq 2 ] && ok "r5-5b an unknown scoped package falls back to every package" || bad "r5-5b an unknown scoped package falls back to every package (rc=$RC)"+rm -rf "$D"+# R5-7 an Xcode framework project never splits off as its own app+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/modules/Pay/Pay.xcodeproj" "$D/modules/Pay/Pay"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf 'X=1;\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf '<plist><dict><key>NSCameraUsageDescription</key><string>Scan receipts</string></dict></plist>' > "$D/ios/Main/Info.plist"+printf 'productType = "com.apple.product-type.framework";\n' > "$D/modules/Pay/Pay.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/modules/Pay/Pay/Info.plist"+printf 'import AVFoundation\nlet d = AVCaptureDevice.default(for: .video)\n' > "$D/modules/Pay/Pay/P.swift"+rr_run "$D"+! rr_has '^App\. ' && ok "r5-7 a framework Xcode project stays with the app that links it" || bad "r5-7 a framework Xcode project stays with the app that links it (rc=$RC)"+rm -rf "$D"+# R6 persona round 2+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+# R6-1 a message quote left open across lines never hides the submit that bash runs+rr_hook "git commit -m \"a+git commit -m \" ; $FL deliver ; echo \"+\"" "$D"+[ "$RC" -eq 2 ] && ok "r6-1 a multi-line quoted message never hides a submit" || bad "r6-1 a multi-line quoted message never hides a submit (rc=$RC)"+rr_hook "gh pr create -b \"x+\" ; $FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r6-1b a gh body across lines never hides a submit" || bad "r6-1b a gh body across lines never hides a submit (rc=$RC)"+rm -rf "$D"+# R6-2 a /* that never closes was a misread string, so the code after it still counts+D="$(mk_rr_ios '' 'import AVFoundation+let s = "x"+/* stray opener inside what was really a string+let dev = AVCaptureDevice.default(for: .video)')"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r6-2 an unclosed block comment never hides a camera call" || bad "r6-2 an unclosed block comment never hides a camera call (rc=$RC)"+rm -rf "$D"+# R6-3 a camera mention in a closed block comment counts, as in 1.0.0+D="$(mk_rr_ios '' 'import Foundation+/* AVCaptureDevice.default(for: .video)+*/+let s = "x"')"+rr_hook "$FL deliver" "$D"+rr_has 'NSCameraUsageDescription' && ok "r6-3 a camera mention in a block comment counts, as in 1.0.0" || bad "r6-3 a camera mention in a block comment counts, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+# R7 Codex round 6+# R7-1 a C# verbatim string, a Rust string holding /*, and a mid-line // never hide a camera call+D="$(mk_rr_ios '' 'let s = "x"')"+printf '%s\n' 'var path = @"C:\"; var q = " // "; var camera = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Video);' > "$D/App/Cam.cs"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r7-1a a C# verbatim string never hides a camera call" || bad "r7-1a a C# verbatim string never hides a camera call (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'let s = "x"')"+printf '%s\n' 'let s = "a' '/* b";' 'let camera = unsafe { AVCaptureDevice::defaultDeviceWithMediaType(AVMediaTypeVideo) };' '/* end */' > "$D/App/cam.rs"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r7-1b a Rust string holding /* never hides a camera call" || bad "r7-1b a Rust string holding /* never hides a camera call (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'import AVFoundation+let q = "a" ; _ = 1 // b ; let dev = AVCaptureDevice.default(for: .video)')"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r7-1c code after a mid-line // still counts, as on main" || bad "r7-1c code after a mid-line // still counts, as on main (rc=$RC)"+rm -rf "$D"+# R7-2 a later web workspace build never masks an earlier root submit script+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/apps/web"+printf '{"name":"root","scripts":{"ship":"eas submit -p ios"}}' > "$D/package.json"+printf '{"name":"web","scripts":{"build":"vercel deploy"}}' > "$D/apps/web/package.json"+rr_hook "npm run ship && yarn workspace web build" "$D"+[ "$RC" -eq 2 ] && ok "r7-2 every runner in the command is read" || bad "r7-2 every runner in the command is read (rc=$RC)"+# R7-2b runner shorthands that name a script without run+for c in "bun ship" "turbo ship" "nx run-many -t ship" "nx affected --target=ship" "pnpm -r ship"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ok "r7-2b scanned. $c" || bad "r7-2b scanned. $c (rc=$RC)"+done+rm -rf "$D"+# R7-3 git beside an Android build can run a configured helper, so the Apple checks stay on+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+for c in "$GW && git diff --no-index --ext-diff /dev/null README.md" "$GW && git status"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ! rr_has 'Command targets Android only' && ok "r7-3 Apple checks stay on. $c" || bad "r7-3 Apple checks stay on. $c (rc=$RC)"+done+# R7-5 Kiro runs PowerShell through execute_pwsh+OUT="$(python3 -c 'import json,sys; print(json.dumps({"hook_event_name":"preToolUse","tool_name":"execute_pwsh","tool_input":{"command":sys.argv[1]}}))' "$FL deliver" | CLAUDE_PROJECT_DIR="$D" bash "$GUARD" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && ok "r7-5 a Kiro execute_pwsh submit is checked" || bad "r7-5 a Kiro execute_pwsh submit is checked (rc=$RC)"+rm -rf "$D"+# R7-4 a brownfield native host that embeds React Native stays in the root scan, so its OTA updater is still reported+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/Native/Native.xcodeproj"+printf '{"name":"r","dependencies":{"react-native":"0.76.0"}}' > "$D/package.json"+printf '{"name":"r","displayName":"R"}' > "$D/app.json"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Main/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf 'let url = CodePush.bundleURL()\n' > "$D/Native/Entry.swift"+rr_run "$D"+rr_has 'RN-OTA-UNDECLARED' && ok "r7-4 a brownfield host keeps the React Native checks" || bad "r7-4 a brownfield host keeps the React Native checks (rc=$RC)"+rm -rf "$D"+# R8 Codex round 7+# R8-1 a multi-line Rust string holding /* and quotes never hides a camera call+D="$(mk_rr_ios '' 'let s = "x"')"+printf '%s\n' 'let pattern = "first' '/* \"quoted\"' 'last";' 'let camera = unsafe {' ' AVCaptureDevice::defaultDeviceWithMediaType(AVMediaTypeVideo)' '};' '/* end */' > "$D/App/cam.rs"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r8-1 a multi-line string holding /* never hides a camera call" || bad "r8-1 a multi-line string holding /* never hides a camera call (rc=$RC)"+rm -rf "$D"+# R8-2 JSX text holding // never hides the deletion handler after it+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+printf '%s\n' 'export const S = () => <View><Text>a // b</Text><Button onPress={deleteAccount} /></View>;' > "$D/App/Settings.tsx"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r8-2 JSX text holding // keeps the handler after it" || bad "r8-2 JSX text holding // keeps the handler after it (rc=$RC)"+rm -rf "$D"+# R8-3 an Objective-C Capacitor host is brownfield and stays in the root scan+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/Native/Native.xcodeproj"+printf '{"name":"r","dependencies":{"@capacitor/core":"6.0.0"}}' > "$D/package.json"+printf 'export default { appId: "a.b" };\n' > "$D/capacitor.config.ts"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Main/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf '#import <Capacitor/Capacitor.h>\n@interface H : CAPBridgeViewController\n@end\n@implementation H { UIWebView *old; }\n@end\n' > "$D/Native/Host.m"+rr_run "$D"+rr_has 'IONIC-UIWEBVIEW-DEPRECATED' && ok "r8-3 an Objective-C Capacitor host keeps the Ionic checks" || bad "r8-3 an Objective-C Capacitor host keeps the Ionic checks (rc=$RC)"+rm -rf "$D"+# R8-4 a quoted folder holding a ; is never split into two commands+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/apps/a;b"; printf '{"name":"ab","scripts":{"ship":"eas submit -p ios"}}' > "$D/apps/a;b/package.json"+rr_hook "npm --prefix \"apps/a;b\" run ship" "$D"+[ "$RC" -eq 2 ] && ok "r8-4 a quoted folder with ; still finds the script" || bad "r8-4 a quoted folder with ; still finds the script (rc=$RC)"+# R8-5 a script defined only in a child package, reached by nx, bun or several filters+mkdir -p "$D/apps/mobile" "$D/apps/web"+printf '{"name":"@acme/mobile","scripts":{"ship":"eas submit -p ios"}}' > "$D/apps/mobile/package.json"+printf '{"name":"@acme/web","scripts":{"ship":"vercel deploy"}}' > "$D/apps/web/package.json"+for c in "nx ship mobile" "nx affected --target=ship" "bun run --filter @acme/mobile ship" "pnpm --filter @acme/mobile --filter @acme/web ship"; do+ rr_hook "$c" "$D"+ [ "$RC" -eq 2 ] && ok "r8-5 scanned. $c" || bad "r8-5 scanned. $c (rc=$RC)"+done+rm -rf "$D"+# R9 Codex round 8+# R9-1 a pointer write led by * and a line with code after a leading /* note */ are code+D="$(mk_rr_ios '' 'let s = "x"')"+printf '%s\n' 'void f(void **out) {' '*out = (__bridge void *)[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];' '}' > "$D/App/P.m"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r9-1a a pointer write led by * is code" || bad "r9-1a a pointer write led by * is code (rc=$RC)"+rm -rf "$D"+D="$(mk_rr_ios '' 'let s = "x"')"+printf '%s\n' '/* note */ AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSString *s = @"*/";' > "$D/App/Q.m"+rr_hook "$FL deliver" "$D"+[ "$RC" -eq 2 ] && ok "r9-1b code after a leading /* note */ counts" || bad "r9-1b code after a leading /* note */ counts (rc=$RC)"+rm -rf "$D"+# R9-2 a // inside a string never hides the deletion call after it+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+printf '%s\n' 'const s = " // x "; deleteAccount();' > "$D/App/del.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r9-2 a // inside a string keeps the deletion after it" || bad "r9-2 a // inside a string keeps the deletion after it (rc=$RC)"+rm -rf "$D"+# R9-3 a runner inside $( ) never masks the outer submit script+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/apps/web"+printf '{"name":"root","scripts":{"ship":"eas submit -p ios"}}' > "$D/package.json"+printf '{"name":"web","scripts":{"args":"printf x"}}' > "$D/apps/web/package.json"+rr_hook "npm run ship -- \"\$(yarn workspace web args)\"" "$D"+[ "$RC" -eq 2 ] && ok "r9-3 a nested runner never masks the outer submit" || bad "r9-3 a nested runner never masks the outer submit (rc=$RC)"+rm -rf "$D"+# R9-4 a native host that imports Cordova under a Capacitor root is brownfield and keeps the Ionic checks+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/Native/Native.xcodeproj"+printf '{"name":"r","dependencies":{"@capacitor/core":"6.0.0","cordova-plugin-x":"1.0.0"}}' > "$D/package.json"+printf 'export default { appId: "a.b" };\n' > "$D/capacitor.config.ts"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Main/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf '#import <Cordova/CDV.h>\nUIWebView *webView;\n' > "$D/Native/Host.m"+rr_run "$D"+rr_has 'IONIC-UIWEBVIEW-DEPRECATED' && ok "r9-4 a Cordova host keeps the Ionic checks" || bad "r9-4 a Cordova host keeps the Ionic checks (rc=$RC)"+rm -rf "$D"+# R10 Codex round 9+# R10-1 a spaced pointer write and code after a closing */ count as triggers+for src in '* out = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];' ' */ AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];'; do+ D="$(mk_rr_ios '' 'let s = "x"')"+ printf '%s\n' "$src" > "$D/App/R.m"+ rr_hook "$FL deliver" "$D"+ [ "$RC" -eq 2 ] && ok "r10-1 the camera call counts. $src" || bad "r10-1 the camera call counts. $src (rc=$RC)"+ rm -rf "$D"+done+# R10-2 runner text inside an argument never hides the outer npm script+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/apps/web"+printf '{"name":"root","scripts":{"ship":"eas submit -p ios"}}' > "$D/package.json"+printf '{"name":"web","scripts":{"args":"printf x"}}' > "$D/apps/web/package.json"+rr_hook "npm run ship -- --path=\"yarn workspace web args.ipa\"" "$D"+[ "$RC" -eq 2 ] && ok "r10-2 runner text in an argument never hides the npm script" || bad "r10-2 runner text in an argument never hides the npm script (rc=$RC)"+rm -rf "$D"+# R10-3 a Swift host that imports Cordova stays in the root scan+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/Native/Native.xcodeproj"+printf '{"name":"r","dependencies":{"@capacitor/core":"6.0.0"}}' > "$D/package.json"+printf 'export default { appId: "a.b" };\n' > "$D/capacitor.config.ts"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Main/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf 'import Cordova\nclass AppDelegate: CDVAppDelegate { var legacy: UIWebView? }\n' > "$D/Native/AppDelegate.swift"+rr_run "$D"+rr_has 'IONIC-UIWEBVIEW-DEPRECATED' && ok "r10-3 a Swift Cordova host keeps the Ionic checks" || bad "r10-3 a Swift Cordova host keeps the Ionic checks (rc=$RC)"+rm -rf "$D"+# R10-4 a // inside a single-quoted string keeps the deletion after it+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+printf '%s\n' "const s = ' // x '; deleteAccount();" > "$D/App/del.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r10-4 a // in a single-quoted string keeps the deletion" || bad "r10-4 a // in a single-quoted string keeps the deletion (rc=$RC)"+rm -rf "$D"+# R7-6 a purpose key in an XcodeGen include, an Nx project.json, a Tuist helper or a Cordova config.xml counts+for f in targets/App.yml project.json Tuist/ProjectDescriptionHelpers/Info.swift config.xml; do+ D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+ mkdir -p "$D/$(dirname "$f")"; printf 'NSCameraUsageDescription Scan receipts\n' > "$D/$f"+ rr_hook "$FL deliver" "$D"+ ! rr_has 'NSCameraUsageDescription' && ok "r7-6 a camera key in $f counts" || bad "r7-6 a camera key in $f counts (rc=$RC)"+ rm -rf "$D"+done++# R11 Codex round 10+# R11-1 triggers read every line raw, as in 1.0.0, so a // line holding a live Swift interpolation still counts+D="$(mk_rr_ios '' 'import AVFoundation+let message = """+// \(AVCaptureDevice.requestAccess(for: .video, completionHandler: { _ in }))+"""')"+rr_hook "$FL deliver" "$D"+rr_has 'NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r11-1 a // line holding an interpolation still triggers" || bad "r11-1 a // line holding an interpolation still triggers (rc=$RC)"+rm -rf "$D"+# R11-2 an RCTAppDelegate host stays in the root scan and keeps the React Native checks+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/ios/Main" "$D/Native/Native.xcodeproj" "$D/Native/js"+printf '{"name":"r","dependencies":{"expo":"51.0.0","react-native":"0.74.0"}}' > "$D/package.json"+printf 'module.exports = { name: "r" };\n' > "$D/app.config.js"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Main/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf 'import React_RCTAppDelegate\nclass AppDelegate: RCTAppDelegate {}\n' > "$D/Native/Host.swift"+printf '{"name":"native-js","dependencies":{"@react-native-async-storage/async-storage":"2"}}' > "$D/Native/js/package.json"+printf "import AsyncStorage from '@react-native-async-storage/async-storage';\nAsyncStorage.getItem('x');\n" > "$D/Native/js/storage.js"+rr_run "$D"+rr_has 'RN-PRIVACY-MANIFEST-MISSING' && ok "r11-2 an RCTAppDelegate host keeps the React Native checks" || bad "r11-2 an RCTAppDelegate host keeps the React Native checks (rc=$RC)"+rm -rf "$D"+# R11-3 a zsh =(...) substitution is executable, so a commit message and a safe command lose their pass+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/scripts"; printf '%s deliver\n' "$FL" > "$D/scripts/up.sh"+rr_hook "git commit -m \"$FL deliver\" =(sh scripts/up.sh)" "$D"+[ "$RC" -eq 2 ] && ok "r11-3 a zsh =() beside a commit message still scans" || bad "r11-3 a zsh =() beside a commit message still scans (rc=$RC)"+rr_hook "./gradlew bundleRelease && echo =(sh scripts/up.sh)" "$D"+rr_has 'NSCameraUsageDescription' && ok "r11-3 a zsh =() beside an Android build keeps the Apple checks" || bad "r11-3 a zsh =() beside an Android build keeps the Apple checks (rc=$RC)"+rm -rf "$D"+# R11-4 a /* ... */ pair inside quoted strings never removes the code between them+D="$(mk_rr_ios '' 'class A { func signIn() {} }')"+printf '%s\n' "signIn();" "const s = ' /* '; deleteAccount(); const end = ' */ ';" > "$D/App/del.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r11-4 quoted block markers keep the deletion between them" || bad "r11-4 quoted block markers keep the deletion between them (rc=$RC)"+rm -rf "$D"+# R12 Codex round 11+# R12-1 an Android word inside a quoted lane parameter is text, so an iOS lane keeps the Apple checks+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/fastlane"+UP="upload_to_""testflight"+printf 'lane :beta do |options|\n %s(changelog: options[:notes])\nend\n' "$UP" > "$D/fastlane/Fastfile"+rr_hook "$FL beta notes:\"test -p android\"" "$D"+rr_has 'NSCameraUsageDescription' && [ "$RC" -eq 2 ] && ok "r12-1 a quoted -p android in a lane parameter keeps the Apple checks" || bad "r12-1 a quoted -p android in a lane parameter keeps the Apple checks (rc=$RC)"+rr_hook "$FL beta notes:'flutter build appbundle'" "$D"+rr_has 'NSCameraUsageDescription' && ok "r12-1 a single-quoted Android build in a parameter keeps the Apple checks" || bad "r12-1 a single-quoted Android build in a parameter keeps the Apple checks (rc=$RC)"+rm -rf "$D"+# R12-1b a plain Android release command still stays Android only+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+rr_hook "./gradlew bundleRelease" "$D"+! rr_has 'NSCameraUsageDescription' && ok "r12-1b a plain Android build still skips the Apple checks" || bad "r12-1b a plain Android build still skips the Apple checks (rc=$RC)"+rm -rf "$D"+# R13 Codex round 12+# R13-1 a harmless echo, a comment or a second line naming Android never vouches for an iOS lane+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/fastlane"+UP="upload_to_""testflight"+printf 'lane :beta do |options|\n %s(changelog: options[:notes])\nend\n' "$UP" > "$D/fastlane/Fastfile"+for c in "$FL beta notes:\"test -p android\"; echo -p android" "$FL beta notes:\"test -p android\" # -p android" "$FL beta notes:\"x -p android\" && ./gradlew bundleRelease"; do+ rr_hook "$c" "$D"+ rr_has 'NSCameraUsageDescription' && ok "r13-1 the iOS lane keeps the Apple checks. $c" || bad "r13-1 the iOS lane keeps the Apple checks. $c (rc=$RC)"+done+rm -rf "$D"+# R13-2 a host using React's surface view, or an Android React activity, stays in the root scan+for host in 'import React+let v = RCTSurfaceHostingProxyRootView(bridge: b, moduleName: "x")' 'class MainActivity : ReactActivity() {}'; do+ D="$(mktemp -d)"; mkdir -p "$D/ios/App.xcodeproj" "$D/ios/App" "$D/Native/Host.xcodeproj"+ printf '{"name":"r","dependencies":{"react-native":"0.74.0"}}' > "$D/package.json"+ printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/App.xcodeproj/project.pbxproj"+ printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Host.xcodeproj/project.pbxproj"+ printf '<plist><dict></dict></plist>' > "$D/ios/App/Info.plist"+ printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+ printf '%s\n' "$host" > "$D/Native/Host.swift"+ printf 'AsyncStorage.getItem("theme");\n' > "$D/Native/Feature.ts"+ rr_run "$D"+ rr_has 'RN-PRIVACY-MANIFEST-MISSING' && ok "r13-2 a React host keeps the React Native checks. ${host%%$'\n'*}" || bad "r13-2 a React host keeps the React Native checks. ${host%%$'\n'*} (rc=$RC)"+ rm -rf "$D"+done+# R14 Codex round 13+# R14-1 a quoted lane name, a quoted variable or a quoted fastlane still counts as an iOS submit beside an Android one+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+mkdir -p "$D/fastlane"+UP="upload_to_""testflight"+printf 'lane :beta do |options|\n %s(changelog: options[:notes])\nend\n' "$UP" > "$D/fastlane/Fastfile"+EA="eas"" submit"+for c in "$FL \"beta\" notes:\"test -p android\"; $EA -p android" "$FL \"\$LANE\" notes:x; $EA -p android" "\"$FL\" beta; $EA -p android"; do+ rr_hook "$c" "$D"+ rr_has 'NSCameraUsageDescription' && ok "r14-1 the iOS submit keeps the Apple checks. $c" || bad "r14-1 the iOS submit keeps the Apple checks. $c (rc=$RC)"+done+rr_hook "$EA -p android && echo done" "$D"+rr_has 'NSCameraUsageDescription' && ok "r14-1b a -p android submit beside a harmless echo keeps the Apple checks, as in 1.0.0" || bad "r14-1b a -p android submit beside a harmless echo keeps the Apple checks, as in 1.0.0 (rc=$RC)"+rm -rf "$D"+# R14-2 a native app split off a framework root keeps that root's framework checks+D="$(mktemp -d)"; mkdir -p "$D/ios/App.xcodeproj" "$D/ios/App" "$D/Native/Legacy.xcodeproj"+printf '{"name":"r","dependencies":{"@capacitor/core":"6.0.0"}}' > "$D/package.json"+printf 'export default { appId: "a.b" };\n' > "$D/capacitor.config.ts"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/App.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Legacy.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/App/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf 'import UIKit\nvar legacy: UIWebView?\n' > "$D/Native/Legacy.swift"+rr_run "$D"+rr_has 'IONIC-UIWEBVIEW-DEPRECATED' && ok "r14-2 a split native app keeps the root framework checks" || bad "r14-2 a split native app keeps the root framework checks (rc=$RC)"+rm -rf "$D"+# R15 Codex round 14+# R15-1 a wrapped Apple submit never borrows an Android flag from a harmless command, Android only needs main's rule too+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+printf '{"name":"r","scripts":{"ship":"%s deliver"}}' "$FL" > "$D/package.json"+rr_hook "npm run ship; echo -p android" "$D"+rr_has 'NSCameraUsageDescription' && ok "r15-1 a wrapped Apple submit keeps the Apple checks beside echo -p android" || bad "r15-1 a wrapped Apple submit keeps the Apple checks beside echo -p android (rc=$RC)"+rm -rf "$D"+# R15-2 a framework marker inside a split native app still counts for the root it was pooled with+D="$(mktemp -d)"; mkdir -p "$D/ios/App.xcodeproj" "$D/Native/Native.xcodeproj"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf '{"name":"r","dependencies":{"react-native":"0.74.0"}}' > "$D/package.json"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/App.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Info.plist"+printf 'import UIKit\nvar legacy: UIWebView?\n' > "$D/ios/Legacy.swift"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf '<widget id="com.acme.native"/>\n' > "$D/Native/config.xml"+rr_run "$D"+rr_has 'IONIC-UIWEBVIEW-DEPRECATED' && ok "r15-2 a framework marker in a split native app still counts for the root" || bad "r15-2 a framework marker in a split native app still counts for the root (rc=$RC)"+rm -rf "$D"+# R16 Codex round 15+# R16-1 a wrapped Apple submit never borrows an Android flag from an echo beside it+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+printf '{"name":"r","scripts":{"ship":"%s deliver"}}' "$FL" > "$D/package.json"+for c in "npm run ship; echo --platform android" "npm run ship && echo build apk"; do+ rr_hook "$c" "$D"+ rr_has 'NSCameraUsageDescription' && ok "r16-1 a wrapped Apple submit keeps the Apple checks. $c" || bad "r16-1 a wrapped Apple submit keeps the Apple checks. $c (rc=$RC)"+done+rm -rf "$D"+# R16-2 a wrapped submit that names Android itself stays Android only+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+BR="bundle""Release"+printf '{"name":"r","scripts":{"ship":"./gradlew %s"}}' "$BR" > "$D/package.json"+rr_hook "npm run ship -- --platform android" "$D"+rr_has 'Command targets Android only' && ok "r16-2 a wrapped submit naming Android itself stays Android only" || bad "r16-2 a wrapped submit naming Android itself stays Android only (rc=$RC)"+rm -rf "$D"+# R17 Codex round 16+# R17-1 a submit quoted inside bash -c never takes an Android word from the outer arguments+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+UP="upload_to_""testflight"+mkdir -p "$D/fastlane"; printf 'lane :beta do\n %s\nend\n' "$UP" > "$D/fastlane/Fastfile"+rr_hook "bash -c '$FL beta' --platform android" "$D"+rr_has 'NSCameraUsageDescription' && ok "r17-1 a submit inside bash -c keeps the Apple checks beside outer Android arguments" || bad "r17-1 a submit inside bash -c keeps the Apple checks beside outer Android arguments (rc=$RC)"+rm -rf "$D"+# R17-2 evidence split between the root and a split native app still counts, scanned as one as in 1.0.0+D="$(mktemp -d)"; mkdir -p "$D/ios/App.xcodeproj" "$D/Shared" "$D/Native/Native.xcodeproj"+printf '{"expo":{"name":"root"}}' > "$D/app.json"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/App.xcodeproj/project.pbxproj"+printf 'productType = "com.apple.product-type.application";\n' > "$D/Native/Native.xcodeproj/project.pbxproj"+printf '<plist><dict></dict></plist>' > "$D/ios/Info.plist"+printf '<plist><dict></dict></plist>' > "$D/Native/Info.plist"+printf 'let title = "Monthly subscription"\n' > "$D/Shared/Pricing.swift"+printf 'let cancel = "Call us to cancel"\n' > "$D/Native/Cancel.swift"+rr_run "$D"+rr_has 'BOTH-SUBSCRIPTION-HARD-CANCEL' && ok "r17-2 evidence split across a split native app still counts" || bad "r17-2 evidence split across a split native app still counts (rc=$RC)"+[ "$(printf '%s' "$OUT" | grep -c 'BOTH-SUBSCRIPTION-HARD-CANCEL')" -le 1 ] && ok "r17-2b the pooled pass never lists a finding twice" || bad "r17-2b the pooled pass never lists a finding twice"+rm -rf "$D"+# R18 Codex round 17+# R18-1 a submit quoted inside any shell, by path or behind env or sudo, never takes the outer Android arguments+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+UP="upload_to_""testflight"+mkdir -p "$D/fastlane"; printf 'lane :beta do\n %s\nend\n' "$UP" > "$D/fastlane/Fastfile"+for c in "/bin/bash -c '$FL beta' --platform android" "env bash -c '$FL beta' --platform android" "sudo sh -c '$FL beta' --platform android"; do+ rr_hook "$c" "$D"+ rr_has 'NSCameraUsageDescription' && ok "r18-1 a quoted submit keeps the Apple checks. $c" || bad "r18-1 a quoted submit keeps the Apple checks. $c (rc=$RC)"+done+rm -rf "$D"+# R18-2 an Nx target whose options carry an env object still names its submit command+D="$(mktemp -d)"; mkdir -p "$D/apps/x/App"+printf '{"name":"root","private":true,"workspaces":["apps/*"]}\n' > "$D/package.json"+printf '{"name":"x","targets":{"ship":{"executor":"nx:run-commands","options":{"env":{"NODE_ENV":"production"},"command":"%s deliver"}}}}\n' "$FL" > "$D/apps/x/project.json"+printf '<plist><dict></dict></plist>' > "$D/apps/x/App/Info.plist"; mkdir -p "$D/apps/x/App.xcodeproj"; printf 'X=1;\n' > "$D/apps/x/App.xcodeproj/project.pbxproj"+printf 'import AVFoundation\nlet d = AVCaptureDevice.default(for: .video)\n' > "$D/apps/x/App/A.swift"+rr_hook "nx run x:ship" "$D"+[ "$RC" -eq 2 ] && ok "r18-2 an Nx target with an env object is still a submit" || bad "r18-2 an Nx target with an env object is still a submit (rc=$RC)"+rm -rf "$D"+# R19 the guard itself on macOS bash 3.2, which reads the \001 separator as a quoting byte+if [ -x /bin/bash ] && /bin/bash --version 2>/dev/null | grep -q 'version 3\.'; then+ D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+ EA="eas"" submit"+ OUT="$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"Bash","tool_input":{"command":sys.argv[1]}}))' "$EA --platform android" | CLAUDE_PROJECT_DIR="$D" /bin/bash "$GUARD" 2>&1)"; RC=$?+ [ "$RC" -eq 0 ] && rr_has 'Command targets Android only' && ok "r19 bash 3.2 reads an Android submit as Android only" || bad "r19 bash 3.2 reads an Android submit as Android only (rc=$RC)"+ rm -rf "$D"+fi+# R20 Codex round 18+# R20-1 a submit inside python -c or ruby -e never takes the outer Android arguments+D="$(mk_rr_ios '' 'import AVFoundation+let dev = AVCaptureDevice.default(for: .video)')"+UP="upload_to_""testflight"+mkdir -p "$D/fastlane"; printf 'lane :beta do\n %s\nend\n' "$UP" > "$D/fastlane/Fastfile"+for c in "python3 -c '__import__(\"os\").system(\"$FL beta\")' --platform android" "ruby -e 'system(\"$FL beta\")' --platform android"; do+ rr_hook "$c" "$D"+ rr_has 'NSCameraUsageDescription' && ok "r20-1 a submit inside another program keeps the Apple checks. $c" || bad "r20-1 a submit inside another program keeps the Apple checks. $c (rc=$RC)"+done+rm -rf "$D"+# R20-2 code after a closing block comment on the same line still counts+D="$(mk_rr_ios '' 'class A { func signIn() {} }+/* Account settings action.+ */ func deleteAccount() { removeCurrentUserAndData() }')"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r20-2 a deletion after a closing block comment still counts" || bad "r20-2 a deletion after a closing block comment still counts (rc=$RC)"+rm -rf "$D"+# R21 Codex round 19+# R21-1 an exclusion-only pnpm filter reads every other package, so the submitting one is found+D="$(mktemp -d)"; mkdir -p "$D/apps/docs" "$D/apps/mobile/App"+printf '{"name":"root","private":true}\n' > "$D/package.json"+printf 'packages: ["apps/*"]\n' > "$D/pnpm-workspace.yaml"+printf '{"name":"@acme/docs","scripts":{"ship":"echo done"}}\n' > "$D/apps/docs/package.json"+printf '{"name":"@acme/mobile","scripts":{"ship":"%s deliver"}}\n' "$FL" > "$D/apps/mobile/package.json"+printf '<plist><dict></dict></plist>' > "$D/apps/mobile/App/Info.plist"; mkdir -p "$D/apps/mobile/App.xcodeproj"; printf 'X=1;\n' > "$D/apps/mobile/App.xcodeproj/project.pbxproj"+printf 'import AVFoundation\nlet d = AVCaptureDevice.default(for: .video)\n' > "$D/apps/mobile/App/A.swift"+rr_hook "pnpm --filter '!@acme/docs' run ship" "$D"+[ "$RC" -eq 2 ] && ok "r21-1 an exclusion-only pnpm filter still finds the submitting package" || bad "r21-1 an exclusion-only pnpm filter still finds the submitting package (rc=$RC)"+rm -rf "$D"+# R22 Codex round 20+# R22-1 an escaped quote inside a string never hides a deletion written after it+D="$(mk_rr_ios '' 'let ready = true')"+printf '%s\n' 'signIn(); const s = "quote: \" // string"; function deleteAccount() { return api.deleteUser(); }' > "$D/App/account.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r22-1 an escaped quote never hides a deletion after it" || bad "r22-1 an escaped quote never hides a deletion after it (rc=$RC)"+rm -rf "$D"+# R23 Codex round 21+# R23-1 the pooled pass keeps a critical finding that shares its id with a high one already listed+D="$(mktemp -d)"; mkdir -p "$D/ios/Main.xcodeproj" "$D/android/app/src/main" "$D/androidRelease/src/main"+printf '{"name":"r","dependencies":{"react-native":"0.74.0"}}' > "$D/package.json"+printf 'productType = "com.apple.product-type.application";\n' > "$D/ios/Main.xcodeproj/project.pbxproj"+printf '<plist><dict><key>ITSAppUsesNonExemptEncryption</key><false/></dict></plist>' > "$D/ios/Info.plist"+printf 'import Photos\nlet lib = PHPhotoLibrary.shared()\n' > "$D/Photo.swift"+printf "include ':app'\n" > "$D/android/settings.gradle"+printf "plugins { id 'com.android.application' }\n" > "$D/android/app/build.gradle"+printf '<manifest package="a.b"/>' > "$D/android/app/src/main/AndroidManifest.xml"+printf "plugins { id 'com.android.application' }\n" > "$D/androidRelease/build.gradle"+printf '<manifest package="a.c"/>' > "$D/androidRelease/src/main/AndroidManifest.xml"+printf 'import AVFoundation\nlet dev = AVCaptureDevice.default(for: .video)\n' > "$D/androidRelease/Camera.swift"+rr_hook "xcodebuild -project ios/Main.xcodeproj archive" "$D"+rr_has 'NSCameraUsageDescription' && ok "r23-1 the pooled pass keeps a critical finding beside a high one with the same id" || bad "r23-1 the pooled pass keeps a critical finding beside a high one with the same id (rc=$RC)"+rm -rf "$D"+# R23-2 a quote inside a JS regex literal never hides a deletion after it+D="$(mk_rr_ios '' 'let ready = true')"+printf '%s\n' 'signIn(); const r = /"/; const s = " // "; function deleteAccount() { return api.deleteUser(); }' > "$D/App/account.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r23-2 a quote in a regex literal never hides a deletion" || bad "r23-2 a quote in a regex literal never hides a deletion (rc=$RC)"+rm -rf "$D"+# R24 Codex round 22+# R24-1 a JS regex literal holding a quote and a space never hides a deletion after it+D="$(mk_rr_ios '' 'let ready = true')"+printf '%s\n' 'signIn(); const r = /" /; const s = " // "; function deleteAccount() { return api.deleteUser(); }' > "$D/App/account.js"+rr_run "$D"+! rr_has 'NO-ACCOUNT-DELETION' && ok "r24-1 a regex literal with a space never hides a deletion" || bad "r24-1 a regex literal with a space never hides a deletion (rc=$RC)"+rm -rf "$D"+# R25 Codex round 23+# R25-1 removing an inline comment never joins two words into deletion evidence+D="$(mk_rr_ios '' 'let ready = true')"+printf '%s\n' 'extern void sendSignup(void);' 'void createAccount(void) { sendSignup(); }' 'typedef int account;' 'account /* cache */deletion = 0;' > "$D/App/Account.m"+rr_run "$D"+rr_has 'NO-ACCOUNT-DELETION' && ok "r25-1 a removed comment never manufactures deletion evidence" || bad "r25-1 a removed comment never manufactures deletion evidence (rc=$RC)"+rm -rf "$D"+# R25-2 a regex literal after && or return never hides a deletion after it+for js in 'signIn(); const r = true && /"/; const s = " // "; function deleteAccount() { return api.deleteUser(); }' \+ 'signIn(); function f() { return /"/; } const s = " // "; function deleteAccount() { return api.deleteUser(); }'; do+ D="$(mk_rr_ios '' 'let ready = true')"+ printf '%s\n' "$js" > "$D/App/account.js"+ rr_run "$D"+ ! rr_has 'NO-ACCOUNT-DELETION' && ok "r25-2 a regex literal after an operator never hides a deletion" || bad "r25-2 a regex literal after an operator never hides a deletion (rc=$RC)"+ rm -rf "$D"+done+# R26 Qwen round 24. a regex literal after + - * < > never hides a deletion after it+for op in '+' '-' '*' '>' '<' '%'; do+ D="$(mk_rr_ios '' 'let ready = true')"+ printf '%s\n' "var a = 1; signIn(); const x = a $op /\"/; const s = \" // \"; function deleteAccount() { return api.deleteUser(); }" > "$D/App/account.js"+ rr_run "$D"+ ! rr_has 'NO-ACCOUNT-DELETION' && ok "r26 a regex literal after $op never hides a deletion" || bad "r26 a regex literal after $op never hides a deletion (rc=$RC)"+ rm -rf "$D"+doneecho ""echo "app-store-compliance-guard-test: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/agent-os/hooks/app-store-compliance-guard.sh b/agent-os/hooks/app-store-compliance-guard.shindex 6dd5d2a..7ed3b08 100755--- a/agent-os/hooks/app-store-compliance-guard.sh+++ b/agent-os/hooks/app-store-compliance-guard.sh@@ -10,10 +10,10 @@ HOOK_LOG="${HOME:-}/.claude/hooks/hook-log.sh"[ -f "$HOOK_LOG" ] && source "$HOOK_LOG" 2>/dev/null || truelog_err() { if type hlog_error >/dev/null 2>&1; then hlog_error "app-store-compliance-guard" "$@"; else echo "app-store-compliance-guard: $*" >&2; fi; }-CRIT=0; HIGH=0; MED=0; ANY_IOS=0; ANY_AND=0; ANY_NATIVE=0; ANY_RN=0; ANY_WEB=0; ANY_NEEDS_NATIVE=0; NATIVE_HINT=""; UNCHECKED=""+CRIT=0; HIGH=0; MED=0; ANY_IOS=0; ANY_AND=0; ANY_NATIVE=0; ANY_RN=0; ANY_WEB=0; ANY_NEEDS_NATIVE=0; NATIVE_HINT=""; UNCHECKED=""; EXPO_READ=0FILELIST=""REPORT=""; REPORT_DEGRADED=0-cleanup() { [ -n "$FILELIST" ] && rm -f "$FILELIST" "$FILELIST.blob" "$FILELIST.manifest" 2>/dev/null; [ -n "$REPORT" ] && rm -f "$REPORT" 2>/dev/null; true; }+cleanup() { [ -n "$FILELIST" ] && rm -f "$FILELIST" "$FILELIST.blob" "$FILELIST.manifest" "$FILELIST.code" "$FILELIST.impl" 2>/dev/null; [ -n "$REPORT" ] && rm -f "$REPORT" 2>/dev/null; true; }trap cleanup EXIT# ----- resolve mode and project dir -----@@ -30,6 +30,20 @@ elif [ ! -t 0 ]; then# An empty hook payload has no command to judge; falling back to scanning the working directory can take minutes.[ -z "$STDIN_JSON" ] && exit 0fi+# Cursor beforeShellExecution reads a permission object on stdout, prose there is a schema error (cursor.com/docs/hooks).+IS_CURSOR=0; CURSOR_SENT=0; CURSOR_FD=0; CURSOR_IDS=""+printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -qE '"hook_event_name"[[:space:]]*:[[:space:]]*"beforeShellExecution"' && IS_CURSOR=1+cursor_reply() { # $1 exit code about to be returned. Prints the permission JSON once, on the real stdout+ [ "$IS_CURSOR" -eq 1 ] && [ "$CURSOR_SENT" -eq 0 ] || return 0+ CURSOR_SENT=1+ if [ "$1" -eq 2 ]; then+ local why="with ${CRIT:-0} critical rejection risk(s)"+ [ "${CRIT:-0}" -eq 0 ] && why="because the scan did not finish"+ printf '{"permission":"deny","user_message":"App Store Compliance Guard blocked this submit %s.","agent_message":"Blocked by app-store-compliance-guard %s. Critical findings. %s Fix each one using the report on stderr, or set APP_STORE_GUARD_OK=1 to override."}\n' "$why" "$why" "${CURSOR_IDS:-none listed.}"+ else+ printf '{"permission":"allow"}\n'+ fi+}# Read .tool_input.command as JSON (issue #610). The best installed parser decides. jq, else python3,# else a backslash-aware regex. A payload the chosen parser rejects yields no command, so the guard stays silent.@@ -37,7 +51,7 @@ tool_ok() { command -v "$1" >/dev/null 2>&1 && "$@" >/dev/null 2>&1; } # presepayload_command() {local outif tool_ok jq -n true; then- out="$(printf '%s' "$STDIN_JSON" | jq -rs 'if length != 1 then empty else .[0] | if (((.tool_name? // "Bash") == "Bash" or .tool_name == "PowerShell") | not) then empty else ((.tool_input.command? | strings) // (.command? | strings) // empty) end end' 2>/dev/null)" && { printf '%s' "$out"; return 0; }+ out="$(printf '%s' "$STDIN_JSON" | jq -rs 'if length != 1 then empty else .[0] | if type != "object" then empty else (.tool_name? // .toolName? // (if (.tool_info.command_line? | type) == "string" then "shell" else "Bash" end)) as $t | if (($t | type) != "string") or ((["Bash","PowerShell","bash","powershell","run_shell_command","shell","Execute","launch-process","execute_bash","execute_cmd","runInTerminal","run_in_terminal","run_terminal_command","run_terminal_cmd","monitor","execute_pwsh"] | any(. == $t)) | not) then empty else ((.tool_input.command? | strings) // (.toolInput.command? | strings) // (.toolArgs? | if type == "string" then (try fromjson catch null) else . end | if type == "object" then (.command? | strings) else empty end) // (.tool_info.command_line? | strings) // (.command? | strings) // empty) end end end' 2>/dev/null)" && { printf '%s' "$out"; return 0; }fiif tool_ok python3 -c pass; thenout="$(printf '%s' "$STDIN_JSON" | python3 -c '@@ -47,23 +61,52 @@ try:except Exception:sys.exit(4)c = None-if isinstance(d, dict) and d.get("tool_name", "Bash") in ("Bash", "PowerShell"):+SHELLS = ("Bash", "PowerShell", "bash", "powershell", "run_shell_command", "shell", "Execute", "launch-process", "execute_bash", "execute_cmd", "runInTerminal", "run_in_terminal", "run_terminal_command", "run_terminal_cmd", "monitor", "execute_pwsh")+info = d.get("tool_info") if isinstance(d, dict) else None+default = "shell" if isinstance(info, dict) and isinstance(info.get("command_line"), str) else "Bash"+t = d.get("tool_name", d.get("toolName", default)) if isinstance(d, dict) else None+if isinstance(d, dict) and isinstance(t, str) and t in SHELLS:ti = d.get("tool_input")+ if not isinstance(ti, dict) and isinstance(d.get("toolInput"), dict):+ ti = d["toolInput"]+ if not isinstance(ti, dict) and isinstance(info, dict) and isinstance(info.get("command_line"), str):+ ti = {"command": info["command_line"]}+ ta = d.get("toolArgs")+ if isinstance(ta, str):+ try:+ ta = json.loads(ta)+ except Exception:+ ta = Noneif isinstance(ti, dict) and isinstance(ti.get("command"), str):c = ti["command"]+ elif isinstance(ta, dict) and isinstance(ta.get("command"), str):+ c = ta["command"]elif isinstance(d.get("command"), str):c = d["command"]sys.stdout.buffer.write((c or "").encode("utf-8"))' 2>/dev/null)"; rc=$?[ "$rc" -eq 0 ] && { printf '%s' "$out"; return 0; }[ "$rc" -eq 4 ] && return 0fi- # No working tool. Prefer the command inside tool_input, else the first command key, then unescape it.- local body+ # No working tool. Prefer the command inside tool_input, then a Copilot toolArgs JSON string, then the first command key.+ local body ta tn+ # A named tool that is not a shell stays quiet here too, the same list jq and python3 use.+ tn="$(printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -oE '"(tool_name|toolName)"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed -E 's/.*:[[:space:]]*"//; s/"$//')"+ if [ -n "$tn" ] && [ "$(printf '%s' "$STDIN_JSON" | grep -oE '"(tool_name|toolName)"[[:space:]]*:' | wc -l | tr -d ' ')" -eq 1 ]; then+ case "$tn" in Bash|PowerShell|bash|powershell|run_shell_command|shell|Execute|launch-process|execute_bash|execute_cmd|runInTerminal|run_in_terminal|run_terminal_command|run_terminal_cmd|monitor|execute_pwsh) ;; *) return 0 ;; esac+ fibody="$(printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -oE '"tool_input"[[:space:]]*:[[:space:]]*\{([^{}]|\{[^{}]*\})*"command"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1)"+ if [ -z "$body" ]; then+ ta="$(printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -oE '"toolArgs"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1 | sed -E 's/^"toolArgs"[[:space:]]*:[[:space:]]*"//; s/"$//')"+ [ -n "$ta" ] && body="$(printf '%s' "$ta" | json_unescape | tr -d '\n\r' | grep -oE '"command"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1)"+ fi[ -z "$body" ] && body="$(printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -oE '"command"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1)"+ [ -z "$body" ] && body="$(printf '%s' "$STDIN_JSON" | tr -d '\n\r' | grep -oE '"command_line"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1 | sed 's/"command_line"/"command"/')"[ -z "$body" ] && return 0- printf '%s' "$body" | sed -E 's/.*"command"[[:space:]]*:[[:space:]]*"//; s/"$//' \- | awk 'BEGIN { hx="0123456789abcdef" }+ printf '%s' "$body" | sed -E 's/.*"command"[[:space:]]*:[[:space:]]*"//; s/"$//' | json_unescape+}+# Decodes JSON string escapes on stdin (newline, tab, quote, ASCII \u), for the no-tools tier.+json_unescape() {+ awk 'BEGIN { hx="0123456789abcdef" }{ n=split($0, part, /\\/); o=part[1]; lit=0for (i=2; i<=n; i++) { p=part[i]if (lit) { o=o p; lit=0; continue }@@ -79,8 +122,33 @@ sys.stdout.buffer.write((c or "").encode("utf-8"))' 2>/dev/null)"; rc=$?printf "%s", o }'}+# The working folder another harness reports in the payload (Codex, Gemini CLI, Cursor, Copilot CLI send cwd).+payload_cwd() {+ if tool_ok jq -n true; then+ printf '%s' "$STDIN_JSON" | jq -rs 'if length == 1 and (.[0] | type) == "object" then .[0] | ((.cwd? | strings) // (.tool_info.cwd? | strings) // (.working_dir? | strings) // (.tool_input.cwd? | strings) // (.workspace_roots[0]? | strings) // empty) else empty end' 2>/dev/null+ return 0+ fi+ if tool_ok python3 -c pass; then+ printf '%s' "$STDIN_JSON" | python3 -c '+import json, sys+try:+ d = json.loads(sys.stdin.buffer.read().decode("utf-8-sig"))+except Exception:+ sys.exit(0)+c = None+if isinstance(d, dict):+ ti, info, roots = d.get("tool_input"), d.get("tool_info"), d.get("workspace_roots")+ for v in (d.get("cwd"), info.get("cwd") if isinstance(info, dict) else None, d.get("working_dir"),+ ti.get("cwd") if isinstance(ti, dict) else None, roots[0] if isinstance(roots, list) and roots else None):+ if isinstance(v, str) and v:+ c = v+ break+sys.stdout.write(c or "")' 2>/dev/null+ fi+}+if [ -n "$STDIN_JSON" ]; then- # Only a Bash or PowerShell tool call carries a shell command. The jq and python3 tiers check the top-level tool_name.+ # Only a shell tool call (Bash, run_shell_command, Grok run_terminal_command, and kin) carries a shell command. The jq and python3 tiers check the top-level tool_name.# The no-tools tier cannot tell a top-level key from a nested one, so it scans rather than skips.CMD="$(payload_command 2>/dev/null | tr -d '\000')"# Fold a backslash-newline continuation (odd trailing backslashes) into one space. Bare newlines stay,@@ -91,9 +159,43 @@ if [ -n "$STDIN_JSON" ]; thenif (k%2==1) { acc=acc substr(l,1,n-1) " "; cont=1 } else { printf "%s%s\n", acc, l; acc="" } }END { if (cont) printf "%s\n", acc }' 2>/dev/null)"[ -z "$CMD" ] && exit 0+ # A commit, tag, note, or gh PR or issue message is text. Its quoted -m, --body, or --title value is blanked,+ # Only inside that git or gh segment, never a later command's, and never when the segment holds any substitution.+ IFS= read -r -d '' INERT_AWK <<'INERT'+BEGIN { sq=sprintf("%c", 39); dq="\""; bt=sprintf("%c", 96) }+function msgflag(w) { return w ~ /^(-[A-Za-z]*m|--message|-b|--body|-t|--title)$/ }+function blank(s, o, i, n, c, w, prev, j, body) {+ o=""; w=""; prev=""; i=1; n=length(s)+ while (i <= n) { c=substr(s, i, 1)+ if (c == " " || c == "\t") { if (w != "") { prev=w; w="" }; o=o c; i++; continue }+ if (c == "\\") { o=o substr(s, i, 2); w=w substr(s, i, 2); i+=2; continue }+ if (c == sq || c == dq) {+ j=i+1; while (j <= n && substr(s, j, 1) != c) { if (c == dq && substr(s, j, 1) == "\\") j++; j++ }+ body=substr(s, i+1, j-i-1)+ if (j <= n && ((w == "" && msgflag(prev)) || (w ~ /=$/ && msgflag(substr(w, 1, length(w)-1)))) && (c == sq || (index(body, "$") == 0 && index(body, bt) == 0))) {+ o=o c c; w=w c c; i=j+1; continue }+ o=o substr(s, i, j-i+1); w=w substr(s, i, j-i+1); i=j+1; continue }+ o=o c; w=w c; i++ }+ return o }+function seg(s, t) {+ if (index(s, "$(") || index(s, bt) || index(s, "<(") || index(s, ">(") || index(s, "=(")) return s+ t=s; sub(/^[ \t({!]+/, "", t)+ while (t ~ /^[A-Za-z_][A-Za-z0-9_]*=[^ \t]*[ \t]+/) sub(/^[A-Za-z_][A-Za-z0-9_]*=[^ \t]*[ \t]+/, "", t)+ if (t ~ /^git([ \t]+-C[ \t]+[^ \t]+)?[ \t]+(commit|tag|notes)([ \t]|$)/ || t ~ /^gh[ \t]+(pr|issue)[ \t]+(create|comment|edit)([ \t]|$)/) return blank(s)+ return s }+{ l=$0; n=length(l); cur=""; out=""; q=""; i=1+ while (i <= n) { c=substr(l, i, 1)+ if (q != "") { if (c == "\\" && q == dq) { cur=cur substr(l, i, 2); i+=2; continue }; if (c == q) q=""; cur=cur c; i++; continue }+ if (c == "\\") { cur=cur substr(l, i, 2); i+=2; continue }+ if (c == sq || c == dq) { q=c; cur=cur c; i++; continue }+ if (c == ";" || c == "|" || c == "&") { out=out seg(cur) c; cur=""; i++; continue }+ cur=cur c; i++ }+ raw[NR]=l; msk[NR]=out seg(cur); if (q != "") open=1 }+END { for (k=1; k<=NR; k++) print (open ? raw[k] : msk[k]) }+INERT# Match raw with quotes and letter escapes stripped. Only a single simple line led by an inert text command# (echo, grep, cat) has quoted spans blanked, and a heredoc body is blanked unless an interpreter consumes it.- CMD_MATCH="$(printf '%s' "$CMD" | awk 'BEGIN { sq=sprintf("%c", 39); dq="\""; bt=sprintf("%c", 96); hd=0 }+ CMD_MATCH="$( { printf '%s\n' "$CMD" | awk "$INERT_AWK" 2>/dev/null || printf '%s' "$CMD"; } | awk 'BEGIN { sq=sprintf("%c", 39); dq="\""; bt=sprintf("%c", 96); hd=0 }{ l=$0if (hd) { t=l; sub(/^\t+/, "", t); if (t == hd_end) { hd=0 } else if (!hd_keep) { l="" } ; print l; next }if (match(l, /<<-?[ \t]*[\047"]?[A-Za-z_][A-Za-z0-9_]*[\047"]?/) && substr(l, RSTART+2, 1) != "<") {@@ -112,6 +214,13 @@ if [ -n "$STDIN_JSON" ]; thenCMD_MATCH="$(printf '%s' "$CMD_MATCH" | sed -E 's/(npm|pnpm|yarn|bun|brew|pip3?|gem|cargo)[[:space:]]+(install|add|i|uninstall|remove)([[:space:]][^;&|$`]*)?//g')"# A Debug publish is a local build, never a store upload.CMD_MATCH="$(printf '%s' "$CMD_MATCH" | sed -E 's/dotnet[[:space:]]+publish[^;&|]*(-c|--configuration)[[:space:]=]+[Dd]ebug[^;&|]*//g')"+ # fastlane global options sit before the action or lane (fastlane --env production deliver). Drop them.+ fl_norm() { printf '%s' "$1" | sed -E ':a+s/(fastlane)[[:space:]]+--env([[:space:]]+|=)[^-[:space:];&|][^[:space:];&|]*/\1/+ta+s/(fastlane)[[:space:]]+--?[A-Za-z][A-Za-z0-9_-]*/\1/+ta'; }+ CMD_MATCH="$(fl_norm "$CMD_MATCH")"SUBMIT_RE='fastlane[[:space:]]+(run[[:space:]]+)?(deliver|pilot|supply|submit|appstore|testflight|upload_to_app_store|upload_to_testflight|upload_to_play_store)([^A-Za-z0-9_]|$)|eas([[:space:]]+--?[A-Za-z][A-Za-z0-9-]*([=[:space:]][^-[:space:]][^[:space:]]*)?)*[[:space:]]+(submit|build)|xcrun[[:space:]]+(altool|notarytool)|transporter|gradlew?[^&|;]*(bundleRelease|assembleRelease|publish[A-Za-z]*(Bundle|Apk|Apps)|promote[A-Za-z]*Artifact)|bundletool|xcodebuild[^&|;]*archive|flutter[[:space:]]+build[[:space:]]+(ipa|appbundle|apk|ios)|(npx[[:space:]]+)?(expo[[:space:]]+(prebuild|run:ios|run:android|submit|upload:(ios|android)|build:(ios|android))|cap[[:space:]]+(sync|build|run|copy|open)|react-native[[:space:]]+run-(ios|android))|ionic[[:space:]]+capacitor[[:space:]]+(build|run)|cordova[[:space:]]+build([[:space:]]+--release)?|(^|[^A-Za-z0-9_])unity(-editor|\.exe)?[[:space:]][^;&|]*-buildtarget[[:space:]]+(ios|android)|dotnet[[:space:]]+publish[^;&|]*(-f|--framework)[[:space:]=]+net[0-9.]+-(ios|android)|tauri[[:space:]]+(ios|android)[[:space:]]+build'UPLOAD_ACTION_RE='(^|[^A-Za-z0-9_])(upload_to_app_store|upload_to_testflight|upload_to_play_store|deliver|pilot|supply|appstore|testflight)([^A-Za-z0-9_]|$)'# A custom fastlane lane submits when a word in its name says so, when its Fastfile block calls an@@ -132,22 +241,64 @@ $(find "$DIR" -maxdepth 3 -name Fastfile -not -path '*/node_modules/*' 2>/dev/nuFASTFILESreturn 1}- submits() { printf '%s' "$1" | grep -qiE "$SUBMIT_RE" || printf '%s' "$1" | grep -qE 'gradlew?[[:space:]]+\$' || fastlane_lane_submits "$1"; }+ submits() { set -- "$(fl_norm "$1")"; printf '%s' "$1" | grep -qiE "$SUBMIT_RE" || printf '%s' "$1" | grep -qE 'gradlew?[[:space:]]+\$' || fastlane_lane_submits "$1"; }# What a package script or a make target runs, one level deep, so a wrapped submit is still seen.- wrapper_body() {+ runner_body() { # $1 one command segmentlocal name esc sub pj seg w prev mf targets mfileslocal opts='([[:space:]]+--?[A-Za-z][A-Za-z-]*([=[:space:]][^-[:space:]][^[:space:]]*)?)*'- name="$(printf '%s' "$CMD_MATCH" | sed -nE 's/.*(^|[^A-Za-z0-9_.\/-])(npm|pnpm|bun)'"$opts"'[[:space:]]+run(-script)?[[:space:]]+([A-Za-z0-9:_.-]+).*/\6/p' | head -1)"- [ -z "$name" ] && name="$(printf '%s' "$CMD_MATCH" | sed -nE 's/.*(^|[^A-Za-z0-9_.\/-])yarn'"$opts"'[[:space:]]+(run[[:space:]]+)?([A-Za-z0-9:_.-]+).*/\5/p' | head -1)"+ local pre='.*(^|[^A-Za-z0-9_./-])'+ name="$(printf '%s' "$1" | sed -nE "s/${pre}(npm|pnpm|bun)${opts}[[:space:]]+run(-script)?${opts}[[:space:]]+([A-Za-z0-9:_.][A-Za-z0-9:_.-]*).*/\8/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}yarn[[:space:]]+workspace[[:space:]]+[^[:space:]]+[[:space:]]+(run[[:space:]]+)?([A-Za-z0-9:_.-]+).*/\3/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}yarn[[:space:]]+workspaces[[:space:]]+foreach${opts}[[:space:]]+(run[[:space:]]+)?([A-Za-z0-9:_.-]+).*/\5/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}(turbo|lerna)${opts}[[:space:]]+run[[:space:]]+([A-Za-z0-9:_.-]+).*/\5/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}nx${opts}[[:space:]]+run(-many)?[[:space:]]+([A-Za-z0-9_.@\/-]+:)?([A-Za-z0-9_.][A-Za-z0-9_.-]*).*/\6/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}nx${opts}[[:space:]]+(run-many|affected)([[:space:]]+[^[:space:]]+)*[[:space:]]+(-t|--targets?)[=[:space:]]+([A-Za-z0-9_.-]+).*/\7/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}(pnpm|bun|turbo)${opts}[[:space:]]+([A-Za-z0-9:_.-]+).*/\5/p" | head -1)"+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}nx${opts}[[:space:]]+([A-Za-z0-9:_.-]+).*/\4/p" | head -1)"+ case "$name" in run|run-many|affected|exec|install|i|add|x|dlx) name="" ;; esac+ [ -z "$name" ] && name="$(printf '%s' "$1" | sed -nE "s/${pre}yarn${opts}[[:space:]]+(run[[:space:]]+)?([A-Za-z0-9:_.-]+).*/\5/p" | head -1)"if [ -n "$name" ]; then+ local sel sub all files pick s2 base f d pat scoped oneesc="$(printf '%s' "$name" | sed 's/\./\\./g')"- sub="$(printf '%s' "$CMD_MATCH" | sed -nE 's/.*[[:space:]](--dir|--prefix|--cwd|-C)[=[:space:]]+([^[:space:]]+).*/\2/p' | head -1)"+ # The package the runner names, or the folder it runs in. Unknown or none named means every package is read.+ local rseg="$1"+ sel="$(printf '%s\n' "$rseg" | grep -oE '(yarn[[:space:]]+workspace|(^|[[:space:]])(--filter|-F|--workspace|-w|--scope))[=[:space:]]+[^[:space:]]+' | sed -E 's/.*[=[:space:]]//')"+ [ -z "$sel" ] && sel="$(printf '%s' "$rseg" | sed -nE 's/.*nx[^;&|]*[[:space:]]run[[:space:]]+([A-Za-z0-9_.@\/-]+):.*/\1/p' | head -1)"+ sub="$(printf '%s' "$rseg" | sed -nE 's/.*[[:space:]](--dir|--prefix|--cwd|-C)[=[:space:]]+([^[:space:]]+).*/\2/p' | head -1)"case "$sub" in /*|*..*) sub="" ;; esac- for pj in "$DIR/package.json" ${sub:+"$DIR/$sub/package.json"}; do- [ -f "$pj" ] && grep -E "^[[:space:]]*\"$esc\"[[:space:]]*:" "$pj" 2>/dev/null | head -1+ all=0; printf '%s' "$rseg" | grep -qE '(^|[^A-Za-z0-9_./-])(turbo|lerna)[[:space:]]|(^|[^A-Za-z0-9_./-])nx[[:space:]]|[[:space:]](-r|--recursive|-ws|--workspaces|foreach)([[:space:]=]|$)' && all=1+ files="$(find "$DIR" -maxdepth 6 \( -type d \( -name node_modules -o -name .git -o -name Pods -o -name build \) -prune \) -o \( -name package.json -o -name project.json \) -print 2>/dev/null | head -200)"+ if [ -n "$sub" ] && [ -f "$DIR/$sub/package.json" ]; then pick="$DIR/$sub/package.json"+ elif [ -n "$sel" ]; then+ pick=""+ while IFS= read -r s2; do+ [ -n "$s2" ] || continue+ # an exclusion such as '!@acme/docs' selects every other package, so every package is read+ case "$s2" in '!'*) pick="$files"; break ;; esac+ s2="${s2#./}"; s2="${s2#!}"; s2="${s2#^}"; s2="${s2#...}"; s2="${s2%...}"; s2="${s2#\{}"; s2="${s2%\}}"; s2="${s2%/}"; base="${s2##*/}"+ # bash 3.2 misreads a case pattern inside $( ), so the scope test sits out here.+ scoped=0; pat="(@[^/\"]+/)?$base"+ case "$s2" in @*/*) scoped=1; pat="$s2" ;; esac+ one="$(printf '%s\n' "$files" | while IFS= read -r f; do+ [ -n "$f" ] || continue; d="$(dirname "$f")"+ if [ "$scoped" -eq 0 ] && { [ "${d##*/}" = "$base" ] || [ "${d%/$s2}" != "$d" ]; }; then echo "$f"; continue; fi+ tr -d '\n' < "$f" 2>/dev/null | grep -qE "\"name\"[[:space:]]*:[[:space:]]*\"$pat\"" && echo "$f"+ done)"+ if [ -z "$one" ]; then pick="$files"; break; fi+ pick="$pick+$one"+ done <<SELS+$sel+SELS+ elif [ "$all" -eq 1 ]; then pick="$files"+ else pick="$DIR/package.json"; fi+ pick="$(printf '%s\n%s' "$DIR/package.json" "$pick" | awk 'NF && !seen[$0]++')"+ printf '%s\n' "$pick" | while IFS= read -r pj; do+ [ -f "$pj" ] || continue+ tr -d '\n' < "$pj" 2>/dev/null | grep -oE "\"$esc\"[[:space:]]*:[[:space:]]*(\"([^\"\\\\]|\\\\.)*\"|\{([^{}]|\{([^{}]|\{[^{}]*\})*\})*)"donefi- seg="$(printf '%s' "$CMD_MATCH" | sed -nE 's/.*(^|[^A-Za-z0-9_.\/-])make[[:space:]]+([^;&|]*).*/\2/p' | head -1)"+ seg="$(printf '%s' "$1" | sed -nE 's/.*(^|[^A-Za-z0-9_.\/-])make[[:space:]]+([^;&|]*).*/\2/p' | head -1)"if [ -n "$seg" ]; thentargets=""; mfiles="Makefile makefile GNUmakefile"; prev=""set -f@@ -165,12 +316,26 @@ FASTFILESset +ffi}+ wrapper_body() { # every runner and make segment, so a later web build never masks an earlier submit+ local sg+ runner_body "$CMD_MATCH"+ printf '%s\n' "$CMD_MATCH" | tr ';&|$()`' '\n\n\n\n\n\n\n' | while IFS= read -r sg; do+ [ -n "$sg" ] && runner_body "$sg"+ done+ }# Cheap exit for the everyday command. Nothing below runs unless a submit tool or a wrapper is named.if ! printf '%s' "$CMD_MATCH" | grep -qiE "$SUBMIT_RE" \- && ! printf '%s' "$CMD_MATCH" | grep -qE '(^|[^A-Za-z0-9_./-])(fastlane|npm|pnpm|bun|yarn|make)[[:space:]]|gradlew?[[:space:]]+\$'; then+ && ! printf '%s' "$CMD_MATCH" | grep -qE '(^|[^A-Za-z0-9_./-])(fastlane|npm|pnpm|bun|yarn|make|turbo|nx|lerna)[[:space:]]|gradlew?[[:space:]]+\$'; thenexit 0fi- DIR="${CLAUDE_PROJECT_DIR:-$PWD}"+ DIR="${CLAUDE_PROJECT_DIR:-}"+ if [ -z "$DIR" ]; then+ PCWD="$(payload_cwd 2>/dev/null)"+ if [ -n "$PCWD" ] && [ -d "$PCWD" ]; then DIR="$PCWD"+ elif [ -n "${GEMINI_PROJECT_DIR:-}" ] && [ -d "${GEMINI_PROJECT_DIR}" ]; then DIR="$GEMINI_PROJECT_DIR"+ elif [ -n "${AUGMENT_PROJECT_DIR:-}" ] && [ -d "${AUGMENT_PROJECT_DIR}" ]; then DIR="$AUGMENT_PROJECT_DIR"+ else DIR="$PWD"; fi+ fi# A leading "cd <dir> &&" scopes the scan to that app (an EAS monorepo submits from apps/<app>).# The target must resolve inside the project root, otherwise the root is scanned as before.FIRST="$(printf '%s' "$CMD" | head -1)"@@ -193,14 +358,89 @@ fi# See docs/CROSS-PLATFORM-FRAMEWORKS.md: an Android-only command beats a committed ios/# folder for the Apple-only checks below (standalone mode has no CMD, unaffected).CMD_TARGET_ANDROID_ONLY=0-if [ -n "$CMD" ] \- && printf '%s' "$CMD" | grep -qiE 'build[[:space:]]+(apk|appbundle)\b|assembleRelease|bundleRelease|run-android|run:android|--platform[[:space:]]+android\b|capacitor[[:space:]]+android\b|-buildtarget[[:space:]]+android|net[0-9.]+-android|tauri[[:space:]]+android\b' \- && ! printf '%s' "$CMD" | grep -qiE '\bios\b|\bipa\b|xcodebuild|altool|notarytool'; then- CMD_TARGET_ANDROID_ONLY=1+# An Android token must be the gradle task, the platform flag or the build verb itself, never a word inside another argument.+W_END='([[:space:]]|$)'+AND_TARGET_RE="(^|[[:space:]])flutter[[:space:]]+build[[:space:]]+(apk|appbundle)$W_END|(^|[[:space:]/])gradlew?([[:space:]]+[^[:space:]]+)*[[:space:]]+:?([A-Za-z0-9_.-]+:)*(assembleRelease|bundleRelease)$W_END|(^|[[:space:]])(run-android|run:android)$W_END|(^|[[:space:]])(-p|--platform)([[:space:]]+|=)android$W_END|capacitor[[:space:]]+android$W_END|(^|[[:space:]])-buildtarget[[:space:]]+android$W_END|(^|[[:space:]=])net[0-9.]+-android$W_END|tauri[[:space:]]+android$W_END"+# An Apple upload in a segment means that segment is never Android, whatever words its arguments carry.+IOS_TARGET_RE='\bios\b|\bipa\b|xcodebuild|altool|notarytool|transporter|fastlane[[:space:]]+(run[[:space:]]+)?(deliver|pilot|appstore|testflight|upload_to_app_store|upload_to_testflight)([^A-Za-z0-9_]|$)'+if [ -n "$CMD" ]; then+ # Each submitting segment is classified on its own. Android only means every submit in the command is Android.+ SEG_SUBMITS=0; SEG_ALL_AND=1+ # Beside an Android submit only a known harmless command keeps it Android only. Anything else may upload to Apple.+ SAFE_SEG_RE='^(cd|pushd|popd|echo|printf|export|unset|set|true|false|:|test|sleep|ls|pwd|mkdir|rm|cp|mv|cat|touch|tee|grep|head|tail|wc|date|clear)$'+ SUBST=0; printf '%s' "$CMD" | grep -qE '\$\(|`|<\(|>\(|=\(' && SUBST=1+ while IFS= read -r SEG; do+ W1="$(printf '%s' "$SEG" | awk '{ sub(/^[ \t({!]+/, ""); while (match($0, /^[A-Za-z_][A-Za-z0-9_]*=[^ \t]*[ \t]+/)) $0 = substr($0, RLENGTH + 1); print $1 }')"+ [ -n "$W1" ] || continue+ if ! submits "$SEG"; then+ { [ "$SUBST" -eq 0 ] && printf '%s' "$W1" | grep -qE "$SAFE_SEG_RE"; } || SEG_ALL_AND=0+ continue+ fi+ SEG_SUBMITS=$((SEG_SUBMITS+1))+ SEGN="$(fl_norm "$SEG")"+ { printf '%s' "$SEGN" | grep -qiE "$AND_TARGET_RE" && ! printf '%s' "$SEGN" | grep -qiE "$IOS_TARGET_RE"; } || SEG_ALL_AND=0+ done <<SEGS+$(printf '%s\n' "$CMD_MATCH" | tr ';&|' '\n\n\n')+SEGS+ if printf '%s' "$CMD" | grep -qiE "$IOS_TARGET_RE"; then+ : # an Apple word anywhere in the command keeps the Apple checks, as on main+ elif [ "$SEG_SUBMITS" -gt 0 ]; then+ [ "$SEG_ALL_AND" -eq 1 ] && CMD_TARGET_ANDROID_ONLY=1+ # A wrapped submit (npm run, make) names no tool in the command itself, so the whole command decides, as before.+ elif printf '%s' "$CMD" | grep -qiE "$AND_TARGET_RE" && ! printf '%s' "$CMD" | grep -qiE "$IOS_TARGET_RE"; then+ CMD_TARGET_ANDROID_ONLY=1+ fi+ # Each command in the line is read twice, quoted text kept and quoted text blanked, # comments dropped. A submit is found+ # in the kept text, its Android word only in the blanked text, and anything that is neither a submit nor harmless keeps Apple.+ if [ "$CMD_TARGET_ANDROID_ONLY" -eq 1 ]; then+ NQ_SEP="$(printf '\037')"+ CMD_PAIRS="$(printf '%s' "$CMD" | awk -v sq="'" -v sep="$NQ_SEP" '{ k=""; b=""; n=length($0); i=1+ while (i <= n) { c=substr($0, i, 1)+ if (c == "#" && (i == 1 || substr($0, i-1, 1) ~ /[ \t]/)) break+ if (c == sq || c == "\"") { j=i+1; while (j <= n && substr($0, j, 1) != c) { if (c == "\"" && substr($0, j, 1) == "\\") j++; j++ }+ k=k substr($0, i+1, j-i-1); b=b " "; i=j+1; continue }+ if (c == ";" || c == "&" || c == "|" || c == "(" || c == ")") { print k sep b; k=""; b=""; i++; continue }+ k=k c; b=b c; i++ }+ print k sep b }')"+ NQ_SUB=0; NQ_AND=1; NQ_WRAP=0; NQ_WRAP_AND=1+ while IFS="$NQ_SEP" read -r NQK NQB; do+ NQW="$(printf '%s' "$NQK" | awk '{ sub(/^[ \t({!]+/, ""); while (match($0, /^[A-Za-z_][A-Za-z0-9_]*=[^ \t]*[ \t]+/)) $0 = substr($0, RLENGTH + 1); print $1 }')"+ [ -n "$NQW" ] || continue+ if submits "$NQK"; then+ NQ_SUB=$((NQ_SUB+1))+ printf '%s' "$NQB" | grep -qiE "$AND_TARGET_RE" || NQ_AND=0+ # the outer arguments of bash -c, sh -c or eval never reach the quoted command, so they name no target+ printf '%s' "$NQB" | grep -qE '(^|[[:space:]/])(bash|sh|zsh|dash|ksh|fish|eval)([[:space:]]|$)' && NQ_AND=0+ # a submit seen only inside quotes runs in another program (python -c, ruby -e), which never passes it the outer arguments+ submits "$NQB" || NQ_AND=0+ elif ! printf '%s' "$NQW" | grep -qE "$SAFE_SEG_RE"; then+ NQ_AND=0; NQ_WRAP=$((NQ_WRAP+1))+ printf '%s' "$NQB" | grep -qiE "$AND_TARGET_RE" || NQ_WRAP_AND=0+ fi+ done <<NQSEGS+$CMD_PAIRS+NQSEGS+ if [ "$SEG_SUBMITS" -gt 0 ]; then+ [ "$NQ_SUB" -gt 0 ] && [ "$NQ_AND" -eq 1 ] || CMD_TARGET_ANDROID_ONLY=0+ else+ # A wrapped submit is Android only when every command that is not harmless names Android itself, never an echo beside it.+ [ "$NQ_WRAP" -gt 0 ] && [ "$NQ_WRAP_AND" -eq 1 ] || CMD_TARGET_ANDROID_ONLY=0+ fi+ fi+fi+# Android only also needs the 1.0.0 rule, so the Apple checks are never off where 1.0.0 ran them.+if [ "$CMD_TARGET_ANDROID_ONLY" -eq 1 ] && ! { printf '%s' "$CMD" | grep -qiE 'build[[:space:]]+(apk|appbundle)\b|assembleRelease|bundleRelease|run-android|run:android|--platform[[:space:]]+android\b|capacitor[[:space:]]+android\b|-buildtarget[[:space:]]+android|net[0-9.]+-android|tauri[[:space:]]+android\b' \+ && ! printf '%s' "$CMD" | grep -qiE '\bios\b|\bipa\b|xcodebuild|altool|notarytool'; }; then+ CMD_TARGET_ANDROID_ONLY=0+fi+CMD_TARGET_IOS_ONLY=0+if [ -n "$CMD" ] && printf '%s' "$CMD" | grep -qiE '(-p|--platform)[[:space:]=]+ios([^A-Za-z]|$)' \+ && ! printf '%s' "$CMD" | grep -qiE 'android|(-p|--platform)[[:space:]=]+all'; then+ CMD_TARGET_IOS_ONLY=1fi[ -z "$DIR" ] && DIR="$PWD"-[ -d "$DIR" ] || { log_err "project dir not found. $DIR"; exit 0; }+[ -d "$DIR" ] || { log_err "project dir not found. $DIR"; cursor_reply 0; exit 0; }[ -L "${DIR%/}" ] && DIR="$(cd "$DIR" 2>/dev/null && pwd -P)" # find never descends a symlinked start point (issue #612)# Every text file once, into one blob, so a hundred grep_has calls read one file instead of every file@@ -229,6 +469,72 @@ manifest_has() { # 0 if regex found in any AndroidManifest.xml in the source li[ -n "$out" ]}+# Where a purpose string can live. Info.plist and its strings, build settings, XcodeGen, Expo config.+CONFIG_FILES_RE='(\.plist|\.pbxproj|\.xcconfig|\.ya?ml|/project\.json|/config\.xml|/Project\.swift|/Tuist/.*\.swift|\.csproj|/app\.json|/app\.config\.[cm]?[jt]s)$'+config_has() { # 0 if regex found in a config file, never in Swift or Kotlin source or a comment there+ [ -s "$FILELIST" ] || return 1+ local out+ out="$(grep -E "$CONFIG_FILES_RE" "$FILELIST" | tr '\n' '\0' | xargs -0 grep -EIls -e "$1" 2>/dev/null | head -1)"+ [ -n "$out" ]+}++SRC_EXT_RE='\.(swift|m|mm|h|kt|kts|java|js|jsx|ts|tsx|dart|cs|rs)$'+# Comments dropped line by line, with no string state, so a misread quote can never hide a later line.+# Only the implementation buffer is stripped. Triggers read every line raw, as in 1.0.0, so no comment rule can hide a call.+STRIP_AWK='BEGIN { sq=sprintf("%c", 39) }+ function opener(s, m, i) { for (i=2; i<length(s); i++) if (substr(s, i, 2) == m && substr(s, i-1, 1) ~ /[ \t;{},)]/) return i; return 0 }+ { l=$0; if (index(l, "/") == 0 && index(l, "*") == 0) { print l; next }+ t=l; sub(/^[ \t]+/, "", t)+ if (substr(t, 1, 2) == "//") { print ""; next }+ if (substr(t, 1, 2) == "*/") { print substr(t, 3); next }+ if (t == "*" || substr(t, 1, 2) == "* " || substr(t, 1, 2) == "*\t") { print ""; next }+ if (substr(t, 1, 2) == "/*") { r=t; sub(/[ \t]+$/, "", r); j=index(substr(r, 3), "*/")+ if (j == 0 || j + 3 == length(r)) { print ""; next } }+ if (tc) {+ while (index(l, "/*") && (o=opener(l, "/*")) > 0 && (c=index(substr(l, o+2), "*/")) > 0) { pre=substr(l, 1, o-1); if (pre !~ /#"/) gsub(/\\./, "", pre); gsub(/(^|[=(,:&|!?{};+*%<>~^-]|return)[ \t]*\/[^\/]+\//, " ", pre); p2=pre+ nq=gsub(/[\"`]/, "", pre); ns=gsub(sq, "", p2); if (nq % 2 || ns % 2) break; l=substr(l, 1, o-1) " ; " substr(l, o+c+3) }+ if (index(l, "//") && (o=opener(l, "//")) > 0 && substr(l, o+2) !~ /<\/|\/>/) { pre=substr(l, 1, o-1); if (pre !~ /#"/) gsub(/\\./, "", pre); gsub(/(^|[=(,:&|!?{};+*%<>~^-]|return)[ \t]*\/[^\/]+\//, " ", pre); p2=pre; nq=gsub(/[\"`]/, "", pre); ns=gsub(sq, "", p2); if (nq % 2 == 0 && ns % 2 == 0) l=substr(l, 1, o-1) } }+ print l }'+build_code() { # .code is the trigger buffer, .impl the buffer an implementation must appear in (no config or translation text)+ CODE_OK=0+ : > "$FILELIST.code" 2>/dev/null || return 0+ : > "$FILELIST.impl" 2>/dev/null || return 0+ { grep -E "$SRC_EXT_RE" "$FILELIST" | tr '\n' '\0' | xargs -0 awk -v tc=1 "$STRIP_AWK" 2>/dev/null+ grep -E '\.html$' "$FILELIST" | tr '\n' '\0' | xargs -0 awk 'function flush( k) { if (nh) { for (k=1; k<=nh; k++) print hr[k]; nh=0 } }+ FNR == 1 { flush(); hc=0 } { l=$0; o=""+ while (l != "") { if (hc) { p=index(l, "-->"); if (p == 0) { l=""; break }; l=substr(l, p+3); hc=0; continue }+ p=index(l, "<!--"); if (p == 0) { o=o l; break }+ pre=substr(l, 1, p-1); if (o pre !~ /(^[ \t]*|>[ \t]*)$/) { o=o substr(l, 1, p+3); l=substr(l, p+4); continue }+ o=o pre; l=substr(l, p+4); hc=1 }+ if (hc) { nh++; ho[nh]=o; hr[nh]=$0; next }+ if (nh) { for (k=1; k<=nh; k++) print ho[k]; nh=0 }+ print o } END { flush() }' 2>/dev/null+ printf '\n%s\n' "$BLOB_END"; } >> "$FILELIST.impl" 2>/dev/null+ { tr '\n' '\0' < "$FILELIST" | xargs -0 grep -EIh -e '' 2>/dev/null+ printf '\n%s\n' "$BLOB_END"; } >> "$FILELIST.code" 2>/dev/null+ [ "$(tail -n 1 "$FILELIST.code" 2>/dev/null)" = "$BLOB_END" ] && [ "$(tail -n 1 "$FILELIST.impl" 2>/dev/null)" = "$BLOB_END" ] && CODE_OK=1+}+code_has() { # grep_has over every file read raw, as in 1.0.0. Falls back to grep_has without a buffer+ [ -s "$FILELIST" ] || return 1+ [ -n "${CODE_STATE:-}" ] || { build_code; CODE_STATE=1; }+ if [ "${CODE_OK:-0}" -eq 1 ]; then grep -Eqs -e "$1" "$FILELIST.code" 2>/dev/null; return; fi+ grep_has "$1"+}+impl_has() { # comment-stripped source and HTML only. a .strings, plist or json mention never proves an implementation+ [ -s "$FILELIST" ] || return 1+ [ -n "${CODE_STATE:-}" ] || { build_code; CODE_STATE=1; }+ if [ "${CODE_OK:-0}" -eq 1 ]; then grep -Eqs -e "$1" "$FILELIST.impl" 2>/dev/null; return; fi+ grep_has "$1"+}++# The app's own privacy manifest. A copy under Pods, Carthage, node_modules, SwiftPM or Flutter symlinks is the SDK's.+own_privacy_manifest() {+ find "$DIR" -mindepth 1 \( -type d \( -name node_modules -o -name Pods -o -name Carthage -o -name .build -o -name checkouts \+ -o -name SourcePackages -o -name .symlinks -o -name vendor -o -name .pub-cache -o -name .dart_tool -o -name DerivedData \+ -o -name build -o -name .git ${NESTED_PRUNE[@]+"${NESTED_PRUNE[@]}"} \) -prune \) -o -name 'PrivacyInfo.xcprivacy' -print 2>/dev/null \+ | grep . >/dev/null+}+# True only if a STRING LITERAL containing the regex appears in RELEASE-reachable source. For# Swift, `#if DEBUG` / `#if !RELEASE` debug-only regions are stripped first, so a URL only a debug# build compiles is not flagged. The string-literal requirement (the match must sit inside "...")@@ -273,9 +579,11 @@ hit_file() {}# Findings are held and printed by flush_findings, critical first (issue #842).-F_CRIT=(); F_HIGH=(); F_MED=()+F_CRIT=(); F_HIGH=(); F_MED=(); FOUND_IDS=""; POOL_PASS=0finding() { # severity id title fix [src|manifest regex]. The optional pair names the file that triggered it.local t w=""+ case "$FOUND_IDS" in *"|$1:$2|"*) [ "$POOL_PASS" -eq 1 ] && return 0 ;; esac+ FOUND_IDS="$FOUND_IDS|$1:$2|"[ -n "${5:-}" ] && w="$(hit_file "$5" "${6:-}")"case "$1" incritical) CRIT=$((CRIT+1)); t=" [CRITICAL] $2 $3" ;;@@ -311,9 +619,48 @@ find_tree() { # find "$DIR" <expr>, the whole tree as before, minus the nestedif [ "${#NESTED_PRUNE[@]}" -eq 0 ]; then find "$DIR" "$@" 2>/dev/nullelse find "$DIR" \( -type d \( -name '' "${NESTED_PRUNE[@]}" \) -prune \) -o "$@" 2>/dev/null; fi}-FILELIST="$(mktemp 2>/dev/null || echo /tmp/ascg.$$)"+FILELIST="$(mktemp 2>/dev/null)" || FILELIST=""+{ [ -n "$FILELIST" ] && : > "$FILELIST" 2>/dev/null; } || FILELIST="/tmp/ascg.$$"+# No scan buffer means no scan. Say so rather than end CLEAR on an empty file list.+if [ -z "$FILELIST" ] || ! : > "$FILELIST" 2>/dev/null; then+ NOTE="NOT CHECKED. The guard could not create its scan buffer in ${TMPDIR:-/tmp}, so nothing was scanned. Point TMPDIR at a writable folder and run it again."+ if [ -n "$STDIN_JSON" ]; then echo "app-store-compliance-guard. $NOTE" >&2; cursor_reply 0; exit 0; fi+ echo "$NOTE"; exit 1+fi+SCAN_ERROR=""# ----- the scan of one tree (issue #612). Runs once per app root, or once on the project root -----+detect_frameworks() { # sets the IS_<framework> flags for the tree under DIR+IS_FLUTTER=0; IS_RN=0; IS_IONIC=0+find_app 12 -name 'pubspec.yaml' | grep . >/dev/null && IS_FLUTTER=1+# Scan EVERY package.json within depth (not just the first), so a monorepo root's tooling+# package.json never shadows a real apps/mobile/package.json deeper in the tree.+while IFS= read -r pkg; do+ grep -qE '"react-native"|"expo"' "$pkg" 2>/dev/null && IS_RN=1+ grep -qE '"@capacitor/core"|"@capacitor/ios"|"@capacitor/android"|"@ionic/(angular|react|vue)"|"cordova-android"|"cordova-ios"' "$pkg" 2>/dev/null && IS_IONIC=1+done < <(find_app 12 -name 'package.json' | grep -vE '/(node_modules|ios/Pods)/')+find_app 12 -name 'capacitor.config.*' | grep . >/dev/null && IS_IONIC=1+# config.xml alone is ambiguous (Maven/NuGet/tooling also use that filename), so require the+# Cordova widget marker before it counts as a signal.+while IFS= read -r cfg; do+ grep -qE '<widget|xmlns:cdv' "$cfg" 2>/dev/null && IS_IONIC=1+done < <(find_app 12 -name 'config.xml')++# ----- Unity, .NET MAUI, Tauri mobile, Kotlin Multiplatform (issue #837) -----+IS_UNITY=0; IS_MAUI=0; IS_TAURI=0; IS_KMP=0+find_app 6 -name 'ProjectVersion.txt' -path '*/ProjectSettings/*' | grep . >/dev/null && IS_UNITY=1+while IFS= read -r cs; do+ grep -qE '<UseMaui>[[:space:]]*true|net[0-9.]+-(ios|android|maccatalyst)' "$cs" 2>/dev/null || continue+ IS_MAUI=1+ grep -qE 'net[0-9.]+-ios' "$cs" 2>/dev/null && IS_IOS=1+ grep -qE 'net[0-9.]+-android' "$cs" 2>/dev/null && IS_AND=1+done < <(find_app 6 -name '*.csproj')+find_app 6 -name 'tauri.conf.json' -o -name 'tauri.conf.json5' -o -name 'Tauri.toml' | grep . >/dev/null && IS_TAURI=1+while IFS= read -r g; do+ grep -qE 'kotlin\("multiplatform"\)|org\.jetbrains\.kotlin\.multiplatform|kotlinMultiplatform' "$g" 2>/dev/null && { IS_KMP=1; break; }+done < <(find_app 6 -name 'build.gradle.kts' -o -name 'build.gradle' -o -name 'libs.versions.toml')+}+scan_tree() {# ----- build a source file list, excluding vendor dirs -----@@ -336,8 +683,9 @@ find "$DIR" -mindepth 1 \-o -name '*.pbxproj' -o -name '*.entitlements' -o -name '*.html' -o -name '*.xcprivacy' \-o -name '*.cs' -o -name '*.rs' -o -name '*.csproj' -o -name '*.xaml' -o -name '*.toml' \\) -print 2>/dev/null \- > "$FILELIST"+ > "$FILELIST" || : 2>/dev/null >> "$FILELIST" || SCAN_ERROR="the file list could not be written to $FILELIST"build_blob+CODE_STATE=""# ----- platform detection -----# Every find below pipes into `grep .`, never `grep -q .`, for the reason in release_string_has:@@ -350,34 +698,11 @@ find_app 12 -name 'package.json' -o -name 'index.html' -o -name 'webpack.config.# ----- cross-platform framework detection -----# IS_IOS/IS_AND above still fire on the built artifact. This adds framework-specific checks.-IS_FLUTTER=0; IS_RN=0; IS_IONIC=0-find_app 12 -name 'pubspec.yaml' | grep . >/dev/null && IS_FLUTTER=1-# Scan EVERY package.json within depth (not just the first), so a monorepo root's tooling-# package.json never shadows a real apps/mobile/package.json deeper in the tree.-while IFS= read -r pkg; do- grep -qE '"react-native"|"expo"' "$pkg" 2>/dev/null && IS_RN=1- grep -qE '"@capacitor/core"|"@capacitor/ios"|"@capacitor/android"|"@ionic/(angular|react|vue)"|"cordova-android"|"cordova-ios"' "$pkg" 2>/dev/null && IS_IONIC=1-done < <(find_app 12 -name 'package.json' | grep -vE '/(node_modules|ios/Pods)/')-find_app 12 -name 'capacitor.config.*' | grep . >/dev/null && IS_IONIC=1-# config.xml alone is ambiguous (Maven/NuGet/tooling also use that filename), so require the-# Cordova widget marker before it counts as a signal.-while IFS= read -r cfg; do- grep -qE '<widget|xmlns:cdv' "$cfg" 2>/dev/null && IS_IONIC=1-done < <(find_app 12 -name 'config.xml')--# ----- Unity, .NET MAUI, Tauri mobile, Kotlin Multiplatform (issue #837) ------IS_UNITY=0; IS_MAUI=0; IS_TAURI=0; IS_KMP=0-find_app 6 -name 'ProjectVersion.txt' -path '*/ProjectSettings/*' | grep . >/dev/null && IS_UNITY=1-while IFS= read -r cs; do- grep -qE '<UseMaui>[[:space:]]*true|net[0-9.]+-(ios|android|maccatalyst)' "$cs" 2>/dev/null || continue- IS_MAUI=1- grep -qE 'net[0-9.]+-ios' "$cs" 2>/dev/null && IS_IOS=1- grep -qE 'net[0-9.]+-android' "$cs" 2>/dev/null && IS_AND=1-done < <(find_app 6 -name '*.csproj')-find_app 6 -name 'tauri.conf.json' -o -name 'tauri.conf.json5' -o -name 'Tauri.toml' | grep . >/dev/null && IS_TAURI=1-while IFS= read -r g; do- grep -qE 'kotlin\("multiplatform"\)|org\.jetbrains\.kotlin\.multiplatform|kotlinMultiplatform' "$g" 2>/dev/null && { IS_KMP=1; break; }-done < <(find_app 6 -name 'build.gradle.kts' -o -name 'build.gradle' -o -name 'libs.versions.toml')+detect_frameworks+# The project root and a native app split off it keep every framework the pooled tree showed, as when it was one scan (#656).+for fw in ${INHERIT_FW:-}; do+ case "$fw" in flutter) IS_FLUTTER=1 ;; rn) IS_RN=1 ;; ionic) IS_IONIC=1 ;; unity) IS_UNITY=1 ;; maui) IS_MAUI=1 ;; tauri) IS_TAURI=1 ;; kmp) IS_KMP=1 ;; esac+done# Unity holds no Xcode or Gradle project until export. The build target names the store, with none named both are scanned.if [ "$IS_UNITY" -eq 1 ]; thencase "$(printf '%s' "${CMD:-}" | grep -oiE -e '-buildtarget[[:space:]]+(ios|android)' | head -1 | tr '[:upper:]' '[:lower:]')" in@@ -408,7 +733,7 @@ fiecho "Frameworks. Flutter=$IS_FLUTTER ReactNative/Expo=$IS_RN Ionic/Capacitor/Cordova=$IS_IONIC Unity=$IS_UNITY MAUI=$IS_MAUI Tauri=$IS_TAURI KotlinMultiplatform=$IS_KMP"[ "$IS_UNITY" -eq 1 ] && echo "Unity. No Xcode or Gradle project exists before export, so Info.plist and the Gradle settings were not read. Scan the exported project too."[ "$IS_TAURI" -eq 1 ] && [ "$IS_IOS" -eq 0 ] && [ "$IS_AND" -eq 0 ] && echo "Tauri. No src-tauri/gen/apple or gen/android folder. Run cargo tauri ios init or cargo tauri android init before a mobile submit, then scan again."-[ "$CMD_TARGET_ANDROID_ONLY" -eq 1 ] && echo "Command targets Android only. Apple-only framework checks suppressed for this run."+[ "$CMD_TARGET_ANDROID_ONLY" -eq 1 ] && echo "Command targets Android only. Apple-only checks suppressed for this run."echo ""# ===== shared checks =====@@ -443,7 +768,7 @@ fi# iOS-only Apple requirement, gated on IS_IOS so an Android-only build is never blocked for it.if [ "$IS_FLUTTER" -eq 1 ]; thenif [ "$IOS_TARGET_ACTIVE" -eq 1 ] && grep_has 'permission_handler|image_picker|geolocator|device_info_plus|package_info_plus|shared_preferences|sqflite|firebase_'; then- if ! find_tree -name 'PrivacyInfo.xcprivacy' -print | grep . >/dev/null; then+ if ! own_privacy_manifest; thenfinding critical "FLUTTER-PRIVACY-MANIFEST-MISSING" "Flutter plugins that touch required-reason APIs but no PrivacyInfo.xcprivacy anywhere in the project" "Add an app-level PrivacyInfo.xcprivacy AND confirm each Flutter plugin ships its own (permission_handler, image_picker, and most first-party plugins added theirs from Flutter 3.19+). A missing plugin-level manifest is invisible to Apple's aggregator unless the app manifest also declares that plugin's reason codes. This check only runs against an iOS target."fifi@@ -461,12 +786,52 @@ if [ "$IS_RN" -eq 1 ] && [ "$IOS_TARGET_ACTIVE" -eq 1 ]; thenfifiif grep_has 'Firebase|@react-native-firebase|expo-file-system|expo-application|AsyncStorage|@react-native-async-storage'; then- if ! find_tree -name 'PrivacyInfo.xcprivacy' -print | grep . >/dev/null; then+ if ! own_privacy_manifest; thenfinding critical "RN-PRIVACY-MANIFEST-MISSING" "React Native native modules that touch required-reason APIs but no PrivacyInfo.xcprivacy anywhere" "Add an app-level PrivacyInfo.xcprivacy. Native modules bundled transitively via JS deps (analytics, storage, device-info libraries) each need their own manifest aggregated in the final IPA; this is easy to miss because the dependency is JS-side." src 'Firebase|@react-native-firebase|expo-file-system|expo-application|AsyncStorage|@react-native-async-storage'fififi+# ===== Managed Expo app config, read when no ios or android folder exists yet =====+# EAS builds the native folders in the cloud, so the config is all there is to read. Native code stays NOT CHECKED.+if [ "$IS_RN" -eq 1 ] && [ "$NEEDS_NATIVE" -eq 1 ]; then+ EXPO_CFG=()+ for f in "$DIR/app.json" "$DIR/app.config.js" "$DIR/app.config.ts" "$DIR/app.config.mjs" "$DIR/app.config.cjs"; do+ if [ -f "$f" ]; then EXPO_CFG+=("$f"); fi+ done+ if [ "${#EXPO_CFG[@]}" -gt 0 ]; then+ EXPO_READ=1+ echo "Expo config. No ios or android folder, so only the app config was read for store checks."+ ex_cfg() { grep -Eqs -e "$1" "${EXPO_CFG[@]}"; }+ ex_dep() { grep -Eqs -e "$1" "$DIR/package.json" "${EXPO_CFG[@]}"; }+ if [ "$CMD_TARGET_ANDROID_ONLY" -eq 0 ]; then+ if ex_dep '"(expo-camera|expo-image-picker|expo-barcode-scanner|react-native-vision-camera)"' && ! ex_cfg 'NSCameraUsageDescription|cameraPermission'; then+ finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Camera module in the Expo app with no camera purpose string in the app config" "Set ios.infoPlist.NSCameraUsageDescription, or the plugin cameraPermission option, to a specific reason. The generic plugin default is a common 5.1.1 rejection."+ fi+ if ex_dep '"(expo-location|react-native-geolocation-service|@react-native-community/geolocation)"' && ! ex_cfg 'NSLocation[A-Za-z]*UsageDescription|location(WhenInUse|AlwaysAndWhenInUse|Always)Permission'; then+ finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Location module in the Expo app with no location purpose string in the app config" "Set ios.infoPlist.NSLocationWhenInUseUsageDescription, or the plugin locationWhenInUsePermission option, to a specific reason."+ fi+ if ex_dep '"(@react-native-async-storage/async-storage|expo-file-system|expo-application|@react-native-firebase/[a-z-]+)"' && ! ex_cfg 'privacyManifests'; then+ finding medium "RN-PRIVACY-MANIFEST-MISSING" "Required-reason modules installed but the Expo app config sets no ios.privacyManifests" "Declare the accessed API categories and reasons under ios.privacyManifests, so the manifest EAS generates carries them."+ fi+ fi+ if [ "$CMD_TARGET_IOS_ONLY" -eq 0 ]; then+ # Only the permissions array counts. blockedPermissions removes a permission, it never adds one.+ EX_PERMS="$(cat "${EXPO_CFG[@]}" 2>/dev/null | tr -d '\n\r' | grep -oE "(^|[^A-Za-z])[\"']?permissions[\"']?[[:space:]]*:[[:space:]]*\\[[^]]*\\]")"+ # A JS or TS config may quote a key either way, or not at all.+ if printf '%s' "$EX_PERMS" | grep -q 'ACCESS_BACKGROUND_LOCATION' || ex_cfg "isAndroidBackgroundLocationEnabled[\"']?[[:space:]]*:[[:space:]]*true"; then+ finding critical "GOOGLE-PERM-BACKGROUND-LOCATION" "Background location requested in the Expo app config" "Justify with a core feature and prominent disclosure, or use foreground location."+ fi+ if printf '%s' "$EX_PERMS" | grep -qE 'READ_SMS|SEND_SMS|RECEIVE_SMS|READ_CALL_LOG|WRITE_CALL_LOG'; then+ finding critical "GOOGLE-PERM-SMS-CALLLOG" "SMS or Call Log permission in the Expo app config" "Use the permissions declaration for an approved core use case, or drop it."+ fi+ if printf '%s' "$EX_PERMS" | grep -q 'MANAGE_EXTERNAL_STORAGE'; then+ finding critical "GOOGLE-PERM-ALL-FILES" "All files access in the Expo app config" "Use scoped storage. Request all files access only for a qualifying use case."+ fi+ fi+ fi+fi+# ===== Ionic / Capacitor / Cordova checks =====# All three are Apple-side (4.2, UIWebView, iOS privacy manifest), IS_IOS-gated as above.if [ "$IS_IONIC" -eq 1 ] && [ "$IOS_TARGET_ACTIVE" -eq 1 ]; then@@ -479,33 +844,34 @@ if [ "$IS_IONIC" -eq 1 ] && [ "$IOS_TARGET_ACTIVE" -eq 1 ]; thenfinding critical "IONIC-UIWEBVIEW-DEPRECATED" "Deprecated UIWebView symbol referenced (directly or via a stale plugin)" "Apple auto-rejects (ITMS-90809) any binary statically linking UIWebView. Update every Capacitor/Cordova plugin to a version using WKWebView; a stale plugin can pull this in even when app code never references it." src 'UIWebView'fiif grep_has '@capacitor/|Capacitor\.'; then- if ! find_tree -name 'PrivacyInfo.xcprivacy' -print | grep . >/dev/null; then+ if ! own_privacy_manifest; thenfinding high "IONIC-PRIVACY-MANIFEST-MISSING" "Capacitor/Cordova plugins present but no PrivacyInfo.xcprivacy" "Capacitor plugin manifest support is less standardized than Flutter's; verify each plugin wrapping a native SDK (camera, geolocation, ads) ships PrivacyInfo.xcprivacy, and add the app-level one." src '@capacitor/|Capacitor\.'fififi# ===== iOS checks =====-if [ "$IS_IOS" -eq 1 ]; then+# Gated like the framework checks, so an Android-only command never meets an Apple finding.+if [ "$IOS_TARGET_ACTIVE" -eq 1 ]; thenif release_string_has 'localhost|127\.0\.0\.1|staging\.[a-z]|ngrok\.io'; thenfinding critical "APPLE-2.1-STAGING-BACKEND" "A release-build string points at localhost or a staging host" "Point the release build at the live production backend. A localhost/staging URL inside #if DEBUG or a comment is fine. this only flags strings the release build actually compiles." src 'localhost|127\.0\.0\.1|staging\.[a-z]|ngrok\.io'fiif grep_has 'signIn|logIn|LoginView|OAuth|FirebaseAuth|createAccount|signUp'; then- if ! grep_has 'deleteAccount|delete_account|account deletion|deleteUser'; then+ if ! impl_has 'deleteAccount|delete_account|account deletion|deleteUser'; thenfinding critical "APPLE-5.1.1-NO-ACCOUNT-DELETION" "Account creation found but no in app account deletion" "Add an in app account deletion flow (Apple 5.1.1(v))." src 'signIn|logIn|LoginView|OAuth|FirebaseAuth|createAccount|signUp'fifi- if grep_has 'AVCaptureDevice|UIImagePickerController'; then- grep_has 'NSCameraUsageDescription' || finding critical "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Camera used without NSCameraUsageDescription" "Add NSCameraUsageDescription with a specific reason." src 'AVCaptureDevice|UIImagePickerController'+ if code_has 'AVCaptureDevice|UIImagePickerController'; then+ config_has 'NSCameraUsageDescription' || finding critical "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Camera used without NSCameraUsageDescription" "Add NSCameraUsageDescription with a specific reason." src 'AVCaptureDevice|UIImagePickerController'fi- if grep_has 'CLLocationManager'; then- grep_has 'NSLocation.*UsageDescription' || finding critical "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Location used without a location usage description" "Add the matching NSLocation usage description with a specific reason." src 'CLLocationManager'+ if code_has 'CLLocationManager'; then+ config_has 'NSLocation.*UsageDescription' || finding critical "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Location used without a location usage description" "Add the matching NSLocation usage description with a specific reason." src 'CLLocationManager'fi- if grep_has 'PHPhotoLibrary|PHPicker'; then- grep_has 'NSPhotoLibrary.*UsageDescription' || finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Photos used without a photo library usage description" "Add NSPhotoLibraryUsageDescription with a specific reason." src 'PHPhotoLibrary|PHPicker'+ if code_has 'PHPhotoLibrary'; then+ config_has 'NSPhotoLibrary.*UsageDescription' || finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Photos used without a photo library usage description" "Add NSPhotoLibraryUsageDescription with a specific reason." src 'PHPhotoLibrary'fi- if grep_has 'CNContactStore'; then- grep_has 'NSContactsUsageDescription' || finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Contacts used without NSContactsUsageDescription" "Add NSContactsUsageDescription with a specific reason." src 'CNContactStore'+ if code_has 'CNContactStore'; then+ config_has 'NSContactsUsageDescription' || finding high "APPLE-5.1.1-MISSING-USAGE-DESCRIPTION" "Contacts used without NSContactsUsageDescription" "Add NSContactsUsageDescription with a specific reason." src 'CNContactStore'fiif grep_has 'FacebookLogin|GoogleSignIn|GIDSignIn|LoginWithFacebook'; thengrep_has 'SignInWithApple|ASAuthorizationAppleIDProvider' || finding high "APPLE-4.8-SOCIAL-LOGIN-ONLY" "Third party social login without Sign in with Apple" "Add Sign in with Apple or an equal privacy preserving login (Apple 4.8)." src 'FacebookLogin|GoogleSignIn|GIDSignIn|LoginWithFacebook'@@ -534,7 +900,10 @@ if [ "$IS_IOS" -eq 1 ]; then# "Branch", which collide with ordinary English ("Adjust times", a git branch) and false-flag a# tracking SDK that is not present.if grep_has 'AppsFlyerLib|import AppsFlyer|AdjustConfig|AdjustEvent|import Adjust[^A-Za-z]|BranchEvent|BranchUniversalObject|import Branch[^A-Za-z]|FBSDKCoreKit|FBSDKLogin|ASIdentifierManager|advertisingIdentifier'; then- grep_has 'ATTrackingManager|NSUserTrackingUsageDescription' || finding high "APPLE-5.1.2-MISSING-ATT" "Tracking SDK without App Tracking Transparency" "Call the ATT prompt and add NSUserTrackingUsageDescription (Apple 5.1.2)." src 'AppsFlyerLib|import AppsFlyer|AdjustConfig|AdjustEvent|import Adjust[^A-Za-z]|BranchEvent|BranchUniversalObject|import Branch[^A-Za-z]|FBSDKCoreKit|FBSDKLogin|ASIdentifierManager|advertisingIdentifier'+ ATT_MISS=""+ config_has 'NSUserTrackingUsageDescription|userTrackingPermission' || ATT_MISS="NSUserTrackingUsageDescription in Info.plist or the build settings"+ impl_has 'requestTrackingAuthorization|requestTrackingPermission' || ATT_MISS="${ATT_MISS:+$ATT_MISS and }the ATTrackingManager.requestTrackingAuthorization call"+ [ -z "$ATT_MISS" ] || finding high "APPLE-5.1.2-MISSING-ATT" "Tracking SDK without App Tracking Transparency, missing $ATT_MISS" "Call the ATT prompt and add NSUserTrackingUsageDescription, both are required (Apple 5.1.2)." src 'AppsFlyerLib|import AppsFlyer|AdjustConfig|AdjustEvent|import Adjust[^A-Za-z]|BranchEvent|BranchUniversalObject|import Branch[^A-Za-z]|FBSDKCoreKit|FBSDKLogin|ASIdentifierManager|advertisingIdentifier'fiif grep_has 'Stripe|PayPalCheckout|braintree|razorpay'; thengrep_has "StoreKit|SKProduct|Product\.purchase|$XPLAT_IAP" || finding critical "APPLE-3.1.1-EXTERNAL-PAYMENT" "External payment SDK without StoreKit" "Route digital goods through in app purchase unless the app is a documented exempt category (Apple 3.1.1)." src 'Stripe|PayPalCheckout|braintree|razorpay'@@ -557,7 +926,7 @@ if [ "$IS_IOS" -eq 1 ]; thenfi# Privacy manifest, the top modern Apple upload rejection since 2024if grep_has 'Firebase|Alamofire|UserDefaults|systemUptime|FileManager\.default|ProcessInfo'; then- if ! find_tree -name 'PrivacyInfo.xcprivacy' -print | grep . >/dev/null; then+ if ! own_privacy_manifest; thenfinding critical "APPLE-PRIVACY-MANIFEST-MISSING" "Required reason APIs or SDKs present but no PrivacyInfo.xcprivacy" "Add a privacy manifest with approved reason codes and tracking domains, and confirm each SDK ships its signed manifest." src 'Firebase|Alamofire|UserDefaults|systemUptime|FileManager\.default|ProcessInfo'fifi@@ -568,11 +937,14 @@ if [ "$IS_IOS" -eq 1 ]; thenMANIFEST_VALIDATOR=""for candidate in \"$(dirname "$0")/../../scripts/validate-privacy-manifest.py" \- "${HOME:-}/.claude/skills/app-store-compliance/scripts/validate-privacy-manifest.py"; do+ "$(dirname "$0")/../skills/app-store-compliance/scripts/validate-privacy-manifest.py" \+ "${HOME:-}/.claude/skills/app-store-compliance/scripts/validate-privacy-manifest.py" \+ "${HOME:-}/.agents/skills/app-store-compliance/scripts/validate-privacy-manifest.py"; do[ -f "$candidate" ] && { MANIFEST_VALIDATOR="$candidate"; break; }doneif [ -n "$MANIFEST_VALIDATOR" ] && command -v python3 >/dev/null 2>&1; then# Same exclusions as the source file list. A pod's manifest is the vendor's job, a Tests fixture never ships.+ : > "$FILELIST.manifest" 2>/dev/null || SCAN_ERROR="the privacy manifest results could not be written to $FILELIST.manifest"find "$DIR" -mindepth 1 \\( -type d \( -name node_modules -o -name Pods -o -name .git -o -name build -o \( -name dist -not -path '*/src/dist' \) \-o -name DerivedData -o -name vendor -o -name .dart_tool -o -name Carthage \@@ -594,8 +966,11 @@ if [ "$IS_IOS" -eq 1 ]; thenfinding medium "APPLE-MANIFEST-VALIDATOR-UNAVAILABLE" "Privacy manifests present but python3 or scripts/validate-privacy-manifest.py is missing, so their internals were not validated" "Install python3 and keep scripts/validate-privacy-manifest.py next to the guard, or run plutil -lint on each manifest by hand."fi[ "$IS_UNITY" -eq 1 ] || grep_has 'ITSAppUsesNonExemptEncryption' || finding high "APPLE-EXPORT-COMPLIANCE-MISSING" "ITSAppUsesNonExemptEncryption not set" "Set it in Info.plist or the build stalls in Missing Compliance and never reaches review."- if grep_has 'SKProduct|Product\.purchase|StoreKit'; then- grep_has 'restorePurchases|restoreCompletedTransactions|AppStore\.sync|Restore Purchases' || finding high "APPLE-RESTORE-PURCHASES-MISSING" "StoreKit purchases without a Restore Purchases control" "Add a visible Restore Purchases control. Required for non consumables." src 'SKProduct|Product\.purchase|StoreKit'+ # Native StoreKit keeps the original restore list. A plugin's own restore call only counts for a plugin app.+ RESTORE_RE='restorePurchases|restoreCompletedTransactions|AppStore\.sync|Restore Purchases'+ grep_has 'SKProduct|Product\.purchase|StoreKit' || RESTORE_RE="$RESTORE_RE|RestorePurchases|restoreTransactions|RestoreTransactions|getAvailablePurchases|queryPastPurchases"+ if grep_has "SKProduct|Product\\.purchase|StoreKit|$XPLAT_IAP"; then+ grep_has "$RESTORE_RE" || finding high "APPLE-RESTORE-PURCHASES-MISSING" "In-app purchases without a Restore Purchases control" "Add a visible Restore Purchases control. Required for non consumables." src "SKProduct|Product\\.purchase|StoreKit|$XPLAT_IAP"fiif grep_has 'deleteAccount|delete account'; thengrep_has 'mailto:|deactivate' && finding high "APPLE-ACCOUNT-DELETION-WEAK" "Account removal may be deactivate or mailto only" "Provide genuine in app deletion of the account and its data, not a deactivate or external form." src 'mailto:|deactivate'@@ -894,9 +1269,37 @@ dir_has_app_marker() { # $1 dir. 0 when an app marker sits at its top level[ -f "$t/package.json" ] && grep -qE '"@capacitor/core"|"cordova-(ios|android)"' "$t/package.json" 2>/dev/null && return 0return 1}+# Issue #656. Under a root framework app, a bare native project with its own Info.plist or AndroidManifest.xml is a+# second app, unless a root build file (settings.gradle, Podfile, a workspace) names its path. A native root is unchanged.+bare_native_apart() { # $1 candidate dir below $DIR+ local rel="${1#"${DIR%/}"/}" f+ case "$rel" in ios|ios/*|android|android/*) return 1 ;; esac+ # A folder named exactly demo, example, sample, or playground (or plural) holds a repo demo, so it stays in the root scan.+ printf '%s' "$rel" | tr '[:upper:]' '[:lower:]' | tr '/' '\n' | grep -qxE 'demos?|examples?|samples?|playgrounds?' && return 1+ find "$1" -maxdepth 4 \( -type d \( -name Pods -o -name node_modules -o -name build \) -prune \) \+ -o \( -name 'Info.plist' -o -name 'AndroidManifest.xml' \) -print 2>/dev/null | grep . >/dev/null || return 1+ # Only a shippable app splits off. a library module or a local native module stays with the app that uses it.+ find "$1" -maxdepth 5 \( -type d \( -name Pods -o -name node_modules -o -name build \) -prune \) -o -path '*.xcodeproj/project.pbxproj' -print 2>/dev/null \+ | while IFS= read -r f; do grep -q 'com\.apple\.product-type\.application' "$f" 2>/dev/null || ! grep -q 'com\.apple\.product-type\.' "$f" 2>/dev/null && echo "$f"; done | grep . >/dev/null \+ || find "$1" -maxdepth 4 \( -type d \( -name node_modules -o -name build \) -prune \) -o \( -name 'build.gradle' -o -name 'build.gradle.kts' \) -print 2>/dev/null \+ | while IFS= read -r f; do grep -lE 'com\.android\.application|android\.application' "$f" 2>/dev/null; done | grep . >/dev/null || return 1+ # A native host that embeds the root framework (brownfield) shares its dependencies, so it stays in the root scan.+ grep -rlsE 'RCTBridge|RCTRootView|RCTSurfaceHostingProxyRootView|RCTSurfaceHostingView|RCTReactNativeFactory|RCTAppDelegate|import React$|import React_|ReactActivity|ReactNativeHost|ReactApplication|ReactInstanceManager|DefaultReactNativeHost|RCTDefaultReactNativeFactoryDelegate|ReactNativeDelegate|ExpoAppDelegate|ExpoReactNativeFactory|React-Core|react-native|CodePush|ExpoModulesCore|EXAppDelegate|FlutterEngine|FlutterViewController|Flutter/Flutter\.h|<React/|import Capacitor|Capacitor/Capacitor\.h|CAPBridgeViewController|Cordova/|import Cordova|CDVViewController|CDVPlugin|CDVAppDelegate|import Flutter' "$1" \+ --include='*.swift' --include='*.m' --include='*.mm' --include='*.h' --include='*.kt' --include='*.java' --include='*.gradle' --include='*.kts' --include='Podfile' --include='*.pbxproj' \+ --exclude-dir=Pods --exclude-dir=node_modules --exclude-dir=build 2>/dev/null | grep . >/dev/null && return 1+ # The root keeps the scan for a platform it has no folder of, or its checks for that platform would vanish.+ native_dir_has_project "$DIR/ios" || ! find "$1" -maxdepth 4 -name 'Info.plist' -not -path '*/Pods/*' 2>/dev/null | grep . >/dev/null || return 1+ native_dir_has_project "$DIR/android" || ! find "$1" -maxdepth 4 -name 'AndroidManifest.xml' -not -path '*/build/*' 2>/dev/null | grep . >/dev/null || return 1+ for f in "$DIR"/settings.gradle "$DIR"/settings.gradle.kts "$DIR"/android/settings.gradle "$DIR"/android/settings.gradle.kts \+ "$DIR"/Podfile "$DIR"/ios/Podfile "$DIR"/*.xcworkspace/contents.xcworkspacedata "$DIR"/ios/*.xcworkspace/contents.xcworkspacedata; do+ [ -f "$f" ] && grep -qF -e "$rel" "$f" 2>/dev/null && return 1+ done+ return 0+}app_roots() { # prints the roots, one per line, only when two or more distinct apps exist. the project root itself may be one of them- local m d r k t x keep=() seen=() atroot=0 ROOT_REAL+ local m d r k t x keep=() seen=() atroot=0 rootfw=0 ROOT_REALROOT_REAL="$(cd "$DIR" 2>/dev/null && pwd -P)" || ROOT_REAL="${DIR%/}"+ has_framework_marker "$DIR" && rootfw=1{find_app 12 -name 'app.json' -o -name 'app.config.js' -o -name 'app.config.ts' -o -name 'app.config.mjs' -o -name 'app.config.cjs' \-o -name 'pubspec.yaml' -o -name 'capacitor.config.*' -o -name 'settings.gradle' -o -name 'settings.gradle.kts' \@@ -930,7 +1333,7 @@ app_roots() { # prints the roots, one per line, only when two or more distinctseen+=("$t")elsefor k in ${keep[@]+"${keep[@]}"}; do case "$r/" in "$k"/*) continue 2 ;; esac; done- [ "$atroot" -eq 1 ] && ! has_framework_marker "$r" && continue+ [ "$atroot" -eq 1 ] && ! has_framework_marker "$r" && ! { [ "$rootfw" -eq 1 ] && bare_native_apart "$r"; } && continuefikeep+=("$r")done@@ -949,23 +1352,32 @@ app_roots() { # prints the roots, one per line, only when two or more distinct# ----- report routing (issue #610). Hook mode buffers the report. A block goes to stderr, the only# stream Claude Code shows on exit 2. A pass stays on stdout. Standalone mode prints straight to stdout.emit_report() { # $1 is the exit code about to be returned- [ -n "$REPORT" ] || return 0- exec 1>&3 3>&-- if [ "$1" -eq 2 ]; then cat "$REPORT" >&2; else cat "$REPORT"; fi- rm -f "$REPORT" 2>/dev/null; REPORT=""+ if [ -n "$REPORT" ]; then+ exec 1>&3 3>&-+ CURSOR_IDS="$(grep -oE '\[CRITICAL\] [A-Za-z0-9._-]+' "$REPORT" 2>/dev/null | sed 's/^\[CRITICAL\] //' | sort -u | tr '\n' ' ')"+ if [ "$1" -eq 2 ] || [ "$IS_CURSOR" -eq 1 ]; then cat "$REPORT" >&2; else cat "$REPORT"; fi+ rm -f "$REPORT" 2>/dev/null; REPORT=""+ elif [ "$CURSOR_FD" -eq 1 ]; then+ exec 1>&3 3>&-; CURSOR_FD=0+ fi+ cursor_reply "$1"}# A hook timeout sends TERM. Flush what was buffered to stderr so the partial report is not lost.trap 'emit_report 2; exit 143' INT TERM HUPif [ -n "$STDIN_JSON" ]; thenREPORT="$(mktemp 2>/dev/null)" || REPORT=""+ # An unusable mktemp falls back to /tmp, as the scan buffer does, so the report still reaches stderr.+ { [ -n "$REPORT" ] && : >"$REPORT" 2>/dev/null; } || REPORT="/tmp/ascg-report.$$"if [ -n "$REPORT" ] && : >"$REPORT" 2>/dev/null; then exec 3>&1; exec >"$REPORT"; else REPORT=""; REPORT_DEGRADED=1; fi+ # Unbuffered, Cursor still needs a clean stdout, so the live report goes to stderr instead.+ if [ -z "$REPORT" ] && [ "$IS_CURSOR" -eq 1 ]; then exec 3>&1; exec 1>&2; CURSOR_FD=1; fifi# The deadline list prints after the findings, and only for the stores this project ships to (issue #842).print_deadlines() {local hd py="" c plats=""hd="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"- for c in "$hd/../../scripts/deadline-checker.py" "$hd/../skills/app-store-compliance/scripts/deadline-checker.py"; do+ for c in "$hd/../../scripts/deadline-checker.py" "$hd/../skills/app-store-compliance/scripts/deadline-checker.py" "${HOME:-}/.agents/skills/app-store-compliance/scripts/deadline-checker.py"; doif [ -f "$c" ]; then py="$c"; break; fidone[ -n "$py" ] || return 0@@ -983,7 +1395,35 @@ if [ -n "$ROOTS" ]; thenPROJECT_ROOT="${DIR%/}"echo "Apps. $(printf '%s\n' "$ROOTS" | grep -c .) app roots, each scanned on its own"echo ""+ POOL_FW=""; SPLIT_NATIVE=""+ if printf '%s\n' "$ROOTS" | sed 's:/$::' | grep -qxF "$PROJECT_ROOT"; then+ NESTED_PRUNE=()+ while IFS= read -r OTHER; do+ [ -n "$OTHER" ] && [ "${OTHER%/}" != "$PROJECT_ROOT" ] || continue+ if ! has_framework_marker "$OTHER" && (DIR="$PROJECT_ROOT"; bare_native_apart "$OTHER"); then+ SPLIT_NATIVE="$SPLIT_NATIVE${OTHER%/}+"+ else+ NESTED_PRUNE+=(-o -path "$(printf '%s' "$OTHER" | sed 's/[][*?\\]/\\&/g')")+ fi+ done <<EOF3+$ROOTS+EOF3+ POOL_PRUNE=(${NESTED_PRUNE[@]+"${NESTED_PRUNE[@]}"})+ if [ -n "$SPLIT_NATIVE" ]; then+ SAVE_DIR="$DIR"; SAVE_IOS="${IS_IOS:-0}"; SAVE_AND="${IS_AND:-0}"; DIR="$PROJECT_ROOT"; detect_frameworks; DIR="$SAVE_DIR"; IS_IOS="$SAVE_IOS"; IS_AND="$SAVE_AND"+ [ "$IS_FLUTTER" -eq 1 ] && POOL_FW="$POOL_FW flutter"; [ "$IS_RN" -eq 1 ] && POOL_FW="$POOL_FW rn"+ [ "$IS_IONIC" -eq 1 ] && POOL_FW="$POOL_FW ionic"; [ "$IS_UNITY" -eq 1 ] && POOL_FW="$POOL_FW unity"+ [ "$IS_MAUI" -eq 1 ] && POOL_FW="$POOL_FW maui"; [ "$IS_TAURI" -eq 1 ] && POOL_FW="$POOL_FW tauri"+ [ "$IS_KMP" -eq 1 ] && POOL_FW="$POOL_FW kmp"+ fi+ fiwhile IFS= read -r ROOT; do+ [ -n "$ROOT" ] || continue+ INHERIT_FW=""+ if [ -n "$POOL_FW" ] && { [ "${ROOT%/}" = "$PROJECT_ROOT" ] || printf '%s' "$SPLIT_NATIVE" | grep -qxF "${ROOT%/}"; }; then+ INHERIT_FW="$POOL_FW"+ fiNESTED_PRUNE=()if [ "${ROOT%/}" = "$PROJECT_ROOT" ]; thenwhile IFS= read -r OTHER; do [ "${OTHER%/}" != "$PROJECT_ROOT" ] && NESTED_PRUNE+=(-o -path "$(printf '%s' "$OTHER" | sed 's/[][*?\\]/\\&/g')"); done <<EOF2@@ -1005,6 +1445,17 @@ EOF2done <<EOF$ROOTSEOF+ # A split native app and the root it left are also scanned as one, as in 1.0.0, so evidence that spans+ # both (a shared source file and the split app) still counts. Only findings not listed above are added.+ if [ -n "$SPLIT_NATIVE" ]; then+ NESTED_PRUNE=(${POOL_PRUNE[@]+"${POOL_PRUNE[@]}"}); INHERIT_FW=""; DIR="$PROJECT_ROOT"; POOL_PASS=1+ scan_tree >/dev/null+ POOL_PASS=0+ if [ "$(( ${#F_CRIT[@]} + ${#F_HIGH[@]} + ${#F_MED[@]} ))" -gt 0 ]; then+ echo "App. $PROJECT_ROOT with its split native apps, scanned as one as in 1.0.0"+ flush_findings+ fi+ fielsescan_treeflush_findings@@ -1033,6 +1484,13 @@ if [ "$CRIT" -gt 0 ]; then[ "${REPORT_DEGRADED:-0}" = "1" ] && echo "BLOCKED. $CRIT critical rejection risk(s). Full report on stdout (no temp file available for buffering)." >&2emit_report 2; exit 2fi+# A scan buffer that failed mid-run leaves the result unknown, never CLEAR.+if [ -n "$SCAN_ERROR" ]; then+ NOTE="NOT CHECKED. The scan could not run because $SCAN_ERROR."+ echo ""; echo "$NOTE"+ if [ -n "$STDIN_JSON" ]; then emit_report 0; echo "$NOTE" >&2; exit 0; fi+ exit 1+fi# A verdict line every time. Exit 0 with nothing scanned reads as a pass, so it is named and, run by hand, exits 1.if [ -n "$UNCHECKED" ] || { [ "$ANY_NATIVE" -eq 0 ] && { [ "$ANY_WEB" -eq 0 ] || [ "$ANY_NEEDS_NATIVE" -eq 1 ]; }; }; thenNOTE="NOT CHECKED. No iOS or Android project was found in $DIR, so the store checks did not run."@@ -1040,6 +1498,7 @@ if [ -n "$UNCHECKED" ] || { [ "$ANY_NATIVE" -eq 0 ] && { [ "$ANY_WEB" -eq 0 ] ||NOTE="NOT CHECKED. No ios or android folder in $UNCHECKED, so the store checks did not run there. The other app roots had 0 critical risks."NEXT="Next. Create the native project in each folder named above (npx expo prebuild, npx cap add, flutter create, or cargo tauri ios init), then run the guard again."elif [ "$ANY_RN" -eq 1 ]; then NEXT="Next. This looks like an Expo or React Native app with no ios or android folder. Run npx expo prebuild, then run the guard again."+ [ "$EXPO_READ" -eq 1 ] && NOTE="NOT CHECKED. No ios or android folder in $DIR, so the native code checks did not run. Only the Expo app config was read."elif [ "$ANY_NEEDS_NATIVE" -eq 1 ]; then NEXT="Next. This app has no ios or android folder yet. Run $NATIVE_HINT, then run the guard again."else NEXT="Next. Point the guard at the folder that holds your Xcode project or your Android app folder."; fiecho ""; echo "$NOTE"; echo "$NEXT"diff --git a/agent-os/skill/SKILL.md b/agent-os/skill/SKILL.mdindex 8bed630..4bb8ce9 100644--- a/agent-os/skill/SKILL.md+++ b/agent-os/skill/SKILL.md@@ -31,7 +31,7 @@ The compliance reference lives in the `app-store-compliance` repo. The key files- `docs/PLATFORM-MECHANICS-2026.md` the platform-mechanics and newer-policy hard rules with dated sources. macOS notarization, Guideline 4.2 and 4.3 with the June 2026 saturation tightening, reader apps, France ANSSI encryption, visionOS and watchOS and tvOS specifics, Android developer verification, Foreground Service types, Play Integrity, Play Billing v8, target API, Health Connect, and the cross-cutting CSAM, UGC, accessibility, sanctions, and PCI items. Load it for any app whose type touches these.- `references/` the structured, AI loadable tree. Load `references/guidelines/by-app-type/<type>.md` for the app at hand and the relevant `references/rules/<category>.md` files for full context before judging.- `templates/REVIEW-NOTES-TEMPLATE.md` the review notes template to hand the user for a new submission.-- `agent-os/hooks/app-store-compliance-guard.sh` the automated scanner.+- `app-store-compliance-guard.sh` the automated scanner. The install puts it in your tool's hooks folder, listed in Step 2.For the strongest audit, also run the metadata layer. A large share of rejections live in the listing text, not the source.@@ -39,9 +39,13 @@ For the strongest audit, also run the metadata layer. A large share of rejectionbash scripts/pull-metadata.sh apple # pulls the live listing into ./metadata via the asc CLIpython3 scripts/metadata-audit.py ./metadata # audits name, subtitle, keywords, description, URLspython3 scripts/metadata-audit.py ./metadata --propose # writes suggested fixes, source copy untouched+python3 scripts/metadata-audit.py ./metadata/android --platform google # Google Play limits and rules+python3 scripts/release-audit.py /path/to/app --metadata ./metadata # full gate, exit 0 clear, 2 blocked, 3 incomplete```-The metadata audit checks character limits, other platform mentions, future functionality, negative Apple sentiment, profanity, ranking and price claims, keyword formatting, missing privacy policy and subscription terms, China storefront AI references, and broken URLs. Run it, then re run it after applying fixes. That is the detect, propose, re validate loop.+The metadata audit checks character limits, other platform mentions, future functionality, negative Apple sentiment, profanity, ranking and price claims, keyword formatting, missing privacy policy and subscription terms, China storefront AI references, and malformed URLs (pass `--check-urls` to also test that each URL loads). It audits every locale folder on its own, filled from a fastlane `default/` folder and parent folders like fastlane does, and names the locale in each finding. It flags a URL that is not a real http or https address, an Apple listing with no support URL, a Google listing with no contact email, and a subscription with no real Terms or EULA link. Run it, then re run it after applying fixes. That is the detect, propose, re validate loop.++The release audit blocks on any critical or high finding with exit 2. It exits 3 when a scan failed or the listing was not audited, so pass `--metadata` with your pulled listing.For monitoring evolving developer requirements, also run the Apple Developer requirements monitor. This tracks 25 key categories against active developer news/announcements and maps updates directly to repository impact:@@ -59,12 +63,30 @@ The monitor determines repository impact, identifies affected files, generates m### Step 2. Run the automated scan-Run the guard against the project root.+Run the guard against the project root. Use the copy the install put in your tool's hooks folder.++| Tool | Guard |+|---|---|+| Claude Code | `~/.claude/hooks/app-store-compliance-guard.sh` |+| Codex CLI | `~/.codex/hooks/app-store-compliance-guard.sh` |+| Gemini CLI | `~/.gemini/hooks/app-store-compliance-guard.sh` |+| OpenCode | `~/.config/opencode/hooks/app-store-compliance-guard.sh` |+| Cursor | `~/.cursor/hooks/app-store-compliance-guard.sh` |+| Copilot CLI | `~/.copilot/hooks/app-store-compliance-guard.sh`, or under `$COPILOT_HOME` when set |+| Grok | `~/.grok/hooks/app-store-compliance-guard.sh` |+| Qwen Code | `~/.qwen/hooks/app-store-compliance-guard.sh`, or under `$QWEN_HOME` when set |+| Kimi Code | `~/.kimi-code/hooks/app-store-compliance-guard.sh`, or under `$KIMI_CODE_HOME` when set |+| Factory Droid | `~/.factory/hooks/app-store-compliance-guard.sh` |+| Auggie | `~/.augment/hooks/app-store-compliance-guard.sh` |+| Windsurf | `~/.codeium/windsurf/hooks/app-store-compliance-guard.sh` |+| From a checkout | `~/repositories/app-store-compliance/agent-os/hooks/app-store-compliance-guard.sh` |```-bash <repo>/agent-os/hooks/app-store-compliance-guard.sh /path/to/app/project+bash <guard path from the table> "/path/to/app/project"```+The `scripts/` paths in this skill are relative to this skill's own folder.+It detects iOS and Android, scans for the rejection patterns, and prints findings ranked critical, high, medium. It exits 2 when a critical risk is present.### Step 3. Run the human checks the scanner cannot seediff --git a/data/regulatory-deadlines.json b/data/regulatory-deadlines.jsonindex 4691ea4..ff4b900 100644--- a/data/regulatory-deadlines.json+++ b/data/regulatory-deadlines.json@@ -1,5 +1,5 @@{- "version": "1.0.0",+ "version": "2.0.0","updated": "2026-09-13","description": "Database of global regional, national, and platform regulatory deadlines compiled from App Store Compliance Playbook records.","deadlines": [diff --git a/data/rejection-patterns.json b/data/rejection-patterns.jsonindex f79d148..05dccf7 100644--- a/data/rejection-patterns.json+++ b/data/rejection-patterns.json@@ -1,5 +1,5 @@{- "version": "1.0.0",+ "version": "2.0.0","updated": "2026-09-05","description": "Machine readable taxonomy of App Store and Google Play rejection patterns. Drives the pre submission guard. Each pattern carries a platform, the cited guideline or policy, a severity, an automatable detection signal, and the fix.","sources": [diff --git a/docs/CREDITS.md b/docs/CREDITS.mdindex a5dbe85..8f9380a 100644--- a/docs/CREDITS.md+++ b/docs/CREDITS.md@@ -4,6 +4,13 @@ This playbook stands on the shoulders of the open source community. The patternsIf you maintain one of these and want the wording changed or a link corrected, open an issue.+## People who contributed++| Person | Contribution |+|---|---|+| Omar Albeik ([@omaralbeik](https://github.com/omaralbeik)) | Corrected the Syria entry in the sanctions section ([#967](https://github.com/mjmirza/app-store-compliance/pull/967), landed in [#1001](https://github.com/mjmirza/app-store-compliance/pull/1001)) |+| Akash Sharma ([@akash5852](https://github.com/akash5852)) | Fixed vendor folder platform detection in the guard and added privacy manifest validation ([#596](https://github.com/mjmirza/app-store-compliance/pull/596)) |+## Repositories we learned from| Project | Author | License | What we adopted |diff --git a/docs/CROSS-PLATFORM-FRAMEWORKS.md b/docs/CROSS-PLATFORM-FRAMEWORKS.mdindex d4b8f05..aa3e90d 100644--- a/docs/CROSS-PLATFORM-FRAMEWORKS.md+++ b/docs/CROSS-PLATFORM-FRAMEWORKS.md@@ -9,9 +9,13 @@ generated the app, on top of the native checks.| Framework | Detected by ||---|---|-| Flutter | `pubspec.yaml` present within 3 levels of the project root |-| React Native / Expo | `package.json` dependency on `react-native` or `expo` |-| Ionic / Capacitor / Cordova | `package.json` dependency on `@capacitor/*`, `@ionic/*`, or `cordova-*`, OR a `capacitor.config.*` / `config.xml` file |+| Flutter | `pubspec.yaml` present within 12 levels of the project root |+| React Native / Expo | `package.json` within 12 levels with a dependency on `react-native` or `expo` |+| Ionic / Capacitor / Cordova | `package.json` within 12 levels with a dependency on `@capacitor/*`, `@ionic/*`, or `cordova-*`, OR a `capacitor.config.*` / `config.xml` file within 12 levels |++These depths come from the `find_app` calls in+`agent-os/hooks/app-store-compliance-guard.sh`. Unity, .NET MAUI, Tauri mobile,+and Kotlin Multiplatform are searched within 6 levels.A project can match more than one framework flag (a Capacitor app that alsoimports `expo` polyfills, for example); every matching check runs. Detection scans@@ -28,7 +32,8 @@ known (hook mode) and clearly targets Android only (`build apk/appbundle`,`assembleRelease`, `bundleRelease`, `run-android`, `run:android`,`--platform android`, `capacitor android`, with no `ios`/`ipa`/`xcodebuild`token present), the command overrides the file-tree signal and these Apple-only-checks stay silent. Standalone mode (no command context) falls back to plain+checks stay silent. 2.0.0 also requires every other command in the line to be a+known harmless one, so it never silences more than 1.0.0 did. Standalone mode (no command context) falls back to plainfile-tree detection.## Submission commands the guard recognizes@@ -99,11 +104,12 @@ Added for issue 837. Each one is detected, named on the `Frameworks.` line, and| Tauri mobile | `tauri.conf.json`, `tauri.conf.json5` or `Tauri.toml` | `.rs`, `.toml` | `tauri ios build`, `tauri android build`, with or without `cargo` or `npx` || Kotlin Multiplatform | the multiplatform plugin in a Gradle file | `commonMain` Kotlin, as before | the Gradle and `xcodebuild archive` commands already covered |-Three behaviours to know.+Four behaviours to know.- A Unity project is scanned for both stores when it is run by hand. As a hook the `-buildTarget` value picks the store.- A Unity project holds no Xcode or Gradle project until it is exported, so the export compliance check and the R8 check stay silent and the report says so. Scan the exported project too.- A Kotlin Multiplatform project is scanned as one app, so shared code in `commonMain` counts for both the iOS and the Android checks.+- A bare Xcode or Android project under a root Expo, React Native, Flutter, or Capacitor app is scanned as its own app when it has its own `Info.plist` or `AndroidManifest.xml` and no root build file names its path (`settings.gradle`, a `Podfile`, or an `.xcworkspace`). It counts as an app only with an `.xcodeproj` that builds an application (or names no product type) or an Android application module, so a library, a framework or a local native module stays with the app that uses it. A native host that embeds the root framework (React Native, Expo, Flutter, Capacitor or Cordova code in its sources, such as an `RCTAppDelegate`, or its Podfile or Gradle files) is a brownfield host and stays in the root scan, so the root's framework checks still cover it. A native app that does split off, and the root it left, both keep every framework check the pooled tree showed, so every check that ran when they were scanned as one still runs, a framework marker found only inside the split app included. The root and its split native apps are also scanned together as in 1.0.0, and any finding the separate scans missed is added once, so evidence spread across a shared file and the split app still counts. A project in a folder named exactly `demo`, `example`, `sample`, or `playground` (or the plural) is treated as a repo demo and stays part of the root scan. A nested project splits off only when the root has its own project for that platform, so a managed Expo root with no native project keeps scanning the nested project and keeps its iOS checks. A native root app never splits off a nested project (issue #656).## What stays out of reach@@ -118,6 +124,10 @@ These are limits, not bugs waiting for a fix. Plan around them.- **Rust naming.** The sign-in and account-deletion patterns look for camelCase names such as `signIn`. A Rust function named `sign_in` does not trigger them.- **Frameworks not detected.** NativeScript and legacy Xamarin.Forms projects.- **More than one Xcode target.** Targets are read as one body of source, so an app extension can satisfy, or trigger, a finding for the main app. A watchOS-only or visionOS-only workspace is treated as iOS.+- **Pooled or split layouts that remain coarse (inherited from 1.0).** A single nested managed Expo app is read through the root's config only, shared packages and a brownfield host's source outside the scanned root are not followed, every native target in one root is pooled, and two .NET MAUI or Unity apps in one repo are scanned as one.+- **Workspace runners.** A package script is followed one level deep, so a root script that runs `turbo run build`, which in turn runs a mobile package's submit, is not seen. A pnpm graph selector (`web...`, `...web`, `{apps/web}`) is reduced to its package name, without following that package's dependencies or dependents, and a change-set selector such as `"[origin/main]"` cannot be resolved, so it reads every package, which can block a web-only build in a repo that also holds a mobile app. Run the web build without the wrapper, or set `APP_STORE_GUARD_OK=1` once.+- **Cross-platform purchase plugins.** 1.0.0 checked the restore flow only for native StoreKit apps. 2.0.0 also checks a react-native-iap, RevenueCat or Flutter purchase plugin app, where a purchase list query (`getAvailablePurchases`, `queryPastPurchases`) or the plugin's restore call counts as the restore flow. Check by hand that a visible Restore Purchases control calls it.+- **Monitor source verification.** The regulatory and privacy monitors mark a claim as corroborated when an official source shares its keywords, not when that source states the same claim. Read the official source before acting on a monitor item.- **Store console state.** The guard cannot see App Store Connect or Play Console, so the age rating, social media declaration, and closed testing items are reminders, not proof of a problem.## Known gaps (found by Codex and Qwen adversarial review, not yet fixed)@@ -130,26 +140,30 @@ These are limits, not bugs waiting for a fix. Plan around them.`<!-- <widget ...> -->` or a look-alike tag like `<widgetConfig>` still countsas Cordova evidence. Low severity, no realistic false negative on a realCordova project, though not a hard proof either.-- **Android-side framework checks are absent.** Every check in this doc is+- **Android-side framework checks are thin.** Apart from the Android+ permissions array a managed Expo app config declares, every check in this doc isApple-side. Flutter/RN/Ionic apps also ship to Google Play, where Data Safetydisclosure for bundled SDKs, WebView-controlled data collection, cleartexttraffic, and mixed-content/debug flags are real, framework-relevant risks thisguard does not yet check.-- **The PrivacyInfo.xcprivacy presence check is both too loose and too strict.**- It accepts a manifest found anywhere, including inside `node_modules` or- `Pods`, which does not prove an APP-LEVEL manifest exists. It also has no- Expo-managed-workflow awareness (`expo.ios.privacyManifests` in `app.json`- can be valid with no `ios/PrivacyInfo.xcprivacy` on disk yet, since EAS- generates the native project remotely at build time).-- **Expo Continuous Native Generation (CNG) is not modeled.** A managed Expo- project legitimately has no committed `ios/`/`android/` folder; treating that- as "no iOS target" is not always correct.+- **The PrivacyInfo.xcprivacy check reads the app's own manifest only.**+ A manifest under `Pods`, `Carthage`, `node_modules`, SwiftPM `.build` or+ checkouts, `SourcePackages` or Flutter `.symlinks` does not count. A managed+ Expo app passes with `expo.ios.privacyManifests` in its app config, since EAS+ generates the native project at build time.+- **Expo Continuous Native Generation (CNG) is modeled for config only.** A+ managed Expo project with no committed `ios/` or `android/` folder has its+ `app.json` or `app.config` read for camera and location purpose strings,+ `ios.privacyManifests` and the sensitive `android.permissions` entries. Its+ native code is still NOT CHECKED until `npx expo prebuild` runs.- **Two frameworks have no coverage.** NativeScript and legacy Xamarin.Formsare not detected. Unity, .NET MAUI, Tauri mobile, and Kotlin Multiplatformare, see the section above for what each one still cannot see.-- **The submission regex still misses a few real commands**- (`eas build` with no platform flag, ambiguous local `cap run` without a- release intent) and can overfire on non-release local dev commands.+- **The submission regex errs toward firing.** `SUBMIT_RE` in+ `agent-os/hooks/app-store-compliance-guard.sh` matches `eas build` with or+ without a `--platform` flag, also when global flags come before the+ subcommand. It also matches every `cap run` and `cap open`, so a local dev+ run with no release intent still triggers the guard.These are logged, not hidden. Track them before treating this guard as completecoverage for a cross-platform team; the checks that exist are a realdiff --git a/docs/PRE-SUBMISSION-CHECKLIST.md b/docs/PRE-SUBMISSION-CHECKLIST.mdindex e8e6c2d..c07b211 100644--- a/docs/PRE-SUBMISSION-CHECKLIST.md+++ b/docs/PRE-SUBMISSION-CHECKLIST.md@@ -1,6 +1,11 @@# Pre Submission Checklist-Treat every unchecked box as a release blocker. Run this before any upload to App Store Connect or the Play Console. Each item is phrased as a verifiable check.+Run this before any upload to App Store Connect or the Play Console. Each item is phrased as a verifiable check. Every box ends in one of two states, checked or marked not applicable. An empty box is a release blocker.++Not applicable is allowed one item at a time, and only with a one-line reason written next to the box, for example "N/A. no login, so no demo account" or "N/A. no in app purchases". An item with no reason counts as unchecked. Two items can never be marked not applicable, because every app has them:++- The privacy declaration matches what the app really collects at runtime, every SDK included.+- A privacy policy URL is published and reachable from inside the app.## Start here. Two checks, about five minutes@@ -30,14 +35,14 @@ Then work down the page. Do Shared first, then the store you ship to. Skip any s- [ ] Every third party SDK and its data behavior is known and declared.### Mobile Security and Best Practices-For a deep-dive reference across platform best practices, see `docs/MOBILE-SECURITY-2026.md`.+For a deep-dive reference across platform best practices, see the [mobile security guide](MOBILE-SECURITY-2026.md).- [ ] **Secure Storage:** Sensitive items (session tokens, passwords, keys) are stored securely (iOS Keychain or Android EncryptedSharedPreferences/Keystore) and never in plaintext files, plain SharedPreferences, or unencrypted local databases.- [ ] **Biometrics:** Biometric login (FaceID, TouchID, BiometricPrompt) is crypto-backed, requiring biometric validation to unlock a secure cryptographic key rather than just returning a bypassable boolean.- [ ] **Jailbreak and Root Detection:** Device environment check is implemented locally (and backed by Google Play Integrity on Android) to block or gracefully degrade app features when run on compromised/rooted/jailbroken devices.-- [ ] **Certificate Pinning and SSL:** SSL/TLS cleartext traffic is completely disabled. Public key pinning (SPKI hashes) is implemented on critical endpoints with valid backup pins configured.+- [ ] **Certificate Pinning and SSL:** SSL/TLS cleartext traffic is completely disabled. Public key pinning (SPKI hashes, a fingerprint of the server's public key) is implemented on critical endpoints with valid backup pins configured.- [ ] **Backup Exclusion:** Sensitive private directory files (database files, token preferences) are explicitly excluded from automatic iOS iCloud/iTunes backups and Android ADB/Google Drive backups.- [ ] **Deep Link and URL Schemes Verification:** Inputs from deep links, Universal Links, and App Links are treated as untrusted, sanitized, and thoroughly validated. Secure Universal Links (iOS) and verified App Links (Android) are used instead of easily hijackable custom schemes.-- [ ] **Secure Auth and Session Flows:** Standard modern flows like OAuth 2.1 or OIDC with PKCE are used without hardcoded client secrets. Session timeouts are enforced, and all local tokens, databases, and caches are thoroughly destroyed on logout or session expiration.+- [ ] **Secure Auth and Session Flows:** Standard modern flows like OAuth 2.1 or OIDC with PKCE (a one-time proof that stops a stolen login code from being reused) are used without hardcoded client secrets. Session timeouts are enforced, and all local tokens, databases, and caches are thoroughly destroyed on logout or session expiration.### Metadata and listing- [ ] The app name, description, and screenshots match what the app actually does.@@ -88,7 +93,7 @@ For a deep-dive reference across platform best practices, see `docs/MOBILE-SECUR## EU specific (legal layer, if the app reaches EU users)-Passing App Review does not make an app EU-legal. The full hard rules and sources are in docs/EU-REGULATORY-2026.md.+Passing App Review does not make an app EU-legal. The full hard rules and sources are in the [EU regulatory guide](EU-REGULATORY-2026.md).- [ ] DSA trader status is declared and verified in App Store Connect. A missing declaration removes the app from the EU App Store (Apple enforced 17 February 2025).- [ ] Any AI feature reaching EU users shows an in-app notice that the user is interacting with AI, at or before first interaction (EU AI Act Article 50(1), in force 2 August 2026).@@ -102,7 +107,7 @@ Passing App Review does not make an app EU-legal. The full hard rules and source## Global specific (USA and other markets, if the app reaches those users)-The full hard rules and sources are in docs/GLOBAL-REGULATORY-2026.md. This is legal, on top of App Review. Several dates are under active litigation, so re-verify each against the cited source.+The full hard rules and sources are in the [global regulatory guide](GLOBAL-REGULATORY-2026.md). This is legal, on top of App Review. Several dates are under active litigation, so re-verify each against the cited source.- [ ] Child-directed or under-13 data. COPPA verifiable parental consent, a separate opt-in for ad or third-party disclosure, a written retention policy and a written security program (general compliance date 22 April 2026).- [ ] US state App Store Accountability Acts (Utah, Texas, Louisiana, Alabama). the app requests an age category from the store, confirms parental consent for a minor, and re-requests on a major change, wired through the Declared Age Range API (iOS) or the Play Age Signals API (Android, ensuring strict ToS compliance prohibiting ads, marketing, user profiling, or analytics use of age data).@@ -119,7 +124,7 @@ The full hard rules and sources are in docs/GLOBAL-REGULATORY-2026.md. This is l## Platform mechanics gate (both stores, if the item applies)-The full detail with dated sources is in `PLATFORM-MECHANICS-2026.md`. These are current, common, blocking causes the base maps did not carry.+The full detail with dated sources is in the [platform mechanics guide](PLATFORM-MECHANICS-2026.md). These are current, common, blocking causes the base maps did not carry.Apple.@@ -149,7 +154,7 @@ Cross-cutting.- [ ] Account-creating app has both an in-app account-and-data deletion flow and a publicly reachable web deletion URL, declared.- [ ] Not on the OFAC SDN list, and country availability excludes the embargoed territories.- [ ] Releasing in Syria. EAR jurisdiction, classification, and the license exception or license relied on are documented (15 CFR 746.9).-- [ ] Non-store card payments for real goods implement PSD2 SCA and 3D Secure in the EU or UK, store no card number, and identify the correct PCI SAQ.+- [ ] Non-store card payments for real goods implement PSD2 SCA and 3D Secure in the EU or UK, store no card number, and identify the correct PCI SAQ (the card industry self-assessment form that fits how the app takes payments).## The two checks that prevent the most rejectionsdiff --git a/scripts/accessibility-audit-test.sh b/scripts/accessibility-audit-test.shindex ed77e9f..951e9e4 100755--- a/scripts/accessibility-audit-test.sh+++ b/scripts/accessibility-audit-test.sh@@ -904,6 +904,127 @@ elsefirm -rf "$ISSUE_DIR" 2>/dev/null || true+# Issue #1000. Edge cases from the October review.+I1000_DIR=$(mktemp -d "/tmp/access_issue1000_XXXXXX")+mkdir -p "$I1000_DIR/paren_label" "$I1000_DIR/comment_image" "$I1000_DIR/code_image"+cat << 'EOF' > "$I1000_DIR/paren_label/P.swift"+import SwiftUI+struct V: View {+ var body: some View {+ Button(action: {}, label: ({ Image(systemName: "trash") }))+ Button(action: {}, label: (({ Image(systemName: "gear") })))+ Button(action: {}, label: ({ Image(systemName: "star") })).accessibilityLabel("Star")+ }+}+EOF+cat << 'EOF' > "$I1000_DIR/comment_image/C.swift"+import SwiftUI+// Example: Image("logo")+/* Another example, Image("banner") */+struct V: View {+ var body: some View {+ Text("Hello")+ }+}+EOF+cat << 'EOF' > "$I1000_DIR/code_image/D.swift"+import SwiftUI+struct V: View {+ var body: some View {+ Image("logo") // accessibilityLabel is still missing here+ }+}+EOF++OUT=$($AUDIT "$I1000_DIR/paren_label" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if [ "$(echo "$OUT" | grep -c "APPLE-ACCESSIBILITY-VOICEOVER (")" -eq 2 ]; then+ ok "#1000 a label closure wrapped in parentheses is read, so the icon-only Button is reported"+else+ bad "#1000 a parenthesised label closure was not read. Output:"; echo "$OUT"+fi++OUT=$($AUDIT "$I1000_DIR/comment_image" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q "Clean. No accessibility compliance regressions found."; then+ ok "#1000 an Image inside a comment is not reported as a VoiceOver finding"+else+ bad "#1000 the Image rule read a comment. Output:"; echo "$OUT"+fi++OUT=$($AUDIT "$I1000_DIR/code_image" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if [ "$(echo "$OUT" | grep -c "APPLE-ACCESSIBILITY-VOICEOVER (")" -eq 1 ] && echo "$OUT" | grep -q 'Image("logo")'; then+ ok "#1000 a real Image in code is still reported even when a comment names accessibilityLabel"+else+ bad "#1000 a real unlabelled Image in code was not reported. Output:"; echo "$OUT"+fi+rm -rf "$I1000_DIR" 2>/dev/null || true++# A Swift bare regex holding a quote never hides the Image after it+R8_DIR="$(mktemp -d)"; mkdir -p "$R8_DIR/app"+printf '%s\n' 'import SwiftUI' 'struct V: View { var body: some View { let regex = /"/; let s = " // "; Image("logo") } }' > "$R8_DIR/app/V.swift"+OUT=$($AUDIT "$R8_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("logo")'; then ok "an Image after a Swift regex holding a quote is still reported"; else bad "an Image after a Swift regex holding a quote was lost. Output:"; echo "$OUT"; fi+rm -rf "$R8_DIR" 2>/dev/null || true++# A closed block comment at the start of a line never hides the code after it+R9_DIR="$(mktemp -d)"; mkdir -p "$R9_DIR/app"+printf '%s\n' 'import SwiftUI' '/* comment */ let r = /"/; let image = Image("hero")' > "$R9_DIR/app/V.swift"+OUT=$($AUDIT "$R9_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after a closed block comment and a regex is still reported"; else bad "an Image after a closed block comment and a regex was lost. Output:"; echo "$OUT"; fi+rm -rf "$R9_DIR" 2>/dev/null || true+# Code between two block comments on one line is never blanked+R10_DIR="$(mktemp -d)"; mkdir -p "$R10_DIR/app"+printf '%s\n' 'import SwiftUI' '/* comment */ let r = /"/; let image = Image("hero") /* tail */' > "$R10_DIR/app/V.swift"+OUT=$($AUDIT "$R10_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image between two block comments is still reported"; else bad "an Image between two block comments was lost. Output:"; echo "$OUT"; fi+rm -rf "$R10_DIR" 2>/dev/null || true+# A Swift continuation line led by * (multiplication) is code, never a comment line+R16_DIR="$(mktemp -d)"; mkdir -p "$R16_DIR/app"+printf '%s\n' 'import SwiftUI' 'func score(_ p: Regex<Substring>) -> Double { 0.25 }' 'struct Demo: View {' ' var body: some View {' ' Color.red.opacity(2' ' * score(/"/)).overlay(Image("hero"))' ' }' '}' > "$R16_DIR/app/V.swift"+OUT=$($AUDIT "$R16_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image on a line led by * is still reported"; else bad "an Image on a line led by * was lost. Output:"; echo "$OUT"; fi+rm -rf "$R16_DIR" 2>/dev/null || true+# A /* inside a Swift multiline string never blanks the code after the string+R17_DIR="$(mktemp -d)"; mkdir -p "$R17_DIR/app"+printf '%s\n' 'import SwiftUI' 'let example = """' '/*' '"""' 'let regex = /"/; let image = Image("hero")' > "$R17_DIR/app/V.swift"+OUT=$($AUDIT "$R17_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after a multiline string holding /* is still reported"; else bad "an Image after a multiline string holding /* was lost. Output:"; echo "$OUT"; fi+rm -rf "$R17_DIR" 2>/dev/null || true+# An escaped triple quote inside a Swift multiline string never closes it+R18_DIR="$(mktemp -d)"; mkdir -p "$R18_DIR/app"+printf '%s\n' 'import SwiftUI' 'let example = """' '\"""' '/*' '"""' 'let regex = /"/; let image = Image("hero")' > "$R18_DIR/app/V.swift"+OUT=$($AUDIT "$R18_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after a string holding an escaped triple quote is still reported"; else bad "an Image after a string holding an escaped triple quote was lost. Output:"; echo "$OUT"; fi+rm -rf "$R18_DIR" 2>/dev/null || true+# A Swift raw multiline string with an escaped delimiter inside never closes early+R20_DIR="$(mktemp -d)"; mkdir -p "$R20_DIR/app"+printf '%s\n' 'import SwiftUI' 'let example = #"""' '\#"""' '/*' '"""#' 'let regex = /"/; let image = Image("hero")' > "$R20_DIR/app/V.swift"+OUT=$($AUDIT "$R20_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after a raw multiline string is still reported"; else bad "an Image after a raw multiline string was lost. Output:"; echo "$OUT"; fi+rm -rf "$R20_DIR" 2>/dev/null || true+# A triple quote inside a // comment never opens a string+R21_DIR="$(mktemp -d)"; mkdir -p "$R21_DIR/app"+printf '%s\n' 'import SwiftUI' '// """' 'let example = """' '/*' '"""' 'let regex = /"/; let image = Image("hero")' > "$R21_DIR/app/V.swift"+OUT=$($AUDIT "$R21_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after a comment holding a triple quote is still reported"; else bad "an Image after a comment holding a triple quote was lost. Output:"; echo "$OUT"; fi+rm -rf "$R21_DIR" 2>/dev/null || true+# A triple quote after an inline // comment never opens a string+R22_DIR="$(mktemp -d)"; mkdir -p "$R22_DIR/app"+printf '%s\n' 'import SwiftUI' 'let n = 1 // """' 'let example = """' '/*' '"""' 'let regex = /"/; let image = Image("hero")' > "$R22_DIR/app/V.swift"+OUT=$($AUDIT "$R22_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an Image after an inline comment holding a triple quote is still reported"; else bad "an Image after an inline comment holding a triple quote was lost. Output:"; echo "$OUT"; fi+rm -rf "$R22_DIR" 2>/dev/null || true+# An interpolated Image inside a multiline string is code, even on a line led by //+R23_DIR="$(mktemp -d)"; mkdir -p "$R23_DIR/app"+printf '%s\n' 'import SwiftUI' 'let q = #"three: """ here"#' 'let text = Text("""' '// \(Image("hero"))' '""")' > "$R23_DIR/app/V.swift"+OUT=$($AUDIT "$R23_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "an interpolated Image inside a string is still reported"; else bad "an interpolated Image inside a string was lost. Output:"; echo "$OUT"; fi+rm -rf "$R23_DIR" 2>/dev/null || true+# A raw-string interpolation such as \#( is code inside a string, even on a line led by //+R24_DIR="$(mktemp -d)"; mkdir -p "$R24_DIR/app"+printf '%s\n' 'import SwiftUI' 'let q = #"three: """ here"#' 'let text = Text(#"""' '// \#(Image("hero"))' '"""#)' > "$R24_DIR/app/V.swift"+OUT=$($AUDIT "$R24_DIR/app" --rule APPLE-ACCESSIBILITY-VOICEOVER 2>&1)+if echo "$OUT" | grep -q 'Image("hero")'; then ok "a raw-string interpolated Image is still reported"; else bad "a raw-string interpolated Image was lost. Output:"; echo "$OUT"; fi+rm -rf "$R24_DIR" 2>/dev/null || trueecho ""echo "Accessibility Compliance test suite complete: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/accessibility-audit.py b/scripts/accessibility-audit.pyindex c47a3a4..9273af8 100755--- a/scripts/accessibility-audit.py+++ b/scripts/accessibility-audit.py@@ -181,6 +181,54 @@ def _regex_close(content, start, hashes):return n+def swift_code_lines(content):+ """Only whole comment lines blanked, with no string state, so a misread quote never hides any code.+ Offsets and newlines are kept."""+ out = []+ in_block = False+ in_text = False+ for line in content.split("\n"):+ t = line.lstrip(" \t")+ if re.search(chr(92) * 2 + "#*" + chr(92) + "(", line):+ out.append(line)+ continue+ if not in_block and not in_text and t.startswith("//"):+ # a comment line is blanked before its quotes are counted, so a quote in a comment never opens a string+ out.append(" " * len(line))+ continue+ code = re.sub(chr(92) * 2 + '#*"', "", line)+ cut = code.find("//")+ if cut != -1 and code[:cut].count('"') % 2 == 0:+ code = code[:cut] # quotes after an inline // comment never open a string+ quotes = code.count('"""')+ if not in_block and (in_text or quotes % 2):+ # a multiline string line is kept as is, so a /* or // inside one never blanks the code after it+ if quotes % 2:+ in_text = not in_text+ out.append(line)+ continue+ if not in_block and t.startswith("//"):+ out.append(" " * len(line))+ continue+ if in_block and not (t.startswith("*") or "*/" in line):+ # a block comment goes on only through lines that look like comment lines, any other line is code+ in_block = False+ out.append(line)+ continue+ if in_block or t.startswith("/*"):+ # only a block comment opened at a line start is blanked, a line led by * outside one is code+ end = line.find("*/", len(line) - len(t) + (0 if in_block else 2))+ if end == -1:+ in_block = True+ out.append(" " * len(line))+ else:+ in_block = False+ out.append(" " * (end + 2) + line[end + 2:])+ continue+ out.append(line)+ return "\n".join(out)++def swift_code_only(content):"""Blank comments (nested too) and string contents, keeping quotes, newlines and offsets.What is left is code, so a Button inside a comment or a string is never read as a control."""@@ -315,7 +363,7 @@ IMAGE_SYMBOL = re.compile(r"\bImage\s*\(\s*systemName\s*:")NAMED_CONTENT = re.compile(r"\b(Text|Label)\s*\(|\baccessibilityLabel\b")TITLED_ARG = re.compile(r"\s*(#*\"|title\s*:)")LABEL_ARG = re.compile(r"\s*label\s*:")-LABEL_CLOSURE = re.compile(r"\s*label\s*:\s*\{")+LABEL_CLOSURE = re.compile(r"\s*label\s*:\s*(?:[(]\s*)*\{") # label: ({ ... }) reads tooHIDDEN_TRUE = re.compile(r"\((?:\s*\()*\s*true\s*(?:\)\s*)*\)")ACC_HIDDEN = re.compile(r"\bhidden\s*:\s*(?:\(\s*)*true\b")ACC_LABEL = re.compile(r"\blabel\s*:")@@ -437,27 +485,33 @@ def run_rule_scan(rule_id, ios_files, android_files):except Exception:continue- # Find SwiftUI Image usages- for match in re.finditer(r"\bImage\s*\(([^)]+)\)", content):+ # Find SwiftUI Image usages in code only, so a commented example is never read+ # The lexer view is precise and the line view never loses code to a misread quote. Both are read.+ seen = set()+ code = swift_code_only(content)+ for view in (code, swift_code_lines(content)):+ for match in re.finditer(r"\bImage\s*\(([^)]+)\)", view):+ if match.start() in seen:+ continue+ seen.add(match.start())expr = match.group(1)# Ignore images explicitly defined as decorative or having system accessibility labels/hiddenif "decorative:" in expr or "systemName:" in expr:continue# Simple parsing check: does the immediate context (within 5 lines) have accessibility modifiers?start_idx = match.start()- context = content[start_idx:start_idx + 300]+ context = code[start_idx:start_idx + 300]if not any(kw in context for kw in ["accessibilityLabel", "accessibilityIdentifier", "accessibilityHidden", "accessibilityElement"]):line_no = content.count("\n", 0, start_idx) + 1findings.append({"file": f,"line": line_no,"rule_id": rule_id,- "match": match.group(0),+ "match": content[match.start() : match.end()],"message": "SwiftUI Image used without accessibilityLabel or decorative initialization.","fix": "Initialize decorative images as Image(decorative: ...) or add an explicit .accessibilityLabel(...) modifier."})- code = swift_code_only(content)newlines = [k for k, ch in enumerate(code) if ch == "\n"]for offset, end in find_icon_only_buttons(code):findings.append(diff --git a/scripts/install-harness-test.sh b/scripts/install-harness-test.shnew file mode 100644index 0000000..337ccb6--- /dev/null+++ b/scripts/install-harness-test.sh@@ -0,0 +1,476 @@+#!/usr/bin/env bash+# Tests install.sh --tool for every supported tool other than Claude Code, in a throwaway HOME.+set -uo pipefail+cd "$(dirname "$0")/.." || exit 1++PASS=0+FAIL=0+ok() { PASS=$((PASS+1)); printf 'PASS %s\n' "$1"; }+bad() { FAIL=$((FAIL+1)); printf 'FAIL %s\n' "$1"; }++INSTALL="$PWD/scripts/install.sh"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT+fresh() { H="$WORK/h$RANDOM$RANDOM"; mkdir -p "$H"; }+run() { env -u QWEN_HOME -u KIMI_CODE_HOME -u COPILOT_HOME -u CODEX_HOME -u XDG_CONFIG_HOME -u CLAUDE_CONFIG_DIR -u CLAUDE_PROJECT_DIR HOME="$H" bash "$INSTALL" "$@" 2>&1; }+cfg() {+ case "$1" in+ codex) echo "$H/.codex/hooks.json" ;;+ gemini) echo "$H/.gemini/settings.json" ;;+ opencode) echo "$H/.config/opencode/plugins/app-store-compliance.js" ;;+ cursor) echo "$H/.cursor/hooks.json" ;;+ copilot) echo "$H/.copilot/hooks/app-store-compliance.json" ;;+ grok) echo "$H/.grok/hooks/app-store-compliance.json" ;;+ qwen) echo "$H/.qwen/settings.json" ;;+ kimi) echo "$H/.kimi-code/config.toml" ;;+ droid) echo "$H/.factory/hooks.json" ;;+ auggie) echo "$H/.augment/settings.json" ;;+ windsurf) echo "$H/.codeium/windsurf/hooks.json" ;;+ esac+}+gdir() { # where each tool's guard lands+ case "$1" in+ opencode) echo "$H/.config/opencode/hooks" ;; kimi) echo "$H/.kimi-code/hooks" ;; droid) echo "$H/.factory/hooks" ;;+ auggie) echo "$H/.augment/hooks" ;; windsurf) echo "$H/.codeium/windsurf/hooks" ;; *) echo "$H/.$1/hooks" ;;+ esac+}+count() { # how many hook entries point at the guard+ if [ "$1" = "kimi" ]; then grep -c "app-store-compliance-guard.sh" "$(cfg kimi)" 2>/dev/null || true; return; fi+ python3 - "$1" "$(cfg "$1")" <<'PY'+import json, sys+tool, path = sys.argv[1], sys.argv[2]+key = {"codex": "PreToolUse", "gemini": "BeforeTool", "cursor": "beforeShellExecution", "copilot": "preToolUse",+ "grok": "PreToolUse", "qwen": "PreToolUse", "droid": "PreToolUse", "auggie": "PreToolUse", "windsurf": "pre_run_command"}[tool]+try:+ d = json.load(open(path))+except Exception:+ print(0); sys.exit()+box = d if tool == "droid" else d.get("hooks", {})+groups = box.get(key, [])+n = 0+for g in groups:+ items = g.get("hooks", []) if tool in ("codex", "gemini", "grok", "qwen", "droid", "auggie") else [g]+ n += sum("app-store-compliance-guard.sh" in str(h.get("command", h.get("bash", ""))) for h in items)+print(n)+PY+}++for t in codex gemini opencode cursor copilot grok qwen kimi droid auggie windsurf; do+ # 1 a fresh install verifies itself end to end+ fresh+ OUT="$(run --tool "$t")"; RC=$?+ [ "$RC" -eq 0 ] && echo "$OUT" | grep -q "^Install verified\." && ok "$t fresh install verifies" || { bad "$t fresh install verifies (rc=$RC)"; echo "$OUT" | tail -15; }+ [ -x "$(gdir "$t")/app-store-compliance-guard.sh" ] && ok "$t guard is installed and executable" || bad "$t guard is installed and executable"+ [ -f "$H/.agents/skills/app-store-compliance/SKILL.md" ] && [ -f "$H/.agents/skills/app-store-compliance/VERSION" ] && ok "$t shared skill and version installed" || bad "$t shared skill and version installed"+ if [ "$t" != "opencode" ]; then+ [ "$(count "$t")" = "1" ] && ok "$t hook registered once" || bad "$t hook registered once (got $(count "$t"))"+ BEFORE="$(cat "$(cfg "$t")")"; run --tool "$t" >/dev/null+ [ "$BEFORE" = "$(cat "$(cfg "$t")")" ] && [ "$(count "$t")" = "1" ] && ok "$t a second run is idempotent" || bad "$t a second run is idempotent"+ else+ grep -q 'tool.execute.before' "$(cfg "$t")" && ok "$t plugin written" || bad "$t plugin written"+ # OpenCode before 1.0 loads plugin/, current OpenCode loads plugins/. Both must carry it.+ cmp -s "$(cfg "$t")" "$H/.config/opencode/plugin/app-store-compliance.js" && ok "$t plugin also in the plugin/ folder older OpenCode reads" || bad "$t plugin also in the plugin/ folder older OpenCode reads"+ echo "$OUT" | grep -q "the plugin stops a submit command" && ok "$t plugin blocks a submit command in node" || bad "$t plugin blocks a submit command in node"+ fi+ # 2 doctor passes, and fails after uninstall+ OUT="$(run --tool "$t" doctor)"; RC=$?+ [ "$RC" -eq 0 ] && ok "$t doctor passes" || bad "$t doctor passes (rc=$RC)"+ run --tool "$t" uninstall >/dev/null+ [ ! -e "$H/.agents/skills/app-store-compliance" ] && ok "$t uninstall removes the shared skill when no tool is left" || bad "$t uninstall removes the shared skill when no tool is left"+ if [ "$t" = "opencode" ]; then+ [ ! -e "$(cfg "$t")" ] && [ ! -e "$H/.config/opencode/plugin/app-store-compliance.js" ] && ok "$t uninstall removes the plugin from both folders" || bad "$t uninstall removes the plugin from both folders"+ else+ [ "$(count "$t")" = "0" ] && ok "$t uninstall removes the hook entry" || bad "$t uninstall removes the hook entry"+ fi+ run --tool "$t" doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "$t doctor fails when nothing is installed" || bad "$t doctor fails when nothing is installed (rc=$RC)"+done++# 2b vendor-specific shapes. Copilot carries its own entry and the one VS Code reads, Auggie counts milliseconds.+fresh; run --tool copilot >/dev/null; run --tool auggie >/dev/null; run --tool windsurf >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); a=d["hooks"]["preToolUse"][0]; b=d["hooks"]["PreToolUse"][0]; sys.exit(0 if d["version"]==1 and a["timeoutSec"]==120 and a["bash"].endswith("guard.sh'"'"'") and b["timeout"]==120 and b["command"]==a["bash"] else 1)' "$H/.copilot/hooks/app-store-compliance.json" \+ && ok "copilot file carries the Copilot entry and the VS Code entry" || bad "copilot file carries the Copilot entry and the VS Code entry"+python3 -c 'import json,sys; a=json.load(open(sys.argv[1]))["hooks"]["preToolUse"][0]; p=a.get("powershell",""); sys.exit(0 if p.startswith("$input | & bash ") and "app-store-compliance-guard.sh" in p and p.rstrip().endswith("exit $LASTEXITCODE") else 1)' "$H/.copilot/hooks/app-store-compliance.json" \+ && ok "copilot also carries a Windows powershell handler that pipes the payload to the guard and keeps its exit code" || bad "copilot also carries a Windows powershell handler that pipes the payload to the guard and keeps its exit code"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooks"]["preToolUse"][0].pop("powershell",None); json.dump(d,open(p,"w"))' "$H/.copilot/hooks/app-store-compliance.json"+run --tool copilot doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "copilot doctor fails when the Windows handler is missing" || bad "copilot doctor fails when the Windows handler is missing (rc=$RC)"+run --tool copilot >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); e=d["hooks"]["preToolUse"]; sys.exit(0 if len(e)==1 and e[0].get("powershell") else 1)' "$H/.copilot/hooks/app-store-compliance.json" \+ && ok "copilot install adds the missing Windows handler without a duplicate" || bad "copilot install adds the missing Windows handler without a duplicate"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooks"]["preToolUse"][0]["powershell"]="Write-Output app-store-compliance-guard.sh; exit $LASTEXITCODE"; json.dump(d,open(p,"w"))' "$H/.copilot/hooks/app-store-compliance.json"+run --tool copilot doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "copilot doctor fails when the Windows handler was edited" || bad "copilot doctor fails when the Windows handler was edited (rc=$RC)"+run --tool copilot >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); g=d["hooks"]["PreToolUse"][0]; sys.exit(0 if g["matcher"]=="launch-process" and g["hooks"][0]["timeout"]==120000 else 1)' "$H/.augment/settings.json" \+ && ok "auggie uses launch-process and a millisecond timeout" || bad "auggie uses launch-process and a millisecond timeout"+python3 -c 'import json,os,sys; c=json.load(open(sys.argv[1]))["hooks"]["PreToolUse"][0]["hooks"][0]["command"]; sys.exit(0 if c==sys.argv[2] and os.access(c,os.X_OK) and open(c).readline().startswith("#!") else 1)' "$H/.augment/settings.json" "$H/.augment/hooks/app-store-compliance-guard.sh" \+ && ok "auggie registers the executable guard script path, as its docs require" || bad "auggie registers the executable guard script path, as its docs require"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); h=d["hooks"]["PreToolUse"][0]["hooks"][0]; h["command"]="bash "+h["command"]; json.dump(d,open(p,"w"))' "$H/.augment/settings.json"+run --tool auggie doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "auggie doctor fails on a shell command string" || bad "auggie doctor fails on a shell command string (rc=$RC)"+run --tool auggie >/dev/null; run --tool auggie doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && [ "$(count auggie)" = "1" ] && ok "auggie install replaces the shell string with the script path once" || bad "auggie install replaces the shell string with the script path once (rc=$RC entries=$(count auggie))"+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); e=d["hooks"]["pre_run_command"][0]; sys.exit(0 if e["show_output"] is True else 1)' "$H/.codeium/windsurf/hooks.json" \+ && ok "windsurf shows the guard output to the user" || bad "windsurf shows the guard output to the user"++# 2b2 Grok runs its shell through run_terminal_command, run_terminal_cmd, bash and monitor, in a camelCase payload+fresh; run --tool grok >/dev/null+python3 -c 'import json,re,sys; m=json.load(open(sys.argv[1]))["hooks"]["PreToolUse"][0]["matcher"]; sys.exit(0 if m=="Bash|run_terminal_command|run_terminal_cmd|bash|monitor" and all(re.fullmatch(m,t) for t in ("run_terminal_command","run_terminal_cmd","bash","monitor")) else 1)' "$(cfg grok)" \+ && ok "grok matcher covers every Grok shell tool" || bad "grok matcher covers every Grok shell tool"+GLOG="$WORK/grok-payload$RANDOM.json"; GG="$(gdir grok)/app-store-compliance-guard.sh"; cp "$GG" "$WORK/grok-guard.bak"+printf '#!/usr/bin/env bash\ncat > "%s"\ngrep -q deliver "%s" && exit 2\nexit 0\n' "$GLOG" "$GLOG" > "$GG"+run --tool grok doctor >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d.get("toolName")=="run_terminal_command" and d.get("hookEventName")=="PreToolUse" and "command" in d.get("toolInput",{}) else 1)' "$GLOG" 2>/dev/null \+ && ok "grok doctor feeds a run_terminal_command payload" || bad "grok doctor feeds a run_terminal_command payload"+cp "$WORK/grok-guard.bak" "$GG"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooks"]["PreToolUse"][0]["matcher"]="Bash"; json.dump(d,open(p,"w"))' "$(cfg grok)"+run --tool grok doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "grok doctor fails on an old Bash-only matcher" || bad "grok doctor fails on an old Bash-only matcher (rc=$RC)"+run --tool grok >/dev/null; run --tool grok doctor >/dev/null; RC=$?+python3 -c 'import json,sys; g=json.load(open(sys.argv[1]))["hooks"]["PreToolUse"]; sys.exit(0 if [x["matcher"] for x in g]==["Bash|run_terminal_command|run_terminal_cmd|bash|monitor"] else 1)' "$(cfg grok)" && [ "$RC" -eq 0 ] && [ "$(count grok)" = "1" ] \+ && ok "grok install repairs a Bash-only matcher once and doctor then passes" || bad "grok install repairs a Bash-only matcher once and doctor then passes (rc=$RC entries=$(count grok))"++# 2c Droid keeps using settings.json when its hooks live there, and never shadows them with a new hooks.json+fresh; mkdir -p "$H/.factory"+printf '{"model":"x","hooks":{"PostToolUse":[{"matcher":"Edit","hooks":[{"type":"command","command":"fmt"}]}]}}' > "$H/.factory/settings.json"+OUT="$(run --tool droid)"; RC=$?+[ "$RC" -eq 0 ] && [ ! -e "$H/.factory/hooks.json" ] && python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d["model"]=="x" and d["hooks"]["PostToolUse"] and d["hooks"]["PreToolUse"][0]["matcher"]=="Execute" else 1)' "$H/.factory/settings.json" \+ && ok "droid adds to settings.json when its hooks already live there" || bad "droid adds to settings.json when its hooks already live there (rc=$RC)"+run --tool droid uninstall >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if "PreToolUse" not in d["hooks"] and d["hooks"]["PostToolUse"] else 1)' "$H/.factory/settings.json" \+ && ok "droid uninstall keeps the other settings.json hooks" || bad "droid uninstall keeps the other settings.json hooks"++# 2d Kimi. A config holding a secret is appended to, never rewritten, and uninstall restores it exactly+fresh; mkdir -p "$H/.kimi-code"+printf 'default_model = "k2"\n\n[providers.moonshot]\n%s = "%s"\n' "api""_key" "fixture-not-a-secret" > "$H/.kimi-code/config.toml"+cp "$H/.kimi-code/config.toml" "$WORK/kimi-orig.toml"+OUT="$(run --tool kimi)"; RC=$?+[ "$RC" -eq 0 ] && grep -q '= "fixture-not-a-secret"' "$H/.kimi-code/config.toml" && python3 -c 'import sys,tomllib; d=tomllib.load(open(sys.argv[1],"rb")); h=d["hooks"][0]; sys.exit(0 if h["event"]=="PreToolUse" and h["matcher"]=="^Bash$" and h["timeout"]==120 else 1)' "$H/.kimi-code/config.toml" \+ && ok "kimi appends a valid hook block and keeps the existing settings" || bad "kimi appends a valid hook block and keeps the existing settings (rc=$RC)"+! echo "$OUT" | grep -q "fixture-not-a-secret" && ok "kimi install never prints the config contents" || bad "kimi install never prints the config contents"+run --tool kimi >/dev/null+[ "$(count kimi)" = "1" ] && ok "kimi a second run adds nothing" || bad "kimi a second run adds nothing"+run --tool kimi uninstall >/dev/null+cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-orig.toml" && ok "kimi uninstall restores the file exactly" || bad "kimi uninstall restores the file exactly"+for tail in "" "\n" "\n\n\n"; do+ fresh; mkdir -p "$H/.kimi-code"; printf "default_model = \"k2\"$tail" > "$H/.kimi-code/config.toml"; cp "$H/.kimi-code/config.toml" "$WORK/kimi-orig.toml"+ run --tool kimi >/dev/null; run --tool kimi uninstall >/dev/null+ cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-orig.toml" && ok "kimi uninstall keeps the original trailing newlines (${#tail} chars)" || bad "kimi uninstall keeps the original trailing newlines (${#tail} chars)"+done++# 2d2 KIMI_CODE_HOME moves Kimi's whole data folder, so the hook goes where Kimi reads it+fresh; mkdir -p "$H/kimi-custom"; printf 'default_model = "k2"\n' > "$H/kimi-custom/config.toml"+OUT="$(env -u QWEN_HOME -u CODEX_HOME -u XDG_CONFIG_HOME HOME="$H" KIMI_CODE_HOME="$H/kimi-custom" bash "$INSTALL" --tool kimi 2>&1)"; RC=$?+[ "$RC" -eq 0 ] && grep -q "app-store-compliance-guard.sh" "$H/kimi-custom/config.toml" && [ ! -e "$H/.kimi-code/config.toml" ] && ok "kimi follows KIMI_CODE_HOME" || bad "kimi follows KIMI_CODE_HOME (rc=$RC)"+OUT="$(env -u QWEN_HOME -u CODEX_HOME -u XDG_CONFIG_HOME HOME="$H" KIMI_CODE_HOME="$H/kimi-custom" bash "$INSTALL" --tool all 2>&1)"+echo "$OUT" | grep -q "== kimi ==" && ok "auto discovery finds Kimi under KIMI_CODE_HOME" || bad "auto discovery finds Kimi under KIMI_CODE_HOME"+# 2d3 an inline hooks array cannot take a [[hooks]] block, so the file is left as it was and the block is shown+fresh; mkdir -p "$H/.kimi-code"+printf 'hooks = [{event = "PreToolUse", matcher = "^Bash$", command = "bash /other/check.sh", timeout = 120}]\ndefault_model = "k2"\n' > "$H/.kimi-code/config.toml"+cp "$H/.kimi-code/config.toml" "$WORK/kimi-inline.toml"+OUT="$(run --tool kimi)"; RC=$?+[ "$RC" -ne 0 ] && cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-inline.toml" && echo "$OUT" | grep -q "\[\[hooks\]\]" && ok "kimi refuses an inline hooks array and changes nothing" || bad "kimi refuses an inline hooks array and changes nothing (rc=$RC)"++# 2d4 an async handler runs in the background and cannot block, so doctor fails and install repairs it+fresh; run --tool qwen >/dev/null+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); [h.__setitem__("async", True) for g in d["hooks"]["PreToolUse"] for h in g["hooks"] if "guard.sh" in h["command"]]; json.dump(d, open(p,"w"))' "$(cfg qwen)"+run --tool qwen doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "qwen doctor fails on an async guard handler" || bad "qwen doctor fails on an async guard handler (rc=$RC)"+run --tool qwen >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if all(not h.get("async") for g in d["hooks"]["PreToolUse"] for h in g["hooks"] if "guard.sh" in h["command"]) else 1)' "$(cfg qwen)" \+ && ok "qwen install repairs an async guard handler" || bad "qwen install repairs an async guard handler"+# Cursor runs a handler only when its type is command and its matcher takes the submit command, and needs a positive whole number version+for broken in 'h.__setitem__("matcher", "^git status$")' 'h.__setitem__("type", "prompt")'; do+ fresh; run --tool cursor >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); [exec(sys.argv[2], {"h": h}) for ev in d["hooks"].values() for h in ev if "guard" in json.dumps(h)]; json.dump(d, open(p,"w"))' "$(cfg cursor)" "$broken"+ run --tool cursor doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "cursor doctor fails on a handler that never runs the guard. $broken" || bad "cursor doctor fails on a handler that never runs the guard. $broken (rc=$RC)"+ run --tool cursor >/dev/null; run --tool cursor doctor >/dev/null; RC=$?+ [ "$RC" -eq 0 ] && ok "cursor install repairs the handler. $broken" || bad "cursor install repairs the handler. $broken (rc=$RC)"+done+for v in 0 true; do+ fresh; run --tool cursor >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["version"]=json.loads(sys.argv[2]); json.dump(d, open(p,"w"))' "$(cfg cursor)" "$v"+ run --tool cursor doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "cursor doctor fails on version $v" || bad "cursor doctor fails on version $v (rc=$RC)"+ run --tool cursor >/dev/null+ python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get("version"); sys.exit(0 if type(v) is int and v >= 1 else 1)' "$(cfg cursor)" \+ && ok "cursor install repairs version $v" || bad "cursor install repairs version $v"+done+# Copilot needs version to be the number 1, true is not 1, and a version repair is written even when the handlers are fine+fresh; mkdir -p "$(dirname "$(cfg copilot)")"; printf '{"version":true}\n' > "$(cfg copilot)"+run --tool copilot >/dev/null+python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get("version"); sys.exit(0 if type(v) is int and v == 1 else 1)' "$(cfg copilot)" \+ && ok "copilot install repairs a version of true" || bad "copilot install repairs a version of true"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d.pop("version", None); json.dump(d, open(p,"w"))' "$(cfg copilot)"+run --tool copilot >/dev/null+python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get("version"); sys.exit(0 if type(v) is int and v == 1 else 1)' "$(cfg copilot)" \+ && ok "copilot reinstall writes back a missing version" || bad "copilot reinstall writes back a missing version"+# Gemini runs no hook when hooksConfig.enabled is false+fresh; run --tool gemini >/dev/null+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooksConfig"]={"enabled": False}; json.dump(d, open(p,"w"))' "$(cfg gemini)"+run --tool gemini doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "gemini doctor fails when hooksConfig.enabled is false" || bad "gemini doctor fails when hooksConfig.enabled is false (rc=$RC)"+# Copilot rejects a hooks file whose version is not 1, and runs a handler only for the tools its matcher names+fresh; mkdir -p "$(dirname "$(cfg copilot)")"; printf '{"version":0}\n' > "$(cfg copilot)"+run --tool copilot >/dev/null+python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1])).get("version") == 1 else 1)' "$(cfg copilot)" \+ && ok "copilot install repairs a bad version" || bad "copilot install repairs a bad version"+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["version"]=0; json.dump(d, open(p,"w"))' "$(cfg copilot)"+run --tool copilot doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "copilot doctor fails on a bad version" || bad "copilot doctor fails on a bad version (rc=$RC)"+fresh; run --tool copilot >/dev/null+python3 -c 'import json,sys+p=sys.argv[1]; d=json.load(open(p))+for ev in d.get("hooks", {}).values():+ for h in ev:+ if "guard" in json.dumps(h): h["matcher"] = "^view$"+json.dump(d, open(p,"w"))' "$(cfg copilot)"+run --tool copilot doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "copilot doctor fails on a handler whose matcher skips the shell" || bad "copilot doctor fails on a handler whose matcher skips the shell (rc=$RC)"+run --tool copilot >/dev/null+run --tool copilot doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && ok "copilot install repairs a handler whose matcher skips the shell" || bad "copilot install repairs a handler whose matcher skips the shell (rc=$RC)"+# Kimi refuses a timeout over 600 and any key beyond event, matcher, command and timeout+for broken in 's/^timeout = 120$/timeout = 601/' 's/^timeout = 120$/timeout = 120\nasync = true/'; do+ fresh; run --tool kimi >/dev/null+ python3 -c 'import re,sys; p=sys.argv[1]; s=open(p).read(); a,b=sys.argv[2][2:-1].split("/"); open(p,"w").write(re.sub(a, b.replace(chr(92)+"n", chr(10)), s, flags=re.M))' "$(cfg kimi)" "$broken"+ run --tool kimi doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "kimi doctor fails on a hook Kimi refuses. $broken" || bad "kimi doctor fails on a hook Kimi refuses. $broken (rc=$RC)"+ run --tool kimi >/dev/null+ python3 -c 'import sys,tomllib; d=tomllib.load(open(sys.argv[1],"rb")); hs=[h for h in d.get("hooks",[]) if "guard.sh" in h.get("command","")]; sys.exit(0 if hs and all(set(h) <= {"event","matcher","command","timeout"} and h["timeout"] == 120 for h in hs) else 1)' "$(cfg kimi)" \+ && ok "kimi install repairs the hook. $broken" || bad "kimi install repairs the hook. $broken"+done+# Qwen and Copilot run no hook at all when disableAllHooks is true, so doctor must say so+for t in qwen copilot; do+ fresh; run --tool $t >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["disableAllHooks"]=True; json.dump(d, open(p,"w"))' "$(cfg $t)"+ run --tool $t doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "$t doctor fails when disableAllHooks is true" || bad "$t doctor fails when disableAllHooks is true (rc=$RC)"+done+# Qwen needs the type on every handler, and reads a timeout of 1000 or more as milliseconds+for broken in 'h.pop("type", None)' 'h.__setitem__("timeout", 1000)'; do+ fresh; run --tool qwen >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); [exec(sys.argv[2], {"h": h}) for g in d["hooks"]["PreToolUse"] for h in g["hooks"] if "guard.sh" in h["command"]]; json.dump(d, open(p,"w"))' "$(cfg qwen)" "$broken"+ run --tool qwen doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "qwen doctor fails on a handler Qwen would not run in time. $broken" || bad "qwen doctor fails on a handler Qwen would not run in time. $broken (rc=$RC)"+ run --tool qwen >/dev/null+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); hs=[h for g in d["hooks"]["PreToolUse"] for h in g["hooks"] if "guard.sh" in h["command"]]; sys.exit(0 if hs and all(h.get("type") == "command" and 120 <= h.get("timeout", 0) < 1000 for h in hs) else 1)' "$(cfg qwen)" \+ && ok "qwen install repairs the handler. $broken" || bad "qwen install repairs the handler. $broken"+done+# 2d5 COPILOT_HOME moves Copilot's user hooks folder, so the hook goes where Copilot reads it+fresh; mkdir -p "$H/cop"+OUT="$(env -u QWEN_HOME -u KIMI_CODE_HOME -u CODEX_HOME -u XDG_CONFIG_HOME HOME="$H" COPILOT_HOME="$H/cop" bash "$INSTALL" --tool copilot 2>&1)"; RC=$?+[ "$RC" -eq 0 ] && [ -f "$H/cop/hooks/app-store-compliance.json" ] && [ ! -e "$H/.copilot" ] && ok "copilot follows COPILOT_HOME" || bad "copilot follows COPILOT_HOME (rc=$RC)"+# 2d6 a CRLF [hooks] table and a quoted hooks key are refused too, and the file is left as it was+for body in '[hooks]\r\nx = 1\r\n' '"hooks" = []\n'; do+ fresh; mkdir -p "$H/.kimi-code"; printf "$body" > "$H/.kimi-code/config.toml"; cp "$H/.kimi-code/config.toml" "$WORK/kimi-k.toml"+ run --tool kimi >/dev/null; RC=$?+ [ "$RC" -ne 0 ] && cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-k.toml" && ok "kimi refuses an existing hooks key and changes nothing ($body)" || bad "kimi refuses an existing hooks key and changes nothing ($body) (rc=$RC)"+done++# 2d7 an escaped hooks key is refused even where Python has no TOML parser+NOTOML="$WORK/notoml"; mkdir -p "$NOTOML"; printf 'raise ImportError("no tomllib here")\n' > "$NOTOML/tomllib.py"+fresh; mkdir -p "$H/.kimi-code"; printf '"ho\\u006fks" = []\n' > "$H/.kimi-code/config.toml"; cp "$H/.kimi-code/config.toml" "$WORK/kimi-esc.toml"+PYTHONPATH="$NOTOML" run --tool kimi >/dev/null; RC=$?+[ "$RC" -ne 0 ] && cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-esc.toml" && ok "kimi refuses an escaped hooks key without a TOML parser" || bad "kimi refuses an escaped hooks key without a TOML parser (rc=$RC)"+# 2d8 repairing our marked block never turns a valid file invalid+fresh; mkdir -p "$H/.kimi-code"+printf 'hooks = []\n# >>> app-store-compliance guard >>>\n# old disabled hook\n# <<< app-store-compliance guard <<<\n' > "$H/.kimi-code/config.toml"+cp "$H/.kimi-code/config.toml" "$WORK/kimi-rep.toml"+run --tool kimi >/dev/null; RC=$?+[ "$RC" -ne 0 ] && cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-rep.toml" && ok "kimi refuses a block repair that would break the file" || bad "kimi refuses a block repair that would break the file (rc=$RC)"++# 2d9 a Windows path in the Gemini audit command still gives valid TOML+python3 -c '+import sys, tomllib+sys.path.insert(0, "scripts")+import install_harness as h+b = chr(92)+h.shown = lambda p: "~" + b + ".gemini" + b + "hooks" + b + "app-store-compliance-guard.sh"+t = tomllib.loads(h.command_text("gemini", "x"))+sys.exit(0 if (b + ".gemini" + b) in t["prompt"] else 1)+' 2>/dev/null && ok "gemini audit command stays valid TOML with a Windows path" || bad "gemini audit command stays valid TOML with a Windows path"++# 2e Copilot in the app repository (cloud agent, JetBrains, VS Code workspace)+fresh; APPR="$WORK/apprepo$RANDOM"; mkdir -p "$APPR"+OUT="$(run --tool copilot-repo)"; RC=$?+[ "$RC" -eq 2 ] && echo "$OUT" | grep -q "Pass --repo" && ok "copilot-repo without --repo exits 2 and says what to pass" || bad "copilot-repo without --repo exits 2 (rc=$RC)"+OUT="$(run --tool copilot-repo --repo "$APPR")"; RC=$?+[ "$RC" -eq 0 ] && echo "$OUT" | grep -q "^Install verified\." && [ -x "$APPR/.github/hooks/app-store-compliance-guard.sh" ] \+ && python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d["hooks"]["preToolUse"][0]["bash"]=="bash ./.github/hooks/app-store-compliance-guard.sh" else 1)' "$APPR/.github/hooks/app-store-compliance.json" \+ && [ ! -e "$H/.agents" ] && ok "copilot-repo writes a relative hook into the repository and nothing in HOME" || { bad "copilot-repo writes a relative hook into the repository (rc=$RC)"; echo "$OUT" | tail -8; }+run --tool copilot-repo --repo "$APPR" uninstall >/dev/null+[ ! -e "$APPR/.github/hooks/app-store-compliance.json" ] && [ ! -e "$APPR/.github/hooks/app-store-compliance-guard.sh" ] && ok "copilot-repo uninstall removes both files" || bad "copilot-repo uninstall removes both files"++# 3 existing settings survive and get a backup (Gemini keeps ide and security, Codex keeps its other hooks)+fresh; mkdir -p "$H/.gemini" "$H/.codex"+printf '{"ide":{"enabled":true},"security":{"auth":{"selectedType":"oauth-personal"}}}' > "$H/.gemini/settings.json"+printf '{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"bash ~/other.sh"}]}]}}' > "$H/.codex/hooks.json"+run --tool gemini >/dev/null; run --tool codex >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); h=d["hooks"]["BeforeTool"][0]; sys.exit(0 if d["ide"]=={"enabled":True} and d["security"]["auth"]["selectedType"]=="oauth-personal" and d["tools"]["enableHooks"] is True and h["matcher"]=="run_shell_command" and h["hooks"][0]["timeout"]==120000 else 1)' "$H/.gemini/settings.json" \+ && ok "gemini keeps existing keys, enables hooks, uses a millisecond timeout" || bad "gemini keeps existing keys, enables hooks, uses a millisecond timeout"+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); c=[h["command"] for g in d["hooks"]["PreToolUse"] for h in g["hooks"]]; sys.exit(0 if "bash ~/other.sh" in c and len(c)==2 else 1)' "$H/.codex/hooks.json" \+ && ok "codex keeps its existing hooks" || bad "codex keeps its existing hooks"+ls "$H"/.gemini/settings.json.bak-* >/dev/null 2>&1 && ls "$H"/.codex/hooks.json.bak-* >/dev/null 2>&1 && ok "a backup is kept for each edited config" || bad "a backup is kept for each edited config"+# 4 the shared skill stays while another tool still uses it+run --tool gemini uninstall >/dev/null+[ -f "$H/.agents/skills/app-store-compliance/SKILL.md" ] && ok "the shared skill stays while codex still uses it" || bad "the shared skill stays while codex still uses it"+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d["ide"]=={"enabled":True} and "hooks" not in d else 1)' "$H/.gemini/settings.json" \+ && ok "gemini uninstall keeps every other key" || bad "gemini uninstall keeps every other key"+OUT="$(run --tool codex uninstall)"+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); c=[h["command"] for g in d["hooks"]["PreToolUse"] for h in g["hooks"]]; sys.exit(0 if c==["bash ~/other.sh"] else 1)' "$H/.codex/hooks.json" \+ && ok "codex uninstall keeps the other hook" || bad "codex uninstall keeps the other hook"++# 4b removing the most recently installed tool keeps the skill for the earlier one, in both orders+for pair in "codex gemini" "gemini codex"; do+ set -- $pair; fresh; run --tool "$1" >/dev/null; run --tool "$2" >/dev/null; run --tool "$2" uninstall >/dev/null+ run --tool "$1" doctor >/dev/null; RC=$?+ [ -f "$H/.agents/skills/app-store-compliance/SKILL.md" ] && [ "$RC" -eq 0 ] && grep -qx "$1" "$H/.agents/skills/app-store-compliance/.installed-by" \+ && ok "uninstalling $2 after $1 keeps the shared skill and $1 doctor passes" || bad "uninstalling $2 after $1 keeps the shared skill and $1 doctor passes (rc=$RC)"+done++# 4c an entry that names the guard but would never dispatch is caught by doctor and repaired by install+fresh; run --tool codex >/dev/null+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooks"]["PreToolUse"][0]["matcher"]="Read"; json.dump(d,open(p,"w"))' "$(cfg codex)"+run --tool codex doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "codex doctor fails when the guard sits on the Read matcher" || bad "codex doctor fails when the guard sits on the Read matcher (rc=$RC)"+run --tool codex >/dev/null; run --tool codex doctor >/dev/null; RC=$?+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); g=[g for g in d["hooks"]["PreToolUse"] if any("guard.sh" in h["command"] for h in g["hooks"])]; sys.exit(0 if [x["matcher"] for x in g]==["Bash"] else 1)' "$(cfg codex)" && [ "$RC" -eq 0 ] \+ && ok "codex install moves the guard back onto Bash and doctor then passes" || bad "codex install moves the guard back onto Bash and doctor then passes (rc=$RC)"+fresh; run --tool gemini >/dev/null+python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); h=d["hooks"]["BeforeTool"][0]["hooks"][0]; h["type"]="prompt"; h.pop("timeout"); json.dump(d,open(p,"w"))' "$(cfg gemini)"+run --tool gemini doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "gemini doctor fails on a wrong handler type and a missing timeout" || bad "gemini doctor fails on a wrong handler type and a missing timeout (rc=$RC)"+run --tool gemini >/dev/null; run --tool gemini doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && [ "$(count gemini)" = "1" ] && ok "gemini install repairs the handler once" || bad "gemini install repairs the handler once (rc=$RC entries=$(count gemini))"+fresh; run --tool kimi >/dev/null+python3 -c 'import sys; p=sys.argv[1]; t=open(p).read(); i=t.index("command = "); j=t.index("\n",i); open(p,"w").write(t[:i]+"command = \"bash /no/such/app-store-compliance-guard.sh\""+t[j:])' "$(cfg kimi)"+run --tool kimi doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "kimi doctor tests the command actually registered in config.toml" || bad "kimi doctor tests the command actually registered in config.toml (rc=$RC)"+run --tool kimi >/dev/null; run --tool kimi doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && [ "$(count kimi)" = "1" ] && ok "kimi install rewrites a broken block once" || bad "kimi install rewrites a broken block once (rc=$RC entries=$(count kimi))"++# 5 a config that is not valid JSON, or repeats a key, is never rewritten+for body in '{"hooks": [broken' '{"permissions":{"deny":["x"]},"permissions":{"allow":["x"]}}'; do+ fresh; mkdir -p "$H/.codex"; printf '%s' "$body" > "$H/.codex/hooks.json"+ OUT="$(run --tool codex)"; RC=$?+ [ "$RC" -ne 0 ] && [ "$(cat "$H/.codex/hooks.json")" = "$body" ] && echo "$OUT" | grep -q "Merge this into" && ok "an unsafe codex config is left untouched and a manual block is printed" || bad "an unsafe codex config is left untouched (rc=$RC)"+done++# 6 the installed guard finds the deadline list and the manifest validator in the shared skill+fresh; run --tool codex >/dev/null+APP="$WORK/app$RANDOM"; mkdir -p "$APP/App"; printf '<plist><dict></dict></plist>' > "$APP/App/Info.plist"; printf 'import UIKit\n' > "$APP/App/A.swift"+OUT="$(env HOME="$H" bash "$H/.codex/hooks/app-store-compliance-guard.sh" "$APP" 2>&1)"+echo "$OUT" | grep -q "Regulatory Compliance Deadline Status" && ok "the codex guard finds the deadline list in ~/.agents/skills" || bad "the codex guard finds the deadline list in ~/.agents/skills"++# 6b release-audit.py run from the shared skill finds the guard installed under the tool's own folder+fresh; run --tool codex >/dev/null+OUT="$(env -u APP_STORE_GUARD_PATH HOME="$H" python3 "$H/.agents/skills/app-store-compliance/scripts/release-audit.py" "$APP" 2>&1)"+echo "$OUT" | grep -qF "Guard. $H/.codex/hooks/app-store-compliance-guard.sh" && ok "release-audit in the shared skill finds the codex guard" || { bad "release-audit in the shared skill finds the codex guard"; echo "$OUT" | grep -i guard | head -3; }+run --tool gemini >/dev/null; run --tool codex uninstall >/dev/null+OUT="$(env -u APP_STORE_GUARD_PATH HOME="$H" python3 "$H/.agents/skills/app-store-compliance/scripts/release-audit.py" "$APP" 2>&1)"+echo "$OUT" | grep -qF "Guard. $H/.gemini/hooks/app-store-compliance-guard.sh" && ok "after codex is removed release-audit uses the gemini guard" || bad "after codex is removed release-audit uses the gemini guard"+rm -rf "$APP"++# 7 the audit command points at the installed paths, and the Gemini command is valid TOML+fresh; run --tool gemini >/dev/null; run --tool opencode >/dev/null+python3 -c 'import sys,tomllib; d=tomllib.load(open(sys.argv[1],"rb")); sys.exit(0 if d["description"] and "{{args}}" in d["prompt"] else 1)' "$H/.gemini/commands/app-store-audit.toml" && ok "the gemini command is valid TOML with {{args}}" || bad "the gemini command is valid TOML with {{args}}"+! grep -q "[~]/.claude" "$H/.gemini/commands/app-store-audit.toml" "$H/.config/opencode/commands/app-store-audit.md" && ok "the commands name no Claude Code path" || bad "the commands name no Claude Code path"++# 8 --tool all installs into every tool it finds, and only those+fresh; mkdir -p "$H/.codex" "$H/.cursor"+OUT="$(run --tool all)"; RC=$?+[ "$RC" -eq 0 ] && echo "$OUT" | grep -q "^Found. codex cursor$" && [ "$(count codex)" = "1" ] && [ "$(count cursor)" = "1" ] && [ ! -e "$H/.gemini" ] && [ ! -e "$H/.claude" ] \+ && ok "--tool all installs into the found tools only" || { bad "--tool all installs into the found tools only (rc=$RC)"; echo "$OUT" | head -5; }+fresh; OUT="$(run --tool all)"; RC=$?+[ "$RC" -eq 1 ] && echo "$OUT" | grep -q "No supported AI coding tool" && ok "--tool all with no tool says so" || bad "--tool all with no tool says so (rc=$RC)"++# 8b Qwen reads $QWEN_HOME/settings.json when QWEN_HOME is set, so install, doctor, uninstall and --tool all follow it+fresh; Q="$WORK/qhome$RANDOM"; mkdir -p "$Q"+qrun() { env -u CODEX_HOME -u XDG_CONFIG_HOME -u CLAUDE_CONFIG_DIR -u CLAUDE_PROJECT_DIR QWEN_HOME="$Q" HOME="$H" bash "$INSTALL" "$@" 2>&1; }+OUT="$(qrun --tool qwen)"; RC=$?+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if any("guard.sh" in h["command"] for g in d["hooks"]["PreToolUse"] for h in g["hooks"]) else 1)' "$Q/settings.json" 2>/dev/null && [ "$RC" -eq 0 ] && [ ! -e "$H/.qwen/settings.json" ] \+ && ok "qwen installs into \$QWEN_HOME/settings.json" || bad "qwen installs into \$QWEN_HOME/settings.json (rc=$RC)"+qrun --tool qwen doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && ok "qwen doctor checks \$QWEN_HOME" || bad "qwen doctor checks \$QWEN_HOME (rc=$RC)"+qrun --tool qwen uninstall >/dev/null+! grep -q "app-store-compliance-guard.sh" "$Q/settings.json" 2>/dev/null && ok "qwen uninstall edits \$QWEN_HOME/settings.json" || bad "qwen uninstall edits \$QWEN_HOME/settings.json"+fresh; Q="$WORK/qhome$RANDOM"; mkdir -p "$Q"+OUT="$(qrun --tool all --dry-run)"; RC=$?+echo "$OUT" | grep -q "^Found. qwen$" && ok "--tool all finds qwen through \$QWEN_HOME" || bad "--tool all finds qwen through \$QWEN_HOME (rc=$RC)"++# 8c two installs of one tool, in two config folders, each own the shared skill+fresh; CA="$WORK/codexa$RANDOM"; CB="$WORK/codexb$RANDOM"; mkdir -p "$CA" "$CB"+crun() { local c="$1"; shift; env -u QWEN_HOME -u XDG_CONFIG_HOME -u CLAUDE_CONFIG_DIR -u CLAUDE_PROJECT_DIR CODEX_HOME="$c" HOME="$H" bash "$INSTALL" "$@" 2>&1; }+crun "$CA" --tool codex >/dev/null; crun "$CB" --tool codex >/dev/null; crun "$CB" --tool codex uninstall >/dev/null+[ -f "$H/.agents/skills/app-store-compliance/SKILL.md" ] && grep -qF "$CA/hooks/app-store-compliance-guard.sh" "$H/.agents/skills/app-store-compliance/.guards" \+ && ok "uninstalling one codex folder keeps the shared skill for the other" || bad "uninstalling one codex folder keeps the shared skill for the other"+crun "$CA" --tool codex doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && ok "the remaining codex folder still passes doctor" || bad "the remaining codex folder still passes doctor (rc=$RC)"+crun "$CA" --tool codex uninstall >/dev/null+[ ! -e "$H/.agents/skills/app-store-compliance" ] && ok "uninstalling the last codex folder removes the shared skill" || bad "uninstalling the last codex folder removes the shared skill"+# 8d --tool all expands a QWEN_HOME written with a Windows tilde, as the installer does+fresh; mkdir -p "$H/qwen-config"+OUT="$(env -u CODEX_HOME -u XDG_CONFIG_HOME -u CLAUDE_CONFIG_DIR -u CLAUDE_PROJECT_DIR QWEN_HOME='~\qwen-config' HOME="$H" bash "$INSTALL" --tool all --dry-run 2>&1)"+echo "$OUT" | grep -q "^Found. qwen$" && ok "--tool all finds a QWEN_HOME written as ~\folder" || bad "--tool all finds a QWEN_HOME written as ~\folder"++# 8e Kimi keeps CRLF line endings byte for byte through install and uninstall+fresh; mkdir -p "$H/.kimi-code"; printf 'default_model = "k2"\r\n\r\n' > "$H/.kimi-code/config.toml"; cp "$H/.kimi-code/config.toml" "$WORK/kimi-crlf.toml"+run --tool kimi >/dev/null; run --tool kimi uninstall >/dev/null+cmp -s "$H/.kimi-code/config.toml" "$WORK/kimi-crlf.toml" && ok "kimi uninstall keeps CRLF line endings" || bad "kimi uninstall keeps CRLF line endings"+# 8f the OpenCode plugin never lets a submit through when the guard cannot run+fresh; mkdir -p "$H/.config/opencode"; run --tool opencode >/dev/null+rm -f "$(gdir opencode)/app-store-compliance-guard.sh"+if command -v node >/dev/null 2>&1; then+ RES="$(node --input-type=module -e '+const m = await import(process.argv[1]);+const p = await m.AppStoreCompliance({ directory: process.argv[2] });+const run = async (c) => { try { await p["tool.execute.before"]({ tool: "bash" }, { args: { command: c } }); return "allowed" } catch (e) { return "thrown" } };+console.log((await run("fast" + "lane deliver")) + " " + (await run("f\\ast" + "lane deliver")) + " " + (await run("ea" + "s\tsubmit")) + " " + (await run("ls -la")));+' "$(cfg opencode)" "$H" 2>/dev/null)"+ [ "$RES" = "thrown thrown thrown allowed" ] && ok "opencode refuses a submit when the guard cannot run and allows other commands" || bad "opencode refuses a submit when the guard cannot run and allows other commands (got $RES)"+else ok "opencode guard-failure check skipped, node not installed"; fi+# 8j OpenCode loads both plugin folders, and a call is still checked once+fresh; mkdir -p "$H/.config/opencode"; run --tool opencode >/dev/null+printf '#!/usr/bin/env bash\necho x >> "%s/count"\nexit 0\n' "$H" > "$(gdir opencode)/app-store-compliance-guard.sh"+if command -v node >/dev/null 2>&1; then+ node --input-type=module -e '+const a = await (await import(process.argv[1])).AppStoreCompliance({ directory: process.argv[3] });+const b = await (await import(process.argv[2])).AppStoreCompliance({ directory: process.argv[3] });+const out = { args: { command: "ls" } };+await a["tool.execute.before"]({ tool: "bash" }, out); await b["tool.execute.before"]({ tool: "bash" }, out);+' "$(cfg opencode)" "$H/.config/opencode/plugin/app-store-compliance.js" "$H" 2>/dev/null+ [ "$(wc -l < "$H/count" | tr -d ' ')" = "1" ] && ok "opencode checks a call once with both plugin folders loaded" || bad "opencode checks a call once with both plugin folders loaded ($(wc -l < "$H/count" 2>/dev/null))"+else ok "opencode double-load check skipped, node not installed"; fi+# 8h a CRLF Kimi config reinstalls without a rewrite+fresh; mkdir -p "$H/.kimi-code"; printf 'default_model = "k2"\r\n' > "$H/.kimi-code/config.toml"+run --tool kimi >/dev/null; N1="$(find "$H/.kimi-code" -maxdepth 1 -name '*bak*' | wc -l | tr -d ' ')"; OUT="$(run --tool kimi)"; N2="$(find "$H/.kimi-code" -maxdepth 1 -name '*bak*' | wc -l | tr -d ' ')"+[ "$N1" = "$N2" ] && echo "$OUT" | grep -q 'already registered' && ok "kimi a second run on a CRLF config changes nothing" || bad "kimi a second run on a CRLF config changes nothing ($N1 $N2)"+# 8i without node the OpenCode install never says verified+fresh; mkdir -p "$H/.config/opencode"+NONODE="$WORK/nonode$RANDOM"; mkdir -p "$NONODE"; for b in bash sh python3 grep sed awk cat cp mv rm mkdir chmod dirname basename tr head tail find date ls env printf mktemp uname cmp wc sort; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$NONODE/$b"; done+OUT="$(env -u QWEN_HOME -u KIMI_CODE_HOME -u COPILOT_HOME -u CODEX_HOME -u XDG_CONFIG_HOME -u CLAUDE_CONFIG_DIR -u CLAUDE_PROJECT_DIR PATH="$NONODE" HOME="$H" bash "$INSTALL" --tool opencode 2>&1)"+echo "$OUT" | grep -q 'not fully verified' && ! echo "$OUT" | grep -q '^Install verified' && ok "opencode without node says not fully verified" || bad "opencode without node says not fully verified"+# 8g a non-Claude doctor says when the checkout is newer than the install+fresh; mkdir -p "$H/.codex"; run --tool codex >/dev/null; printf '1.0.0' > "$H/.agents/skills/app-store-compliance/VERSION"+OUT="$(run --tool codex doctor)"+echo "$OUT" | grep -q "this checkout is version" && ok "codex doctor says the checkout is newer" || bad "codex doctor says the checkout is newer"++# 9 a home folder with an apostrophe still verifies+H="$WORK/O'Reilly home"; mkdir -p "$H"+OUT="$(run --tool cursor)"; RC=$?+[ "$RC" -eq 0 ] && [ "$(count cursor)" = "1" ] && ok "a home with an apostrophe installs and verifies" || bad "a home with an apostrophe installs and verifies (rc=$RC)"++# 10 bad input+fresh; OUT="$(run --tool vim)"; RC=$?+[ "$RC" -eq 2 ] && echo "$OUT" | grep -q "Unknown tool" && ok "an unknown tool exits 2" || bad "an unknown tool exits 2 (rc=$RC)"+OUT="$(run --tool)"; RC=$?+[ "$RC" -eq 2 ] && ok "--tool with no name exits 2" || bad "--tool with no name exits 2 (rc=$RC)"+OUT="$(run --tool gemini --dry-run)"; RC=$?+[ "$RC" -eq 0 ] && [ ! -e "$H/.gemini" ] && [ ! -e "$H/.agents" ] && ok "--dry-run writes nothing" || bad "--dry-run writes nothing (rc=$RC)"++echo ""+echo "install-harness-test: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ]diff --git a/scripts/install-test.sh b/scripts/install-test.shindex 3edcf4b..716ba9b 100755--- a/scripts/install-test.sh+++ b/scripts/install-test.sh@@ -114,6 +114,12 @@ fresh; run >/dev/nullpython3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["hooks"]["PreToolUse"][0]["hooks"][0]["command"]="bash /no/such/app-store-compliance-guard.sh"; json.dump(d,open(p,"w"))' "$C/settings.json"run doctor >/dev/null; RC=$?[ "$RC" -eq 1 ] && ok "doctor fails when the registered command cannot run" || bad "doctor fails when the registered command cannot run (rc=$RC)"+for patch in 'h["type"]="prompt"' 'h["timeout"]=1'; do+ fresh; run >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); h=d["hooks"]["PreToolUse"][0]["hooks"][0]; exec(sys.argv[2]); json.dump(d,open(p,"w"))' "$C/settings.json" "$patch"+ run doctor >/dev/null; RC=$?+ [ "$RC" -eq 1 ] && ok "doctor fails for a hook Claude would not run as intended. $patch" || bad "doctor fails for a hook Claude would not run as intended. $patch (rc=$RC)"+done# 15 a settings.json with a repeated key is ambiguous and is never rewrittenfresh@@ -137,6 +143,12 @@ if command -v jq >/dev/null 2>&1; thenOUT="$(PATH="$SHIM" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" 2>&1)"; RC=$?PATH="$SHIM" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" >/dev/null 2>&1[ "$RC" -eq 0 ] && echo "$OUT" | grep -q "^Install verified\." && [ "$(hooks)" = "1" ] && grep -q '"opus"' "$C/settings.json" && ok "with jq only the hook is merged once and verified" || bad "with jq only the hook is merged once and verified (rc=$RC entries=$(hooks))"+ # jq keeps only the last of two repeated keys, so a repeated key must stop the jq path too+ for body in '{"permissions":{"deny":["Bash(*)"]},"permissions":{"allow":["Bash(*)"]}}' '{"hooks":{"PreToolUse":[]},"a":{"b":1,"b":2}}'; do+ fresh; printf '%s' "$body" > "$C/settings.json"+ OUT="$(PATH="$SHIM" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" 2>&1)"; RC=$?+ [ "$RC" -eq 1 ] && [ "$(cat "$C/settings.json")" = "$body" ] && echo "$OUT" | grep -q '"PreToolUse"' && ok "with jq only a repeated key leaves settings.json untouched" || bad "with jq only a repeated key leaves settings.json untouched (rc=$RC)"+ donerm -rf "$SHIM"fi@@ -193,6 +205,81 @@ run doctor >/dev/null; RC=$?run uninstall >/dev/null[ "$(hooks)" = "0" ] && ok "uninstall removes the hook for a folder with an apostrophe" || bad "uninstall removes the hook for a folder with an apostrophe (entries=$(hooks))"+# 24 the installed version is recorded and reported, so a user can tell what they run+fresh+run >/dev/null+V="$(cat VERSION 2>/dev/null)"+[ -n "$V" ] && [ "$(cat "$C/skills/app-store-compliance/VERSION" 2>/dev/null)" = "$V" ] && ok "install records the playbook version" || bad "install records the playbook version (repo=$V)"+OUT="$(run doctor)"; echo "$OUT" | grep -q "^ ok version $V" && ok "doctor prints the installed version" || bad "doctor prints the installed version"+[ "$(run --version)" = "app-store-compliance $V" ] && ok "--version prints the checkout version" || bad "--version prints the checkout version"++# 25 on Windows (Git Bash, MSYS, Cygwin) the hook also covers PowerShell, and doctor proves a PowerShell call is blocked+fresh+OUT="$(ASC_UNAME=MINGW64_NT-10.0 run)"; RC=$?+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); m=[e["matcher"] for e in d["hooks"]["PreToolUse"]]; sys.exit(0 if m==["Bash|PowerShell"] else 1)' "$C/settings.json" && [ "$RC" -eq 0 ] && ok "Git Bash registers Bash|PowerShell" || bad "Git Bash registers Bash|PowerShell (rc=$RC)"+echo "$OUT" | grep -q "blocks a submit command run through PowerShell" && ok "doctor proves the PowerShell path on Windows" || bad "doctor proves the PowerShell path on Windows"+fresh; run >/dev/null+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); m=[e["matcher"] for e in d["hooks"]["PreToolUse"]]; sys.exit(0 if m==["Bash"] else 1)' "$C/settings.json" && ok "macOS and Linux keep the Bash matcher" || bad "macOS and Linux keep the Bash matcher"++# 26 a Bash-only entry written by an older install on Windows is upgraded to Bash|PowerShell, and doctor checks the matcher+fresh; run >/dev/null+ASC_UNAME=MINGW64_NT-10.0 run doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "Windows doctor fails while the matcher covers only Bash" || bad "Windows doctor fails while the matcher covers only Bash (rc=$RC)"+OUT="$(ASC_UNAME=MINGW64_NT-10.0 run)"; RC=$?+python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); m=[e["matcher"] for e in d["hooks"]["PreToolUse"]]; sys.exit(0 if m==["Bash|PowerShell"] else 1)' "$C/settings.json" && [ "$(hooks)" = "1" ] && [ "$RC" -eq 0 ] \+ && ok "a Windows reinstall upgrades the owned Bash matcher once" || bad "a Windows reinstall upgrades the owned Bash matcher once (rc=$RC entries=$(hooks))"+ASC_UNAME=MINGW64_NT-10.0 run doctor >/dev/null; RC=$?+[ "$RC" -eq 0 ] && ok "Windows doctor passes after the upgrade" || bad "Windows doctor passes after the upgrade (rc=$RC)"+if command -v jq >/dev/null 2>&1; then+ fresh; run >/dev/null+ SHIM="$(mktemp -d)"+ for b in bash cp rm mkdir chmod cat grep sed awk find xargs tr head tail mktemp printf wc sort uniq cut dirname basename date cmp mv ls env plutil xmllint file od comm tee sleep expr touch jq; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$SHIM/$b"; done+ OUT="$(ASC_UNAME=MINGW64_NT-10.0 PATH="$SHIM" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" 2>&1)"; RC=$?+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); m=[e["matcher"] for e in d["hooks"]["PreToolUse"]]; sys.exit(0 if m==["Bash|PowerShell"] else 1)' "$C/settings.json" && [ "$(hooks)" = "1" ] && [ "$RC" -eq 0 ] \+ && ok "with jq only a Windows reinstall upgrades the matcher once" || bad "with jq only a Windows reinstall upgrades the matcher once (rc=$RC entries=$(hooks))"+ # an old Bash-only entry is still removed by a jq-only Windows uninstall+ fresh; run >/dev/null+ ASC_UNAME=MINGW64_NT-10.0 PATH="$SHIM" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" uninstall >/dev/null 2>&1; RC=$?+ [ "$(hooks)" = "0" ] && [ "$RC" -eq 0 ] && ok "with jq only a Windows uninstall removes an old Bash-only entry" || bad "with jq only a Windows uninstall removes an old Bash-only entry (rc=$RC entries=$(hooks))"+ rm -rf "$SHIM"+fi++# an async guard runs in the background and cannot block, so doctor fails and install repairs it, with python3 and with jq only+mkasync() { python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); [h.__setitem__("async", True) for e in d["hooks"]["PreToolUse"] for h in e["hooks"] if "guard.sh" in h["command"]]; json.dump(d, open(p,"w"))' "$C/settings.json"; }+noasync() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if all(not h.get("async") for e in d["hooks"]["PreToolUse"] for h in e["hooks"] if "guard.sh" in h["command"]) else 1)' "$C/settings.json"; }+fresh; run >/dev/null; mkasync+run doctor >/dev/null; RC=$?+[ "$RC" -eq 1 ] && ok "doctor fails on an async guard hook" || bad "doctor fails on an async guard hook (rc=$RC)"+run >/dev/null; noasync && [ "$(hooks)" = "1" ] && ok "install repairs an async guard hook" || bad "install repairs an async guard hook"+if command -v jq >/dev/null 2>&1; then+ fresh; run >/dev/null; mkasync+ JQS="$(mktemp -d)"+ for b in bash cp rm mkdir chmod cat grep sed awk find xargs tr head tail mktemp printf wc sort uniq cut dirname basename date cmp mv ls env jq plutil xmllint; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$JQS/$b"; done+ PATH="$JQS" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" doctor >/dev/null 2>&1; RC=$?+ [ "$RC" -eq 1 ] && ok "jq-only doctor fails on an async guard hook" || bad "jq-only doctor fails on an async guard hook (rc=$RC)"+ PATH="$JQS" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" >/dev/null 2>&1+ noasync && [ "$(hooks)" = "1" ] && ok "jq-only install repairs an async guard hook" || bad "jq-only install repairs an async guard hook"+ rm -rf "$JQS"+fi++# a jq-only install repairs an owned hook whose timeout is too short or whose type is not a command+if command -v jq >/dev/null 2>&1; then+ for fix in 'h["timeout"]=1' 'h["type"]="prompt"'; do+ fresh; run >/dev/null+ python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p))+for e in d["hooks"]["PreToolUse"]:+ for h in e["hooks"]:+ if "guard.sh" in h["command"]: '"$fix"'+json.dump(d, open(p,"w"))' "$C/settings.json"+ JQS="$(mktemp -d)"+ for b in bash cp rm mkdir chmod cat grep sed awk find xargs tr head tail mktemp printf wc sort uniq cut dirname basename date cmp mv ls env jq plutil xmllint; do p="$(command -v "$b" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$JQS/$b"; done+ PATH="$JQS" CLAUDE_CONFIG_DIR="$C" bash "$INSTALL" >/dev/null 2>&1+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); hs=[h for e in d["hooks"]["PreToolUse"] for h in e["hooks"] if "guard.sh" in h["command"]]; sys.exit(0 if len(hs)==1 and hs[0].get("type","command")=="command" and hs[0].get("timeout",600)>=120 else 1)' "$C/settings.json" \+ && ok "jq-only install repairs an owned hook ($fix)" || bad "jq-only install repairs an owned hook ($fix)"+ rm -rf "$JQS"+ done+fi+echo ""echo "install-test: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/install.sh b/scripts/install.shindex 738b7da..8ba522b 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash-# One command setup for Claude Code. Installs the guard, the skill and the slash command, registers-# the hook, then proves the guard blocks a bad app. Usage: install.sh [install|doctor|uninstall] [--dry-run]+# One command setup for Claude Code and, with --tool, eleven other AI coding tools. Installs the guard,+# skill and command, registers the hook, then proves it blocks a bad app. Run with --help for usage.set -uo pipefailREPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"@@ -16,6 +16,12 @@ SKILL="$CONF/skills/app-store-compliance"CMD_FILE="$CONF/commands/app-store-audit.md"SETTINGS="$CONF/settings.json"PAYLOAD_DIRS="docs data references templates scripts"+# Claude Code on Windows may run commands through PowerShell, so the hook covers both there.+case "${ASC_UNAME:-$(uname -s 2>/dev/null)}" in+ MINGW*|MSYS*|CYGWIN*) MATCHER="Bash|PowerShell" ;;+ *) MATCHER="Bash" ;;+esac+export ASC_MATCHER="$MATCHER"# shellcheck disable=SC2088if [ "$CONF" = "${HOME:-}/.claude" ]; then SHOWN='~/.claude'; else SHOWN="$CONF"; fi@@ -26,15 +32,68 @@ elseHOOK_CMD="bash '$(printf '%s' "$GUARD" | sed "s/'/'\\\\''/g")'"fi-MODE="install"; DRY=0-for arg in "$@"; do- case "$arg" in- install|doctor|uninstall) MODE="$arg" ;;+MODE="install"; DRY=0; TOOL="claude"; REPO_DIR=""+TOOL_NAMES="claude|codex|gemini|opencode|cursor|copilot|copilot-repo|grok|qwen|kimi|droid|auggie|windsurf|all"+USAGE="Usage. install.sh [install|doctor|uninstall] [--tool $TOOL_NAMES] [--repo DIR] [--dry-run] [--version]"+while [ "$#" -gt 0 ]; do+ case "$1" in+ install|doctor|uninstall) MODE="$1" ;;--dry-run) DRY=1 ;;-h|--help) MODE="help" ;;- *) echo "Unknown argument. $arg" >&2; echo "Usage. install.sh [install|doctor|uninstall] [--dry-run]" >&2; exit 2 ;;+ --version) MODE="version" ;;+ --tool=*) TOOL="${1#--tool=}" ;;+ --tool) [ "$#" -ge 2 ] || { echo "--tool needs a name." >&2; echo "$USAGE" >&2; exit 2; }; TOOL="$2"; shift ;;+ --repo=*) REPO_DIR="${1#--repo=}" ;;+ --repo) [ "$#" -ge 2 ] || { echo "--repo needs a folder." >&2; exit 2; }; REPO_DIR="$2"; shift ;;+ *) echo "Unknown argument. $1" >&2; echo "$USAGE" >&2; exit 2 ;;esac+ shiftdone+case "$TOOL" in+ claude|codex|gemini|opencode|cursor|copilot|copilot-repo|grok|qwen|kimi|droid|auggie|windsurf|all) ;;+ *) echo "Unknown tool. $TOOL" >&2; echo "$USAGE" >&2; exit 2 ;;+esac++# Every other tool is installed by install_harness.py, which merges that tool's own config file.+run_harness() {+ if ! command -v python3 >/dev/null 2>&1; then+ echo "python3 is needed to install for $1. Install python3, or follow the manual steps in the README." >&2+ return 1+ fi+ local args=("$1" "$MODE"); [ "$DRY" -eq 1 ] && args+=(--dry-run); [ -n "$REPO_DIR" ] && args+=(--repo "$REPO_DIR")+ python3 "$REPO/scripts/install_harness.py" "${args[@]}"+}+if [ "$TOOL" = "all" ] && [ "$MODE" != "help" ] && [ "$MODE" != "version" ]; then+ found=""; rc_all=0+ [ -d "$CONF" ] && found="claude"+ [ -d "${CODEX_HOME:-${HOME:-}/.codex}" ] && found="$found codex"+ [ -d "${HOME:-}/.gemini" ] && found="$found gemini"+ [ -d "${XDG_CONFIG_HOME:-${HOME:-}/.config}/opencode" ] && found="$found opencode"+ [ -d "${HOME:-}/.cursor" ] && found="$found cursor"+ CDIR="${COPILOT_HOME:-${HOME:-}/.copilot}"; case "$CDIR" in [~]|[~]/*|[~]\\*) CDIR="${CDIR#\~}"; CDIR="${HOME:-}/${CDIR#?}" ;; esac+ [ -d "$CDIR" ] && found="$found copilot"+ [ -d "${HOME:-}/.grok" ] && found="$found grok"+ QDIR="${QWEN_HOME:-${HOME:-}/.qwen}"; case "$QDIR" in [~]|[~]/*|[~]\\*) QDIR="${QDIR#\~}"; QDIR="${HOME:-}/${QDIR#?}" ;; esac+ [ -d "$QDIR" ] && found="$found qwen"+ KDIR="${KIMI_CODE_HOME:-${HOME:-}/.kimi-code}"; case "$KDIR" in [~]|[~]/*|[~]\\*) KDIR="${KDIR#\~}"; KDIR="${HOME:-}/${KDIR#?}" ;; esac+ [ -d "$KDIR" ] && found="$found kimi"+ [ -d "${HOME:-}/.factory" ] && found="$found droid"+ [ -d "${HOME:-}/.augment" ] && found="$found auggie"+ [ -d "${HOME:-}/.codeium/windsurf" ] && found="$found windsurf"+ [ -z "$found" ] && { echo "No supported AI coding tool found in your home folder. Pass --tool with one name."; exit 1; }+ echo "Found.$found"+ for t in $found; do+ echo ""; echo "== $t =="+ flags=("$MODE"); [ "$DRY" -eq 1 ] && flags+=(--dry-run)+ bash "$0" --tool "$t" "${flags[@]}" || rc_all=1+ done+ echo ""+ if [ "$rc_all" -eq 0 ]; then echo "All tools done."; else echo "At least one tool reported a problem above."; fi+ exit "$rc_all"+fi+if [ "$TOOL" != "claude" ] && [ "$MODE" != "help" ] && [ "$MODE" != "version" ]; then+ run_harness "$TOOL"; exit $?+fihave() { command -v "$1" >/dev/null 2>&1 && "$@" >/dev/null 2>&1; }say() { printf '%s\n' "$*"; }@@ -52,7 +111,7 @@ manual_block() {"hooks": {"PreToolUse": [{- "matcher": "Bash",+ "matcher": "$MATCHER","hooks": [{ "type": "command", "command": "$HOOK_CMD", "timeout": 120 }]@@ -112,14 +171,21 @@ def ours(h):return c == cmd or any(c in ("bash " + s, "bash '" + s + "'", 'bash "' + s + '"') for s in spots)-def fires(e, h):+TOOLS = ["Bash"] + (["PowerShell"] if "PowerShell" in os.environ.get("ASC_MATCHER", "") else [])+++def hits(m, tool):+ try:+ return m in ("", "*") or re.fullmatch(m, tool) is not None+ except re.error:+ return False+++def fires(e, h, tools=("Bash",)):# Only an entry Claude Code would run for a Bash call counts. Wrong matcher or a commented name does not.m = e.get("matcher", "")c = str(h.get("command", "")).strip()- try:- on_bash = m in ("", "*") or re.fullmatch(m, "Bash") is not None- except re.error:- on_bash = False+ on_bash = all(hits(m, t) for t in tools)runs = c.startswith("bash ") and "#" not in c and c.rstrip("'\"").endswith(name)return ours(h) and on_bash and runs and h.get("type", "command") == "command"@@ -129,6 +195,19 @@ if action == "add":found = [h for e in pre for h in e.get("hooks", []) if fires(e, h)]else:found = [h for e in pre for h in e.get("hooks", []) if ours(h)]+if action == "add" and found and len(TOOLS) > 1:+ # On Windows an owned entry must also match PowerShell. A group holding only ours is widened in place,+ # otherwise ours moves to its own group so another hook's matcher is never changed.+ for e in list(pre):+ mine = [h for h in e.get("hooks", []) if fires(e, h) and not fires(e, h, TOOLS)]+ if not mine:+ continue+ if len(mine) == len(e.get("hooks", [])):+ e["matcher"] = os.environ.get("ASC_MATCHER", "Bash")+ else:+ e["hooks"] = [h for h in e["hooks"] if h not in mine]+ pre.append({"matcher": os.environ.get("ASC_MATCHER", "Bash"), "hooks": mine})+ changed = Trueif action == "add":if found:for h in found:@@ -136,9 +215,12 @@ if action == "add":if not isinstance(t, (int, float)) or t < 120:h["timeout"] = 120changed = True+ if h.get("async") not in (None, False):+ h.pop("async", None)+ changed = Trueelse:pre.append(- {"matcher": "Bash", "hooks": [{"type": "command", "command": cmd, "timeout": 120}]}+ {"matcher": os.environ.get("ASC_MATCHER", "Bash"), "hooks": [{"type": "command", "command": cmd, "timeout": 120}]})hooks["PreToolUse"] = predata["hooks"] = hooks@@ -179,17 +261,22 @@ PYif [ -n "$cur" ]; thenjq -e 'type == "object" and ((.hooks // {}) | type == "object") and ((.hooks.PreToolUse // []) | type == "array") and ((.hooks.PreToolUse // []) | all(type == "object" and ((.hooks // []) | type == "array")))' "$cur" >/dev/null 2>&1 || return 4[ -w "$cur" ] || return 6+ # --stream reads every key as written, a parse keeps only the last of a repeated key. Unequal counts mean a repeat.+ [ "$(jq -c --stream . "$cur" 2>/dev/null | wc -l)" -eq "$(jq -c tostream "$cur" 2>/dev/null | wc -l)" ] || return 4filocal present=1- [ -n "$cur" ] && jq -e --arg hc "$HOOK_CMD" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '[.hooks.PreToolUse[]? | select((.matcher // "") == "Bash" or (.matcher // "") == "" or .matcher == "*") | .hooks[]?.command? // "" | tostring | select(startswith("bash ") and (. as $c | $c == $hc or ([$g, $t] | any(. as $s | $c == "bash " + $s or $c == "bash \u0027" + $s + "\u0027" or $c == "bash \"" + $s + "\""))) and (contains("#") | not))] | length > 0' "$cur" >/dev/null 2>&1 && present=0+ [ -n "$cur" ] && jq -e --arg m "$MATCHER" --arg hc "$HOOK_CMD" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '[.hooks.PreToolUse[]? | select((.matcher // "") == $m or (.matcher // "") == "" or .matcher == "*") | .hooks[]? | select(type == "object" and ((.async // false) == false) and ((.type // "command") == "command") and (((.timeout // 600) | numbers) >= 120)) | .command? // "" | tostring | select(startswith("bash ") and (. as $c | $c == $hc or ([$g, $t] | any(. as $s | $c == "bash " + $s or $c == "bash \u0027" + $s + "\u0027" or $c == "bash \"" + $s + "\""))) and (contains("#") | not))] | length > 0' "$cur" >/dev/null 2>&1 && present=0if [ "$action" = "add" ]; then[ "$present" -eq 0 ] && return 3mkdir -p "$CONF"; tmp="$(mktemp "$CONF/.settings-XXXXXX")" || return 4if [ -n "$cur" ]; then cp -p "$cur" "$SETTINGS.bak-$(date +%Y%m%d-%H%M%S)"; else cur="/dev/null"; fiif [ "$cur" = "/dev/null" ]; then printf '{}' > "$tmp.in"; cur="$tmp.in"; fi- jq --arg c "$HOOK_CMD" '.hooks.PreToolUse = ((.hooks.PreToolUse // []) + [{matcher: "Bash", hooks: [{type: "command", command: $c, timeout: 120}]}])' "$cur" > "$tmp" || { rm -f "$tmp" "$tmp.in"; return 4; }+ # An owned entry on a narrower matcher is dropped first, so the widened one never duplicates it.+ jq --arg c "$HOOK_CMD" --arg m "$MATCHER" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '.hooks.PreToolUse = (((.hooks.PreToolUse // []) | map(.hooks |= map(select((.command? // "" | tostring | (. as $x | $x == $c or ([$g, $t] | any(. as $s | $x == "bash " + $s or $x == "bash \u0027" + $s + "\u0027" or $x == "bash \"" + $s + "\"")))) | not)) | select((.hooks | length) > 0))) + [{matcher: $m, hooks: [{type: "command", command: $c, timeout: 120}]}])' "$cur" > "$tmp" || { rm -f "$tmp" "$tmp.in"; return 4; }rm -f "$tmp.in"; mv "$tmp" "$SETTINGS"; return 0fi+ # Removal owns its handler under any matcher, so an older Bash-only entry is removed too.+ [ -n "$cur" ] && jq -e --arg hc "$HOOK_CMD" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '[.hooks.PreToolUse[]? | .hooks[]?.command? // "" | tostring | select(. as $c | $c == $hc or ([$g, $t] | any(. as $s | $c == "bash " + $s or $c == "bash \u0027" + $s + "\u0027" or $c == "bash \"" + $s + "\"")))] | length > 0' "$cur" >/dev/null 2>&1 && present=0[ "$present" -ne 0 ] && return 3tmp="$(mktemp "$CONF/.settings-XXXXXX")" || return 4cp -p "$cur" "$SETTINGS.bak-$(date +%Y%m%d-%H%M%S)"@@ -203,7 +290,7 @@ PYregistered_cmd() {[ -f "$SETTINGS" ] || return 0if have python3 -c pass; then- python3 -c 'import json,re,sys+ python3 -c 'import json,os,re,systry: d=json.load(open(sys.argv[1]))except Exception: sys.exit(0)hc=sys.argv[2]@@ -212,17 +299,22 @@ n+=[h+s[2:] for s in list(n) if s.startswith("~/") for h in ("$HOME/","${HOME}/"for e in d.get("hooks",{}).get("PreToolUse",[]):if not isinstance(e,dict): continuem=e.get("matcher","")- try: ok=m in ("","*") or re.fullmatch(m,"Bash") is not None+ tools=["Bash"]+(["PowerShell"] if "PowerShell" in os.environ.get("ASC_MATCHER","") else [])+ try: ok=all(m in ("","*") or re.fullmatch(m,t) is not None for t in tools)except re.error: ok=Falseif not ok: continuefor h in e.get("hooks",[]):- c=str(h.get("command","")) if isinstance(h,dict) else ""+ if not isinstance(h,dict) or h.get("type","command")!="command": continue+ t=h.get("timeout",600)+ if isinstance(t,bool) or not isinstance(t,(int,float)) or t<30: continue+ if h.get("async") not in (None,False): continue+ c=str(h.get("command",""))if (c.strip()==hc or any(c.strip() in ("bash " + s, "bash \"" + s + "\"", "bash \u0027" + s + "\u0027") for s in n)) and "#" not in c and c.strip().startswith("bash "):print(c); sys.exit(0)' "$SETTINGS" "$HOOK_CMD" "$GUARD" "$SHOWN/hooks/$GUARD_NAME" 2>/dev/nullreturn 0fiif have jq -n true; then- jq -r --arg hc "$HOOK_CMD" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '[.hooks.PreToolUse[]? | select((.matcher // "") == "Bash" or (.matcher // "") == "" or .matcher == "*") | .hooks[]?.command? // "" | tostring | select(startswith("bash ") and (. as $c | $c == $hc or ([$g, $t] | any(. as $s | $c == "bash " + $s or $c == "bash \u0027" + $s + "\u0027" or $c == "bash \"" + $s + "\""))) and (contains("#") | not))] | first // empty' "$SETTINGS" 2>/dev/null+ jq -r --arg m "$MATCHER" --arg hc "$HOOK_CMD" --arg g "$GUARD" --arg t "$SHOWN/hooks/$GUARD_NAME" '[.hooks.PreToolUse[]? | select((.matcher // "") == $m or (.matcher // "") == "" or .matcher == "*") | .hooks[]? | select(type == "object" and (.type // "command") == "command" and ((.async // false) == false) and (((.timeout // 600) | numbers) >= 30)) | .command? // "" | tostring | select(startswith("bash ") and (. as $c | $c == $hc or ([$g, $t] | any(. as $s | $c == "bash " + $s or $c == "bash \u0027" + $s + "\u0027" or $c == "bash \"" + $s + "\""))) and (contains("#") | not))] | first // empty' "$SETTINGS" 2>/dev/nullreturn 0figrep -qF "$SHOWN/hooks/$GUARD_NAME" "$SETTINGS" 2>/dev/null && printf '%s\n' "$HOOK_CMD"@@ -236,6 +328,12 @@ verify() {if [ -f "$GUARD" ] && [ -f "$GUARD_SRC" ] && ! cmp -s "$GUARD" "$GUARD_SRC"; thenwarn "installed guard differs from this checkout. Run install.sh again to update it."fi+ if [ -f "$SKILL/VERSION" ]; then+ good "version $(cat "$SKILL/VERSION")"+ if [ -f "$REPO/VERSION" ] && ! cmp -s "$SKILL/VERSION" "$REPO/VERSION"; then+ warn "this checkout is version $(cat "$REPO/VERSION"). Run install.sh again to update."+ fi+ filocal missing="" pfor p in SKILL.md data/rejection-patterns.json data/regulatory-deadlines.json docs/PRE-SUBMISSION-CHECKLIST.md references scripts/deadline-checker.py scripts/validate-privacy-manifest.py templates .citation-allowlist; do[ -e "$SKILL/$p" ] || missing="$missing $p"@@ -258,6 +356,10 @@ verify() {if [ "$rc" -eq 2 ]; then good "the registered hook command blocks a submit command"; else fail "the registered hook command did not block a submit command (exit $rc, expected 2). Command. $reg"; fiout="$( cd "$fx" && printf '{"tool_name":"Bash","tool_input":{"command":"ls -la"}}' | env -u CLAUDE_PROJECT_DIR bash -c "$reg" 2>&1 )"; rc=$?if [ "$rc" -eq 0 ] && [ -z "$out" ]; then good "the registered hook command stays silent on an ordinary command"; else fail "the registered hook command reacted to an ordinary command (exit $rc)"; fi+ if [ "$MATCHER" != "Bash" ]; then+ ( cd "$fx" && printf '{"tool_name":"PowerShell","tool_input":{"command":"fastlane deliver"}}' | env -u CLAUDE_PROJECT_DIR bash -c "$reg" >/dev/null 2>&1 ); rc=$?+ if [ "$rc" -eq 2 ]; then good "the registered hook command blocks a submit command run through PowerShell"; else fail "the registered hook command did not block a PowerShell submit command (exit $rc)"; fi+ fifirm -rf "$fx"fi@@ -290,6 +392,7 @@ do_install() {cp "$GUARD_SRC" "$GUARD" && chmod +x "$GUARD"cp "$REPO/agent-os/skill/SKILL.md" "$SKILL/SKILL.md"cp "$REPO/.citation-allowlist" "$SKILL/.citation-allowlist"+ [ -f "$REPO/VERSION" ] && cp "$REPO/VERSION" "$SKILL/VERSION"local dfor d in $PAYLOAD_DIRS; dorm -rf "${SKILL:?}/$d"@@ -324,7 +427,8 @@ do_uninstall() {}case "$MODE" in- help) say "Usage. install.sh [install|doctor|uninstall] [--dry-run]"; say " install copy the guard, skill and slash command, register the hook, verify (default)"; say " doctor verify an existing install, change nothing"; say " uninstall remove everything install added"; say "Set CLAUDE_CONFIG_DIR to target a config folder other than ~/.claude." ;;+ version) printf 'app-store-compliance %s\n' "$(cat "$REPO/VERSION" 2>/dev/null || echo unknown)" ;;+ help) say "$USAGE"; say " --tool the AI coding tool to install into, claude by default. all installs into every one found"; say " --repo with --tool copilot-repo, the app repository whose .github/hooks gets the guard"; say " install copy the guard, skill and slash command, register the hook, verify (default)"; say " doctor verify an existing install, change nothing"; say " uninstall remove everything install added"; say "Set CLAUDE_CONFIG_DIR to target a config folder other than ~/.claude." ;;install) do_install ;;doctor) verify ;;uninstall) do_uninstall ;;diff --git a/scripts/install_harness.py b/scripts/install_harness.pynew file mode 100644index 0000000..5585231--- /dev/null+++ b/scripts/install_harness.py@@ -0,0 +1,1316 @@+#!/usr/bin/env python3+"""Install the guard, skill and audit command into every supported AI coding tool other than Claude Code.+Usage. install_harness.py <tool> [install|doctor|uninstall] [--dry-run] [--repo DIR]. Configs are merged, never replaced."""++import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import time++REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+GUARD_NAME = "app-store-compliance-guard.sh"+PAYLOAD_DIRS = ("docs", "data", "references", "templates", "scripts")+SUBMIT = "fast" + "lane deliver"+PROBLEMS = []+UNVERIFIED = []+KIMI_BEGIN = "# >>> app-store-compliance guard >>>"+KIMI_END = "# <<< app-store-compliance guard <<<"+KIMI_SEP_FILE = ".app-store-compliance-kimi-sep"++# How each tool runs a hook before a shell command, from each vendor's hook reference.+# style nested. groups of {matcher, hooks:[...]} under the event. flat. a list of entries under the event.+SPECS = {+ "codex": {+ "name": "Codex CLI",+ "style": "nested",+ "event": "PreToolUse",+ "matcher": "Bash",+ "timeout": ("timeout", 120),+ },+ "gemini": {+ "name": "Gemini CLI",+ "style": "nested",+ "event": "BeforeTool",+ "matcher": "run_shell_command",+ "timeout": ("timeout", 120000),+ },+ "grok": {+ "name": "Grok",+ "style": "nested",+ "event": "PreToolUse",+ "matcher": "Bash|run_terminal_command|run_terminal_cmd|bash|monitor",+ # Grok Build's shell tools. A matcher must cover all of them, so an old Bash-only entry is repaired.+ "tools": ("run_terminal_command", "run_terminal_cmd", "bash", "monitor"),+ "timeout": ("timeout", 120),+ },+ "qwen": {+ "name": "Qwen Code",+ "style": "nested",+ "event": "PreToolUse",+ "matcher": "run_shell_command",+ "timeout": ("timeout", 120),+ },+ "droid": {+ "name": "Factory Droid",+ "style": "nested",+ "event": "PreToolUse",+ "matcher": "Execute",+ "timeout": ("timeout", 120),+ },+ "auggie": {+ "name": "Augment Auggie",+ "style": "nested",+ "event": "PreToolUse",+ "matcher": "launch-process",+ "timeout": ("timeout", 120000),+ },+ "cursor": {"name": "Cursor", "style": "flat", "event": "beforeShellExecution"},+ "copilot": {"name": "Copilot CLI and VS Code", "style": "copilot"},+ "copilot-repo": {"name": "Copilot cloud agent and JetBrains", "style": "copilot"},+ "windsurf": {"name": "Windsurf", "style": "flat", "event": "pre_run_command"},+ "kimi": {"name": "Kimi Code", "style": "toml"},+ "opencode": {"name": "OpenCode", "style": "plugin"},+}+TOOLS = tuple(SPECS)+AFTER = {+ "codex": "Open Codex and run /hooks once to approve the new hook. Codex runs no new or changed hook until you do.",+ "gemini": "Restart Gemini CLI so it loads the hook. Skills need Gemini CLI 0.24 or later, the hook works from 0.22.",+ "grok": "Start a new Grok session so it loads the hook.",+ "qwen": "Restart Qwen Code so it loads the hook.",+ "droid": "Start a new Droid session so it loads the hook.",+ "auggie": "Start a new Auggie session so it loads the hook.",+ "cursor": "Restart Cursor so it loads ~/.cursor/hooks.json.",+ "copilot": "Start a new Copilot CLI session, and reload VS Code, so they load the hook.",+ "copilot-repo": "Commit .github/hooks to your default branch. The Copilot cloud agent reads hooks only from there.",+ "windsurf": "Restart Windsurf so it loads the hook.",+ "kimi": "Restart Kimi Code so it loads the hook.",+ "opencode": "Restart OpenCode so it loads the plugin.",+}+++def home():+ h = os.environ.get("HOME")+ if not h:+ sys.exit("HOME is not set, so there is no folder to install into.")+ return h+++def qwen_dir():+ """Qwen Code's global folder. QWEN_HOME wins, with a leading tilde expanded, as Qwen's own Storage does."""+ v = os.environ.get("QWEN_HOME")+ if not v:+ return os.path.join(home(), ".qwen")+ if v == "~" or v.startswith("~/") or v.startswith("~\\"):+ v = os.path.join(home(), v[2:])+ return os.path.abspath(v)+++def kimi_dir():+ """Kimi Code's data folder. KIMI_CODE_HOME wins, with a leading tilde expanded, as its docs describe."""+ v = os.environ.get("KIMI_CODE_HOME")+ if not v:+ return os.path.join(home(), ".kimi-code")+ if v == "~" or v.startswith("~/") or v.startswith("~\\"):+ v = os.path.join(home(), v[2:])+ return os.path.abspath(v)+++def copilot_dir():+ """Copilot CLI's user folder. COPILOT_HOME wins, as the hooks reference describes."""+ v = os.environ.get("COPILOT_HOME")+ if not v:+ return os.path.join(home(), ".copilot")+ if v == "~" or v.startswith("~/") or v.startswith("~\\"):+ v = os.path.join(home(), v[2:])+ return os.path.abspath(v)+++def skill_dir():+ return os.path.join(home(), ".agents", "skills", "app-store-compliance")+++def layout(tool, repo_dir=None):+ """Where each tool keeps its hooks, its hook config and its commands, from each tool's own docs."""+ h = home()+ if tool == "copilot-repo":+ base = os.path.join(repo_dir or "", ".github")+ return {+ "hooks": os.path.join(base, "hooks"),+ "config": os.path.join(base, "hooks", "app-store-compliance.json"),+ "command": None,+ "wrap": True,+ }+ if tool == "opencode":+ base = os.path.join(+ os.environ.get("XDG_CONFIG_HOME") or os.path.join(h, ".config"), "opencode"+ )+ return {+ "hooks": os.path.join(base, "hooks"),+ "config": os.path.join(base, "plugins", "app-store-compliance.js"),+ "command": os.path.join(base, "commands", "app-store-audit.md"),+ "wrap": True,+ }+ if tool == "droid":+ base = os.path.join(h, ".factory")+ hooks_json, settings = (+ os.path.join(base, "hooks.json"),+ os.path.join(base, "settings.json"),+ )+ # Droid reads settings.json hooks only while hooks.json is absent. Creating hooks.json would switch them off.+ uses_settings = not os.path.exists(hooks_json) and has_hooks_key(settings)+ return {+ "hooks": os.path.join(base, "hooks"),+ "config": settings if uses_settings else hooks_json,+ "command": None,+ "wrap": uses_settings,+ }+ bases = {+ "codex": os.environ.get("CODEX_HOME") or os.path.join(h, ".codex"),+ "gemini": os.path.join(h, ".gemini"),+ "grok": os.path.join(h, ".grok"),+ "qwen": qwen_dir(),+ "auggie": os.path.join(h, ".augment"),+ "cursor": os.path.join(h, ".cursor"),+ "copilot": copilot_dir(),+ "windsurf": os.path.join(h, ".codeium", "windsurf"),+ "kimi": kimi_dir(),+ }+ base = bases[tool]+ configs = {+ "codex": "hooks.json",+ "gemini": "settings.json",+ "grok": os.path.join("hooks", "app-store-compliance.json"),+ "qwen": "settings.json",+ "auggie": "settings.json",+ "cursor": "hooks.json",+ "copilot": os.path.join("hooks", "app-store-compliance.json"),+ "windsurf": "hooks.json",+ "kimi": "config.toml",+ }+ command = (+ os.path.join(base, "commands", "app-store-audit.toml")+ if tool == "gemini"+ else None+ )+ return {+ "hooks": os.path.join(base, "hooks"),+ "config": os.path.join(base, configs[tool]),+ "command": command,+ "wrap": True,+ }+++def has_hooks_key(path):+ try:+ with open(path, encoding="utf-8") as f:+ return isinstance(json.load(f).get("hooks"), dict)+ except Exception:+ return False+++def shown(path):+ h = home()+ return "~" + path[len(h) :] if path.startswith(h + os.sep) else path+++def hook_cmd(tool, guard):+ if tool == "copilot-repo":+ return (+ "bash ./.github/hooks/" + GUARD_NAME+ ) # the cloud agent runs it from the repository root+ if tool == "auggie":+ return guard # Auggie runs a script path by its extension and shebang, never a shell string+ return "bash '" + guard.replace("'", "'\\''") + "'"+++def ps_cmd(tool, guard):+ """The Windows handler Copilot runs in PowerShell. It pipes the payload to bash and keeps the guard's exit code."""+ target = "./.github/hooks/" + GUARD_NAME if tool == "copilot-repo" else guard+ if tool != "copilot-repo" and shutil.which("cygpath"):+ r = subprocess.run(["cygpath", "-m", guard], capture_output=True, text=True)+ target = r.stdout.strip() or guard+ return "$input | & bash '" + target.replace("'", "''") + "'; exit $LASTEXITCODE"+++def ok(msg):+ print(" ok " + msg)+++def note(msg):+ print(" note " + msg)+++def fail(msg):+ print(" FAIL " + msg)+ PROBLEMS.append(msg)+++def load_json(path):+ """The parsed object, {} when the file is absent or empty, None when it is unsafe to rewrite."""+ if not os.path.exists(path):+ return {}++ def no_repeats(pairs):+ keys = [k for k, _ in pairs]+ if len(keys) != len(set(keys)):+ raise ValueError("repeated key")+ return dict(pairs)++ try:+ with open(path, encoding="utf-8") as f:+ text = f.read()+ data = json.loads(text, object_pairs_hook=no_repeats) if text.strip() else {}+ except Exception:+ return None+ if not isinstance(data, dict) or not os.access(path, os.W_OK):+ return None+ return data+++def write_atomic(path, text, newline=None):+ folder = os.path.dirname(path)+ os.makedirs(folder, exist_ok=True)+ real = os.path.realpath(path)+ if os.path.exists(real):+ shutil.copy2(+ real,+ path + ".bak-" + time.strftime("%Y%m%d-%H%M%S") + "-" + str(os.getpid()),+ )+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(real) or folder, prefix=".asc-")+ with os.fdopen(fd, "w", encoding="utf-8", newline=newline) as f:+ f.write(text)+ if os.path.exists(real):+ shutil.copymode(real, tmp)+ os.replace(tmp, real)+++def events(tool):+ """(event key, style) pairs this tool's file carries. Copilot carries its own form and the Claude form VS Code reads."""+ spec = SPECS[tool]+ if spec["style"] == "copilot":+ return [("preToolUse", "copilot"), ("PreToolUse", "vscode")]+ return [(spec["event"], spec["style"])]+++def new_entry(tool, style, cmd):+ spec = SPECS[tool]+ if style == "nested":+ key, value = spec["timeout"]+ return {+ "matcher": spec["matcher"],+ "hooks": [{"type": "command", "command": cmd, key: value}],+ }+ if style == "copilot":+ return {+ "type": "command",+ "bash": cmd,+ "powershell": ps_cmd(tool, guard_of(cmd)),+ "timeoutSec": 120,+ }+ if style == "vscode":+ return {"type": "command", "command": cmd, "timeout": 120}+ if tool == "windsurf":+ return {"command": cmd, "show_output": True}+ return {"command": cmd, "timeout": 120}+++def guard_of(cmd):+ """The guard path inside a bash command line this installer wrote."""+ if cmd.startswith("bash '") and cmd.endswith("'"):+ return cmd[6:-1].replace("'\\''", "'")+ return cmd[5:] if cmd.startswith("bash ") else cmd+++def is_ours(item, cmd, guard):+ if not isinstance(item, dict):+ return False+ c = str(item.get("command", item.get("bash", ""))).strip()+ return c in (cmd, "bash " + guard, 'bash "' + guard + '"', "bash '" + guard + "'")+++def ours_in(style, groups, cmd, guard):+ if style == "nested":+ return [+ h+ for g in groups+ for h in (g.get("hooks") if isinstance(g.get("hooks"), list) else [])+ if is_ours(h, cmd, guard)+ ]+ return [g for g in groups if is_ours(g, cmd, guard)]+++def matcher_hits(m, name):+ if m in (None, "", "*"):+ return True+ try:+ return re.fullmatch(str(m), name) is not None+ except re.error:+ return False+++def dispatches(tool, style, group, h):+ """True when the tool would run this handler for a shell call and give it time to finish."""+ spec = SPECS[tool]+ if style == "nested" and not all(+ matcher_hits(group.get("matcher"), t) for t in spec.get("tools", (spec["matcher"],))+ ):+ return False+ if style in ("nested", "copilot", "vscode") and h.get("type", "command") != "command":+ return False+ # Qwen requires the type, and reads a command timeout of 1000 or more as milliseconds+ if tool == "qwen" and h.get("type") != "command":+ return False+ if h.get("async") not in (None, False):+ return False+ if tool == "cursor" and (+ h.get("type", "command") != "command"+ or not all(matcher_hits(h.get("matcher"), c) for c in ("fastlane deliver", "eas submit --platform ios", "xcrun altool --upload-app"))+ ):+ return False+ shell_tools = {"copilot": ("bash", "powershell"), "vscode": ("runInTerminal", "run_in_terminal")}.get(style)+ if shell_tools and "matcher" in h and not all(matcher_hits(h.get("matcher"), t) for t in shell_tools):+ return False+ if tool == "windsurf":+ return True+ if tool == "auggie" and not (+ str(h.get("command", "")).endswith(".sh") and os.access(str(h.get("command", "")), os.X_OK)+ ):+ return False+ if style == "copilot":+ ps = h.get("powershell")+ if ps != ps_cmd(tool, guard_of(str(h.get("bash", "")))):+ return False+ key, want = {"nested": spec.get("timeout"), "copilot": ("timeoutSec", 120)}.get(+ style+ ) or ("timeout", 120)+ t = h.get(key)+ if not isinstance(t, (int, float)) or isinstance(t, bool):+ return False+ if tool == "qwen" and t >= 1000:+ t = t / 1000+ return t >= want+++def live_in(tool, style, groups, cmd, guard):+ """Our handlers that would actually run, the ones doctor may certify."""+ if style == "nested":+ return [+ h+ for g in groups+ for h in (g.get("hooks") if isinstance(g.get("hooks"), list) else [])+ if is_ours(h, cmd, guard) and dispatches(tool, style, g, h)+ ]+ return [g for g in groups if is_ours(g, cmd, guard) and dispatches(tool, style, None, g)]+++def without_ours(style, groups, cmd, guard):+ """The groups with every handler of ours removed, dropping a group only we filled."""+ if style != "nested":+ return [g for g in groups if not is_ours(g, cmd, guard)]+ kept = []+ for g in groups:+ hs = g.get("hooks") if isinstance(g.get("hooks"), list) else []+ mine = [h for h in hs if is_ours(h, cmd, guard)]+ if mine:+ g["hooks"] = [h for h in hs if not is_ours(h, cmd, guard)]+ if not g["hooks"]:+ continue+ kept.append(g)+ return kept+++def container(lay, data):+ """The object that holds the event lists, created if missing. None when the shape is wrong."""+ if not lay["wrap"]:+ return data+ hooks = data.setdefault("hooks", {})+ return hooks if isinstance(hooks, dict) else None+++def plugin_source(guard):+ return (+ "// App Store Compliance Playbook guard for OpenCode. Runs the guard before every shell command\n"+ "// and stops the command when the guard exits 2. Installed by scripts/install_harness.py.\n"+ 'import { spawnSync } from "node:child_process";\n\n'+ "export const AppStoreCompliance = async ({ directory }) => ({\n"+ ' "tool.execute.before": async (input, output) => {\n'+ ' if (input.tool !== "bash") return;\n'+ " const command = output && output.args ? output.args.command : undefined;\n"+ ' if (typeof command !== "string") return;\n'+ " // OpenCode loads both plugin folders, so a call one copy already checked is skipped by the other.\n"+ " const seen = (globalThis.__appStoreComplianceSeen ||= new WeakSet());\n"+ " if (seen.has(output)) return;\n"+ " seen.add(output);\n"+ ' const r = spawnSync("bash", [' + json.dumps(guard) + "], {\n"+ ' input: JSON.stringify({ tool_name: "Bash", tool_input: { command }, cwd: directory }),\n'+ ' encoding: "utf8", timeout: 120000, cwd: directory,\n'+ " });\n"+ ' if (r.status === 2) throw new Error((r.stdout || "") + (r.stderr || "") || "Blocked by the App Store compliance guard.");\n'+ ' if (r.error || (r.status !== 0 && r.status !== 1)) {\n'+ ' const why = "The App Store compliance guard could not run (" + (r.error ? r.error.message : "exit " + r.status) + "). Run install.sh --tool opencode doctor.";\n'+ ' if (/fastlane|eas |xcrun|altool|notarytool|transporter|gradle|bundletool|xcodebuild|flutter|expo|capacitor|cap |cordova|ionic|unity|dotnet|tauri|npm|pnpm|yarn|bun |make|turbo|nx |lerna/i.test(command.replace(/[\\\\\\x27"`]/g, "").replace(/\\s+/g, " "))) throw new Error(why);\n'+ ' console.error(why);\n'+ ' }\n'+ " },\n"+ "});\n"+ )+++def legacy_plugin(lay):+ """OpenCode before 1.0 loads plugin/, current OpenCode loads plugins/. The plugin goes in both."""+ return os.path.join(+ os.path.dirname(os.path.dirname(lay["config"])),+ "plugin",+ os.path.basename(lay["config"]),+ )+++def kimi_block(cmd):+ return (+ "\n".join(+ [+ KIMI_BEGIN,+ "[[hooks]]",+ 'event = "PreToolUse"',+ 'matcher = "^Bash$"',+ "command = " + json.dumps(cmd),+ "timeout = 120",+ KIMI_END,+ ]+ )+ + "\n"+ )+++def kimi_entry(text):+ """The [[hooks]] table inside our marked block, {} when it does not parse, None when absent."""+ m = re.search(re.escape(KIMI_BEGIN) + r"\r?\n(.*?)" + re.escape(KIMI_END), text, re.S)+ if not m:+ return None+ try:+ import tomllib++ hooks = tomllib.loads(m.group(1)).get("hooks")+ return hooks[0] if isinstance(hooks, list) and hooks and isinstance(hooks[0], dict) else {}+ except ImportError:+ out = {}+ for line in m.group(1).splitlines():+ k, eq, v = line.partition("=")+ if eq:+ try:+ out[k.strip()] = json.loads(v.strip())+ except ValueError:+ return {}+ return out+ except Exception:+ return {}+++def kimi_live(h):+ """True when Kimi would run this handler before a shell command and give it time to finish."""+ if not h or h.get("event") != "PreToolUse" or not isinstance(h.get("command"), str):+ return False+ # Kimi accepts only these four keys and an integer timeout up to 600, and refuses the whole config otherwise+ if set(h) - {"event", "matcher", "command", "timeout"}:+ return False+ t = h.get("timeout")+ ok_time = isinstance(t, int) and not isinstance(t, bool) and 120 <= t <= 600+ return ok_time and matcher_hits(h.get("matcher"), "Bash")+++def command_text(tool, guard):+ with open(+ os.path.join(REPO, "agent-os", "commands", "app-store-audit.md"),+ encoding="utf-8",+ ) as f:+ md = f.read()+ md = md.replace("~/.claude/hooks/" + GUARD_NAME, shown(guard)).replace(+ "~/.claude/skills/app-store-compliance", shown(skill_dir())+ )+ if tool == "opencode":+ return md+ head, _, body = md.partition("\n---\n")+ desc = head.split("description:", 1)[-1].strip()+ body = (+ body.replace('\\', '\\\\').replace('"""', "'''")+ + "\n\nThe target project is {{args}}. When it is empty, use the current folder.\n"+ )+ return "description = " + json.dumps(desc) + '\nprompt = """\n' + body + '"""\n'+++def manual_block(tool, lay, cmd):+ if tool == "opencode":+ return plugin_source(cmd)+ if tool == "kimi":+ return (+ "\nAppend this to "+ + shown(lay["config"])+ + " yourself.\n\n"+ + kimi_block(cmd)+ )+ events_map = {ev: [new_entry(tool, st, cmd)] for ev, st in events(tool)}+ data = {"hooks": events_map} if lay["wrap"] else events_map+ if tool == "gemini":+ data["tools"] = {"enableHooks": True}+ if tool in ("cursor", "copilot", "copilot-repo"):+ data["version"] = 1+ return (+ "\nMerge this into "+ + shown(lay["config"])+ + " yourself.\n\n"+ + json.dumps(data, indent=2)+ + "\n"+ )+++def register(tool, lay, guard, dry):+ cmd = hook_cmd(tool, guard)+ style = SPECS[tool]["style"]+ if style == "plugin":+ if dry:+ print(+ " would write the OpenCode plugin "+ + shown(lay["config"])+ + " and "+ + shown(legacy_plugin(lay))+ )+ return True+ for path in (lay["config"], legacy_plugin(lay)):+ write_atomic(path, plugin_source(guard))+ ok(+ "plugin written to "+ + shown(lay["config"])+ + " and "+ + shown(legacy_plugin(lay))+ )+ return True+ if style == "toml":+ return register_kimi(lay, cmd, dry)+ data = load_json(lay["config"])+ if data is None:+ fail(+ shown(lay["config"])+ + " is not valid JSON, repeats a key, is read-only, or has an unexpected shape. It was not changed."+ )+ print(manual_block(tool, lay, cmd))+ return False+ fixed = False+ if tool in ("cursor", "copilot", "copilot-repo") and "version" not in data:+ data["version"] = 1+ fixed = True+ if tool == "cursor" and not (type(data.get("version")) is int and data.get("version") >= 1):+ data["version"] = 1+ fixed = True+ # Copilot rejects the whole hooks file unless version is the number 1, and true is not 1+ if tool in ("copilot", "copilot-repo") and not (type(data.get("version")) is int and data.get("version") == 1):+ data["version"] = 1+ fixed = True+ if tool == "gemini" and not isinstance(data.setdefault("tools", {}), dict):+ fail(+ shown(lay["config"])+ + " has a tools key that is not an object. It was not changed."+ )+ print(manual_block(tool, lay, cmd))+ return False+ box = container(lay, data)+ changed = fixed+ for ev, st in events(tool):+ groups = box.setdefault(ev, []) if isinstance(box, dict) else None+ if not isinstance(groups, list) or not all(isinstance(g, dict) for g in groups):+ fail(+ shown(lay["config"])+ + " has hooks with an unexpected shape. It was not changed."+ )+ print(manual_block(tool, lay, cmd))+ return False+ if not live_in(tool, st, groups, cmd, guard):+ # An entry of ours that would never run is replaced, never left beside the new one.+ groups[:] = without_ours(st, groups, cmd, guard)+ groups.append(new_entry(tool, st, cmd))+ changed = True+ if tool == "gemini" and data["tools"].get("enableHooks") is not True:+ data["tools"]["enableHooks"] = (+ True # Gemini CLI before 0.26 runs no hook without this+ )+ changed = True+ if not changed:+ ok("hook already registered in " + shown(lay["config"]))+ return True+ if dry:+ print(+ " would add the hook entry to "+ + shown(lay["config"])+ + ", keeping every other key, with a backup"+ )+ return True+ write_atomic(lay["config"], json.dumps(data, indent=2, ensure_ascii=False) + "\n")+ ok(+ "hook added to "+ + shown(lay["config"])+ + " (a backup sits next to it when the file already existed)"+ )+ return True+++KIMI_KEY = r"""(?:hooks|"hooks"|'hooks')"""+++def kimi_hooks_taken(text):+ """True when the file already defines hooks as a key or a table, which a [[hooks]] block cannot join."""+ t = text.replace("\r", "")+ return bool(+ re.search(r"^[ \t]*" + KIMI_KEY + r"[ \t]*[=.]", t, re.M)+ or re.search(r"^[ \t]*\[[ \t]*" + KIMI_KEY + r"[ \t]*[\].]", t, re.M)+ or re.search(r'^[ \t]*\[?[ \t]*"[^"\n]*\\[uU]', t, re.M)+ )+++def toml_still_valid(before, after):+ """False when a file that parsed before no longer parses. True when no TOML parser is available."""+ try:+ import tomllib+ except ImportError:+ return True+ try:+ tomllib.loads(before)+ except Exception:+ return True+ try:+ tomllib.loads(after)+ except Exception:+ return False+ return True+++def register_kimi(lay, cmd, dry):+ path = lay["config"]+ text = ""+ if os.path.exists(path):+ if not os.access(path, os.W_OK):+ fail(shown(path) + " is read-only. It was not changed.")+ print(manual_block("kimi", lay, cmd))+ return False+ with open(path, encoding="utf-8", newline="") as f:+ text = f.read()+ nl = "\r\n" if "\r\n" in text else "\n"+ if KIMI_BEGIN in text:+ h = kimi_entry(text)+ if kimi_live(h) and h.get("command") == cmd:+ ok("hook already registered in " + shown(path))+ return True+ if dry:+ print(" would rewrite the guard block in " + shown(path) + ", with a backup")+ return True+ pattern = re.escape(KIMI_BEGIN) + r".*?" + re.escape(KIMI_END) + r"(\r?\n)?"+ repaired = re.sub(pattern, lambda _m: kimi_block(cmd).replace("\n", nl), text, count=1, flags=re.S)+ if kimi_hooks_taken(re.sub(pattern, "", text, count=1, flags=re.S)) or not toml_still_valid(text, repaired):+ fail(shown(path) + " defines hooks another way, so the guard block cannot be repaired. It was not changed.")+ print(manual_block("kimi", lay, cmd))+ return False+ write_atomic(path, repaired, newline="")+ ok("guard block repaired in " + shown(path) + " (a backup sits next to it)")+ return True+ if kimi_hooks_taken(text):+ fail(shown(path) + " defines hooks inline, so a [[hooks]] block cannot be added. It was not changed.")+ print(manual_block("kimi", lay, cmd))+ return False+ if dry:+ print(+ " would append one [[hooks]] block to "+ + shown(path)+ + ", keeping everything else, with a backup"+ )+ return True+ sep = "" if not text or text.endswith(nl + nl) else (nl if text.endswith(nl) else nl + nl)+ if not toml_still_valid(text, text + sep + kimi_block(cmd).replace("\n", nl)):+ fail(shown(path) + " would not stay valid TOML with a [[hooks]] block. It was not changed.")+ print(manual_block("kimi", lay, cmd))+ return False+ write_atomic(path, text + sep + kimi_block(cmd).replace("\n", nl), newline="")+ os.makedirs(lay["hooks"], exist_ok=True)+ with open(os.path.join(lay["hooks"], KIMI_SEP_FILE), "w", encoding="utf-8") as f:+ f.write(json.dumps(sep))+ ok(+ "hook appended to "+ + shown(path)+ + " (a backup sits next to it when the file already existed)"+ )+ return True+++def unregister(tool, lay, guard):+ cmd = hook_cmd(tool, guard)+ style = SPECS[tool]["style"]+ if style == "plugin":+ for path in (lay["config"], legacy_plugin(lay)):+ if os.path.exists(path):+ os.remove(path)+ return True+ if not os.path.exists(lay["config"]):+ return True+ if style == "toml":+ with open(lay["config"], encoding="utf-8", newline="") as f:+ text = f.read()+ if KIMI_BEGIN not in text:+ return True+ m = re.search(re.escape(KIMI_BEGIN) + r".*?" + re.escape(KIMI_END) + r"(\r?\n)?", text, flags=re.S)+ before, after = text[: m.start()], text[m.end() :]+ sep_file = os.path.join(lay["hooks"], KIMI_SEP_FILE)+ try:+ with open(sep_file, encoding="utf-8") as f:+ sep = json.loads(f.read() or '""')+ except (OSError, ValueError):+ sep = ""+ sep = "\n" * sep if isinstance(sep, int) else (sep if isinstance(sep, str) else "")+ # Drop only the newlines the install added in front of a block it appended at the end.+ if sep and not after and before.endswith(sep):+ before = before[: -len(sep)]+ write_atomic(lay["config"], before + after, newline="")+ if os.path.exists(sep_file):+ os.remove(sep_file)+ return True+ data = load_json(lay["config"])+ if data is None:+ return False+ box = data.get("hooks") if lay["wrap"] else data+ if not isinstance(box, dict):+ return True+ changed = False+ for ev, st in events(tool):+ groups = box.get(ev)+ if not isinstance(groups, list) or not ours_in(st, groups, cmd, guard):+ continue+ kept = without_ours(st, groups, cmd, guard)+ if kept:+ box[ev] = kept+ else:+ box.pop(ev)+ changed = True+ if not changed:+ return True+ if lay["wrap"] and not box:+ data.pop("hooks")+ if tool in ("copilot", "copilot-repo", "grok") and set(data) <= {"version"}:+ os.remove(lay["config"])+ return True+ write_atomic(lay["config"], json.dumps(data, indent=2, ensure_ascii=False) + "\n")+ return True+++def read_owners():+ try:+ with open(os.path.join(skill_dir(), ".installed-by"), encoding="utf-8") as f:+ return {line.strip() for line in f if line.strip() in TOOLS}+ except OSError:+ return set()+++def write_owners(owners):+ """Replaces .installed-by in one step, so a reader never sees it empty or half written."""+ sk = skill_dir()+ fd, tmp = tempfile.mkstemp(dir=sk, prefix=".asc-owners-")+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ f.write("\n".join(sorted(owners)) + "\n")+ os.replace(tmp, os.path.join(sk, ".installed-by"))+++def read_guards():+ """Every installed guard path and its tool, so two folders of one tool each own the skill."""+ out = {}+ try:+ with open(os.path.join(skill_dir(), ".guards"), encoding="utf-8") as f:+ for line in f:+ t, tab, path = line.rstrip("\n").partition("\t")+ if tab and t in TOOLS and path:+ out[path] = t+ except OSError:+ pass+ return out+++def write_guards(guards):+ sk = skill_dir()+ fd, tmp = tempfile.mkstemp(dir=sk, prefix=".asc-guards-")+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ f.write("".join(guards[g] + "\t" + g + "\n" for g in sorted(guards)))+ os.replace(tmp, os.path.join(sk, ".guards"))+++def copy_payload(tool, lay, guard):+ if tool != "copilot-repo":+ sk = skill_dir()+ os.makedirs(sk, exist_ok=True)+ shutil.copy2(+ os.path.join(REPO, "agent-os", "skill", "SKILL.md"),+ os.path.join(sk, "SKILL.md"),+ )+ shutil.copy2(+ os.path.join(REPO, ".citation-allowlist"),+ os.path.join(sk, ".citation-allowlist"),+ )+ if os.path.exists(os.path.join(REPO, "VERSION")):+ shutil.copy2(os.path.join(REPO, "VERSION"), os.path.join(sk, "VERSION"))+ for d in PAYLOAD_DIRS:+ shutil.rmtree(os.path.join(sk, d), ignore_errors=True)+ shutil.copytree(+ os.path.join(REPO, d),+ os.path.join(sk, d),+ ignore=shutil.ignore_patterns("__pycache__"),+ )+ write_owners(read_owners() | {tool})+ write_guards(dict(read_guards(), **{guard: tool}))+ os.makedirs(lay["hooks"], exist_ok=True)+ shutil.copy2(os.path.join(REPO, "agent-os", "hooks", GUARD_NAME), guard)+ os.chmod(guard, 0o755)+ if lay["command"]:+ os.makedirs(os.path.dirname(lay["command"]), exist_ok=True)+ with open(lay["command"], "w", encoding="utf-8") as f:+ f.write(command_text(tool, guard))+ ok("guard copied" if tool == "copilot-repo" else "guard, skill and command copied")+++def payload_for(tool, style, command, cwd):+ """The exact JSON each tool sends its hook, from each vendor's hook reference."""+ if tool == "gemini":+ return {+ "hook_event_name": "BeforeTool",+ "tool_name": "run_shell_command",+ "tool_input": {"command": command},+ "cwd": cwd,+ }+ if tool == "qwen":+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "run_shell_command",+ "tool_input": {"command": command},+ "cwd": cwd,+ }+ if tool == "grok":+ return {+ "hookEventName": "PreToolUse",+ "toolName": "run_terminal_command",+ "toolInput": {"command": command},+ "cwd": cwd,+ }+ if tool == "droid":+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "Execute",+ "tool_input": {"command": command},+ "cwd": cwd,+ }+ if tool == "auggie":+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "launch-process",+ "tool_input": {"command": command},+ "workspace_roots": [cwd],+ }+ if tool == "cursor":+ return {+ "hook_event_name": "beforeShellExecution",+ "command": command,+ "cwd": cwd,+ }+ if tool == "windsurf":+ return {+ "agent_action_name": "pre_run_command",+ "tool_info": {"command_line": command, "cwd": cwd},+ }+ if style == "copilot":+ return {+ "toolName": "bash",+ "toolArgs": json.dumps({"command": command}),+ "cwd": cwd,+ }+ if style == "vscode":+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "runInTerminal",+ "tool_input": {"command": command},+ "cwd": cwd,+ }+ if tool == "kimi":+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": command},+ }+ return {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": command},+ "cwd": cwd,+ }+++def sample_app():+ d = tempfile.mkdtemp()+ os.makedirs(os.path.join(d, "App"))+ with open(os.path.join(d, "App", "Info.plist"), "w") as f:+ f.write("<plist><dict></dict></plist>")+ with open(os.path.join(d, "App", "X.swift"), "w") as f:+ f.write(+ 'import CoreLocation\nclass A { func signIn(){} func createAccount(){} }\nlet m=CLLocationManager()\nlet u="https://staging.example.com"\nimport Stripe\n'+ )+ return d+++def run_hook(cmd_line, payload, cwd, tool=None):+ env = {+ k: v+ for k, v in os.environ.items()+ if k not in ("CLAUDE_PROJECT_DIR", "GEMINI_PROJECT_DIR", "AUGMENT_PROJECT_DIR")+ }+ argv = [cmd_line] if tool == "auggie" else ["bash", "-c", cmd_line]+ try:+ r = subprocess.run(+ argv, input=json.dumps(payload), capture_output=True, text=True,+ cwd=cwd, env=env, timeout=180,+ )+ except OSError as e:+ return 126, str(e)+ return r.returncode, (r.stdout + r.stderr).strip()+++def run_plugin(plugin, command, cwd):+ """Loads the OpenCode plugin in node and calls its hook the way OpenCode does. None when node is absent."""+ if not shutil.which("node"):+ return None+ js = (+ "const m = await import(process.argv[1]);"+ "const h = await m.AppStoreCompliance({ directory: process.argv[3] });"+ 'try { await h["tool.execute.before"]({ tool: "bash" }, { args: { command: process.argv[2] } }); process.exit(0); }'+ "catch (e) { process.exit(2); }"+ )+ r = subprocess.run(+ ["node", "--input-type=module", "-e", js, "file://" + plugin, command, cwd],+ capture_output=True,+ text=True,+ timeout=180,+ )+ return r.returncode+++def verify(tool, lay, guard, repo_dir):+ print("\nChecking the " + SPECS[tool]["name"] + " install.")+ if os.path.isfile(guard):+ ok("guard present at " + shown(guard))+ else:+ fail("guard missing at " + shown(guard))+ if tool != "copilot-repo":+ sk = skill_dir()+ need = (+ "SKILL.md",+ "data/rejection-patterns.json",+ "data/regulatory-deadlines.json",+ "docs/PRE-SUBMISSION-CHECKLIST.md",+ "scripts/deadline-checker.py",+ "scripts/validate-privacy-manifest.py",+ ".citation-allowlist",+ )+ missing = [p for p in need if not os.path.exists(os.path.join(sk, p))]+ if missing:+ fail("skill payload is missing " + " ".join(missing))+ else:+ ok("skill payload complete at " + shown(sk))+ if os.path.isfile(os.path.join(sk, "VERSION")):+ with open(os.path.join(sk, "VERSION")) as f:+ inst = f.read().strip()+ ok("version " + inst)+ repo_v = os.path.join(REPO, "VERSION")+ if os.path.isfile(repo_v):+ with open(repo_v) as f:+ cur = f.read().strip()+ if cur and cur != inst:+ note("this checkout is version " + cur + ". Run install.sh --tool " + tool + " again to update.")+ if lay["command"]:+ if os.path.isfile(lay["command"]):+ ok("audit command at " + shown(lay["command"]))+ else:+ fail("audit command missing at " + shown(lay["command"]))+ app = sample_app()+ try:+ style = SPECS[tool]["style"]+ if style == "plugin":+ check_plugin(lay, app)+ elif style == "toml":+ check_kimi(lay, guard, app)+ else:+ check_hooks(tool, lay, guard, app, repo_dir)+ finally:+ shutil.rmtree(app, ignore_errors=True)+ print("")+ if PROBLEMS:+ extra = " --repo " + repo_dir if repo_dir else ""+ print(+ str(len(PROBLEMS))+ + " problem(s) above. Fix them, then run. bash "+ + os.path.join(REPO, "scripts", "install.sh")+ + " --tool "+ + tool+ + extra+ + " doctor"+ )+ return 1+ if UNVERIFIED:+ print("Installed, but not fully verified. " + "; ".join(UNVERIFIED) + ". Install node and run doctor to verify.")+ else:+ print("Install verified.")+ if tool != "copilot-repo":+ print("Check your app now. bash " + shown(guard) + ' "/path/to/your/app"')+ print(AFTER[tool])+ return 0+++def check_plugin(lay, app):+ for path in (lay["config"], legacy_plugin(lay)):+ if not os.path.isfile(path):+ fail("plugin missing at " + shown(path))+ return+ rc = run_plugin(lay["config"], SUBMIT, app)+ if rc is None:+ note(+ "node not found, so the plugin was not exercised here. OpenCode runs it with its own runtime."+ )+ UNVERIFIED.append("the OpenCode plugin was not exercised (node not found)")+ return+ if rc == 2:+ ok("the plugin stops a submit command")+ else:+ fail("the plugin did not stop a submit command (exit " + str(rc) + ")")+ if run_plugin(lay["config"], "ls -la", app) == 0:+ ok("the plugin lets an ordinary command through")+ else:+ fail("the plugin stopped an ordinary command")+++def check_kimi(lay, guard, app):+ try:+ with open(lay["config"], encoding="utf-8") as f:+ text = f.read()+ except OSError:+ text = ""+ if KIMI_BEGIN not in text:+ fail("no hook block for the guard in " + shown(lay["config"]))+ return+ try:+ import tomllib++ tomllib.loads(text)+ ok(+ "hook registered in "+ + shown(lay["config"])+ + ", and the file still parses as TOML"+ )+ except ImportError:+ ok("hook registered in " + shown(lay["config"]))+ except Exception:+ fail(shown(lay["config"]) + " no longer parses as TOML")+ return+ h = kimi_entry(text)+ if not kimi_live(h):+ fail(+ "the guard block in "+ + shown(lay["config"])+ + " would not run before a shell command. Check its event, matcher and timeout, or run install again"+ )+ return+ prove(h["command"], "kimi", "toml", app, app)+++def check_hooks(tool, lay, guard, app, repo_dir):+ cmd = hook_cmd(tool, guard)+ data = load_json(lay["config"]) or {}+ box = data.get("hooks") if lay["wrap"] else data+ box = box if isinstance(box, dict) else {}+ found_any = False+ for ev, st in events(tool):+ groups = box.get(ev)+ found = live_in(tool, st, groups, cmd, guard) if isinstance(groups, list) else []+ if not found:+ if isinstance(groups, list) and ours_in(st, groups, cmd, guard):+ fail(+ "the " + ev + " entry in " + shown(lay["config"])+ + " names the guard but would never run it. Check its matcher, type and timeout, or run install again"+ )+ else:+ fail("no " + ev + " hook entry for the guard in " + shown(lay["config"]))+ continue+ found_any = True+ line = found[0].get("command") or found[0].get("bash")+ prove(line, tool, st, app, repo_dir or "/")+ if st == "copilot":+ prove_ps(found[0]["powershell"], tool, app, repo_dir or "/")+ if found_any:+ ok("hook registered in " + shown(lay["config"]))+ if tool in ("copilot", "copilot-repo") and not (type(data.get("version")) is int and data.get("version") == 1):+ fail("version is not 1 in " + shown(lay["config"]) + ", so Copilot rejects the whole hooks file")+ if tool == "cursor" and not (type(data.get("version")) is int and data.get("version") >= 1):+ fail("version is not a positive whole number in " + shown(lay["config"]) + ", so Cursor rejects the hooks file")+ hc = data.get("hooksConfig")+ if tool == "gemini" and isinstance(hc, dict) and hc.get("enabled") is False:+ fail("hooksConfig.enabled is false in " + shown(lay["config"]) + ", so Gemini CLI runs no hook, the guard included")+ if tool in ("qwen", "copilot", "copilot-repo") and data.get("disableAllHooks") is True:+ fail("disableAllHooks is true in " + shown(lay["config"]) + ", so the tool runs no hook, the guard included")+ if tool == "gemini" and (data.get("tools") or {}).get("enableHooks") is not True:+ fail(+ "tools.enableHooks is not true in "+ + shown(lay["config"])+ + ", so Gemini CLI before 0.26 runs no hook"+ )+++def prove(line, tool, style, app, run_dir):+ """Feeds a submit command and an ordinary one to the registered command, in the tool's own payload shape."""+ label = {"vscode": " for VS Code", "copilot": " for Copilot"}.get(style, "")+ rc, _ = run_hook(line, payload_for(tool, style, SUBMIT, app), run_dir, tool)+ if rc == 2:+ ok(+ "the registered command blocks a submit command in this tool's own payload shape"+ + label+ )+ else:+ fail(+ "the registered command did not block a submit command"+ + label+ + " (exit "+ + str(rc)+ + ", expected 2)"+ )+ rc, out = run_hook(line, payload_for(tool, style, "ls -la", app), run_dir, tool)+ if rc == 0 and not out:+ ok("the registered command stays silent on an ordinary command" + label)+ else:+ fail(+ "the registered command reacted to an ordinary command"+ + label+ + " (exit "+ + str(rc)+ + ")"+ )+++def prove_ps(line, tool, app, run_dir):+ """Runs the Windows handler in PowerShell when one is installed here, as Copilot does on Windows."""+ shell = shutil.which("pwsh") or shutil.which("powershell")+ if not shell:+ ok("the Windows powershell handler is registered (PowerShell is not installed here to run it)")+ return+ r = subprocess.run(+ [shell, "-NoProfile", "-NonInteractive", "-Command", line],+ input=json.dumps(payload_for(tool, "copilot", SUBMIT, app)),+ capture_output=True, text=True, cwd=run_dir, timeout=180,+ )+ if r.returncode == 2:+ ok("the Windows powershell handler blocks a submit command")+ else:+ fail("the Windows powershell handler did not block a submit command (exit " + str(r.returncode) + ")")+++def uninstall(tool, lay, guard, dry):+ if dry:+ print(+ "Dry run. Would remove the guard, the command and the hook entry for "+ + SPECS[tool]["name"]+ + "."+ )+ return 0+ done = unregister(tool, lay, guard)+ for p in (guard, lay["command"]):+ if p and os.path.exists(p):+ os.remove(p)+ if tool == "copilot-repo":+ print("Removed the guard and the hook from the repository.")+ else:+ guards = read_guards()+ guards.pop(guard, None)+ owners = (read_owners() - {tool}) | set(guards.values())+ if owners:+ write_owners(owners)+ write_guards(guards)+ print(+ "Removed the "+ + SPECS[tool]["name"]+ + " guard and hook. The shared skill stays for "+ + ", ".join(sorted(owners))+ + "."+ )+ else:+ shutil.rmtree(skill_dir(), ignore_errors=True)+ print(+ "Removed the "+ + SPECS[tool]["name"]+ + " guard, hook and the shared skill."+ )+ if not done:+ print(+ "Could not edit "+ + shown(lay["config"])+ + ". Remove the "+ + GUARD_NAME+ + " entry by hand."+ )+ return 1+ return 0+++def main(argv):+ dry = "--dry-run" in argv+ args = [a for a in argv if a != "--dry-run"]+ repo_dir = None+ if "--repo" in args:+ i = args.index("--repo")+ if i + 1 >= len(args):+ print("--repo needs a folder.", file=sys.stderr)+ return 2+ repo_dir = os.path.abspath(args[i + 1])+ del args[i : i + 2]+ if not args or args[0] not in TOOLS:+ print(+ "Usage. install_harness.py <"+ + "|".join(TOOLS)+ + "> [install|doctor|uninstall] [--dry-run] [--repo DIR]",+ file=sys.stderr,+ )+ return 2+ tool = args[0]+ mode = args[1] if len(args) > 1 else "install"+ if mode not in ("install", "doctor", "uninstall"):+ print("Unknown mode. " + mode, file=sys.stderr)+ return 2+ if tool == "copilot-repo" and (not repo_dir or not os.path.isdir(repo_dir)):+ print(+ "copilot-repo installs into your app's repository. Pass --repo with that folder.",+ file=sys.stderr,+ )+ return 2+ lay = layout(tool, repo_dir)+ guard = os.path.join(lay["hooks"], GUARD_NAME)+ if mode == "doctor":+ return verify(tool, lay, guard, repo_dir)+ if mode == "uninstall":+ return uninstall(tool, lay, guard, dry)+ if dry:+ print("Dry run. Nothing is written.")+ print(" would copy the guard to " + shown(guard))+ if tool != "copilot-repo":+ print(" would copy the skill to " + shown(skill_dir()))+ if lay["command"]:+ print(" would write the audit command to " + shown(lay["command"]))+ register(tool, lay, guard, True)+ return 0+ print("Installing the App Store Compliance Playbook for " + SPECS[tool]["name"])+ copy_payload(tool, lay, guard)+ if not register(tool, lay, guard, False):+ verify(tool, lay, guard, repo_dir)+ return 1+ return verify(tool, lay, guard, repo_dir)+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/metadata-audit-test.sh b/scripts/metadata-audit-test.shindex a452747..b3609db 100755--- a/scripts/metadata-audit-test.sh+++ b/scripts/metadata-audit-test.sh@@ -24,7 +24,7 @@ T=$(mktemp -d); mkdir -p "$T/en-US"printf 'Lumina Studio' > "$T/en-US/name.txt"printf 'photo,editor,filters' > "$T/en-US/keywords.txt"printf 'A focused editor with layers and presets.' > "$T/en-US/description.txt"-printf '{"privacy_policy_url":"https://lumina.app/privacy"}' > "$T/m.json"+printf '{"privacy_policy_url":"https://lumina.app/privacy","support_url":"https://lumina.app/support"}' > "$T/m.json"OUT="$($AUDIT "$T" 2>&1)"; RC=$?if echo "$OUT" | grep -qE '\[(HIGH|MEDIUM)\]'; then bad "clean dir flagged high/medium"; else ok "clean dir passes"; fi# 5 propose writes the fixes file@@ -44,6 +44,92 @@ OUT="$($AUDIT 2>&1)"; RC=$?OUT="$($AUDIT --description "Subscribe for premium, auto-renew monthly" 2>&1)"echo "$OUT" | grep -q 'MISLEADING-PRICING\|Terms' && ok "flags subscription without terms" || bad "subscription terms"+# Google Play has its own limits and rules. Short description is 80 chars, not Apple's 170 promotional text.+LONG80="$(python3 -c 'print("x"*100)')"+OUT="$($AUDIT --platform google --title "Lumina" --short_description "$LONG80" --privacy_url https://lumina.app/p --contact_email [email protected] 2>&1)"+echo "$OUT" | grep -q 'over the 80 limit' && ok "google short description is held to 80 chars" || bad "google short description is held to 80 chars"+OK70="$(python3 -c 'print("x"*70)')"+OUT="$($AUDIT --platform google --title "Lumina" --short_description "$OK70" --privacy_url https://lumina.app/p --contact_email [email protected] 2>&1)"+echo "$OUT" | grep -q 'over the' && bad "a 70 char google short description passes" || ok "a 70 char google short description passes"+OUT="$($AUDIT --platform google --title "Lumina" --full_description "Get the Android app today" --privacy_url https://lumina.app/p --contact_email [email protected] 2>&1)"+echo "$OUT" | grep -q 'CROSS-PLATFORM-REFERENCE' && bad "an Android listing saying Android is not an Apple violation" || ok "an Android listing saying Android is not an Apple violation"+OUT="$($AUDIT --platform google --title "Lumina" --privacy_url https://lumina.app/p 2>&1)"+echo "$OUT" | grep -q 'MISSING-CONTACT-EMAIL' && ok "google listing without a contact email is flagged" || bad "google listing without a contact email is flagged"+OUT="$($AUDIT --platform windows --name "Lumina" 2>&1)"; RC=$?+[ "$RC" -eq 1 ] && echo "$OUT" | grep -q 'apple or google' && ok "an unknown platform exits 1" || bad "an unknown platform exits 1 (rc=$RC)"++# URLs must be real http or https URLs before any network check.+OUT="$($AUDIT --name 'Real App' --privacy_url nonsense --support_url https://real.app/help --check-urls 2>&1)"+echo "$OUT" | grep -q 'INVALID-METADATA-URL' && ! echo "$OUT" | grep -q '^Clean' && ok "a privacy url that is not a url is flagged" || bad "a privacy url that is not a url is flagged"+OUT="$($AUDIT --name 'Real App' --privacy_url ftp://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'INVALID-METADATA-URL' && ok "a non http privacy url is flagged" || bad "a non http privacy url is flagged"+OUT="$($AUDIT --name 'Real App' --privacy_url https://real.app/p 2>&1)"+echo "$OUT" | grep -q 'MISSING-SUPPORT-URL' && ok "apple listing without a support url is flagged" || bad "apple listing without a support url is flagged"++# A subscription needs a real Terms or EULA link, not the word terms.+OUT="$($AUDIT --description "Subscription. Terms apply." --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "the word terms without a link is flagged" || bad "the word terms without a link is flagged"+OUT="$($AUDIT --description "Subscription renews monthly. Terms of Use https://www.apple.com/legal/internet-services/itunes/dev/stdeula/" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && bad "the Apple standard EULA link satisfies the terms check" || ok "the Apple standard EULA link satisfies the terms check"+OUT="$($AUDIT --description "Subscription renews monthly. Terms https://real.app/terms" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && bad "an own terms link satisfies the terms check" || ok "an own terms link satisfies the terms check"+OUT="$($AUDIT --description "Monthly subscription for journaling." --terms_url https://journal.test/terms --privacy_url https://journal.test/p --support_url https://journal.test/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a separate terms_url field does not replace the link in the description" || bad "a separate terms_url field does not replace the link in the description"+OUT="$($AUDIT --name Photos --description "Monthly subscription. Privacy policy https://photos.app/privacy" --privacy_url https://photos.app/privacy --support_url https://photos.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a privacy link on a host named photos is not a Terms link" || bad "a privacy link on a host named photos is not a Terms link"+OUT="$($AUDIT --description "Monthly subscription. More at https://legal.example.app/x" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a legal-looking link without the word terms or EULA is still flagged" || bad "a legal-looking link without the word terms or EULA is still flagged"+OUT="$($AUDIT --description "Read our policy at https:///privacy" --privacy_url https://real.app/p --support_url https://real.app/help --check-urls 2>&1)"+echo "$OUT" | grep -q 'BOTH-UNREACHABLE-METADATA-URL' && ok "a malformed URL in the description is reported with --check-urls" || bad "a malformed URL in the description is reported with --check-urls"+OUT="$($AUDIT --description "Monthly subscription." --promotional_text "Terms of Use https://journal.test/terms" --privacy_url https://journal.test/p --support_url https://journal.test/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a Terms link only in the promotional text is flagged" || bad "a Terms link only in the promotional text is flagged"+OUT="$($AUDIT --description "Monthly subscription. Terms apply. Privacy https://tos.example/privacy" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a privacy link on a tos host is not a Terms link" || bad "a privacy link on a tos host is not a Terms link"+for u in https://journal.test/legal/privacy https://journal.test/tostadas; do+ OUT="$($AUDIT --description "Monthly subscription. Terms apply. Privacy $u" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+ echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "$u is not a Terms link" || bad "$u is not a Terms link"+done+OUT="$($AUDIT --description "Monthly subscription. Terms apply. Privacy https://journal.test/privacy?next=apple.com/legal/internet-services/itunes/dev/stdeula" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "the Apple EULA path in a query string is not a Terms link" || bad "the Apple EULA path in a query string is not a Terms link"+OUT="$($AUDIT --description "Monthly subscription. Terms of Use https://journal.test/termsofuse" --privacy_url https://real.app/p --support_url https://real.app/help 2>&1)"+! echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "a termsofuse path is a Terms link" || bad "a termsofuse path is a Terms link"++# Every locale is audited on its own, and each finding says which locale.+L="$(mktemp -d)"; mkdir -p "$L/en-US" "$L/de-DE"+printf 'Lumina Studio Photo Editor' > "$L/en-US/name.txt"+printf 'App fuer Android' > "$L/de-DE/name.txt"+printf '{"privacy_policy_url":"https://lumina.app/privacy","support_url":"https://lumina.app/support"}' > "$L/m.json"+OUT="$($AUDIT "$L" 2>&1)"+echo "$OUT" | grep 'CROSS-PLATFORM-REFERENCE' | grep -q 'de-DE' && ok "a short German name with a violation is audited and named" || bad "a short German name with a violation is audited and named"+echo "$OUT" | grep 'CROSS-PLATFORM-REFERENCE' | grep -q 'en-US' && bad "the clean English name is not blamed" || ok "the clean English name is not blamed"+rm -rf "$L"++# A fastlane android folder is audited with the Google rules even without --platform.+A="$(mktemp -d)"; mkdir -p "$A/android/en-US"+printf 'Lumina' > "$A/android/en-US/title.txt"+printf '%s' "$LONG80" > "$A/android/en-US/short_description.txt"+printf 'Get the Android app today' > "$A/android/en-US/full_description.txt"+printf '{"privacy_policy_url":"https://lumina.app/privacy","contact_email":"[email protected]"}' > "$A/android/m.json"+OUT="$($AUDIT "$A" 2>&1)"+echo "$OUT" | grep -q 'over the 80 limit' && ! echo "$OUT" | grep -q 'CROSS-PLATFORM-REFERENCE' && ok "a fastlane android folder uses the Google rules" || bad "a fastlane android folder uses the Google rules"+# Pointing at metadata/android itself, or at one of its locale folders, keeps the Google rules.+OUT="$($AUDIT "$A/android" 2>&1)"+echo "$OUT" | grep -q 'over the 80 limit' && ! echo "$OUT" | grep -q 'CROSS-PLATFORM-REFERENCE' && ok "the android folder given directly uses the Google rules" || bad "the android folder given directly uses the Google rules"+OUT="$($AUDIT "$A/android/en-US" 2>&1)"+echo "$OUT" | grep -q 'over the 80 limit' && ok "an android locale folder given directly uses the Google rules" || bad "an android locale folder given directly uses the Google rules"+rm -rf "$A"++# Two files that both supply one field never hide the overlong one, and the conflict is named (origin/main kept the longest).+for pair in "name.txt title.txt" "Name.txt title.txt" "name.txt m.json"; do+ C="$(mktemp -d)"; mkdir -p "$C/en-US"; set -- $pair+ printf 'This App Name Is Definitely Way Too Long For The Store' > "$C/en-US/$1"+ if [ "$2" = "m.json" ]; then printf '{"title":"Short"}' > "$C/en-US/m.json"; else printf 'Short' > "$C/en-US/$2"; fi+ printf '{"privacy_url":"https://a.io/p","support_url":"https://a.io/s"}' > "$C/u.json"+ OUT="$($AUDIT "$C" 2>&1)"+ echo "$OUT" | grep -q 'over the 30 limit' && echo "$OUT" | grep -q 'conflicting values' && ok "conflicting name files keep the overlong value and flag the conflict. $pair" || bad "conflicting name files keep the overlong value and flag the conflict. $pair"+ rm -rf "$C"+done+echo ""# A folder with no listing files was not audited. That is exit 1 with the file names to add, never a pass.E="$(mktemp -d)"@@ -53,5 +139,100 @@ OUT="$($AUDIT "$E/missing" 2>&1)"; RC=$?[ "$RC" -eq 1 ] && echo "$OUT" | grep -q "not a directory" && ok "a missing metadata folder exits 1" || bad "a missing metadata folder exits 1 (rc=$RC)"rm -rf "$E"+# two equal-length names, the risky one still audited+EQ="$(mktemp -d)"; mkdir -p "$EQ/en-US"+printf 'Android' > "$EQ/en-US/title.txt"; printf 'Journal' > "$EQ/en-US/name.txt"+printf 'https://journal.test/privacy' > "$EQ/en-US/privacy_url.txt"; printf 'https://journal.test/help' > "$EQ/en-US/support_url.txt"+OUT="$($AUDIT "$EQ" 2>&1)"+echo "$OUT" | grep -q 'CROSS-PLATFORM' && ok "an equal-length conflicting name is audited too" || bad "an equal-length conflicting name is audited too"+rm -rf "$EQ"++# two fields in conflict at once, the risky pairing across them is still audited+XC="$(mktemp -d)"; mkdir -p "$XC/en-US"+printf 'Notes xxxxxxxxxxxxxxxxxxxx' > "$XC/en-US/full_description.txt"+printf 'Subscribe' > "$XC/en-US/short_description.txt"+printf 'Terms https://j.test/terms' > "$XC/en-US/description.txt"+printf 'Notebooks' > "$XC/en-US/promo_text.txt"+printf 'Journal' > "$XC/en-US/name.txt"+printf 'https://j.test/privacy' > "$XC/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$XC/en-US/support_url.txt"+OUT="$($AUDIT "$XC" 2>&1)"+echo "$OUT" | grep -q 'APPLE-3.1.2-MISLEADING-PRICING' && ok "a risky pairing across two conflicting fields is audited" || bad "a risky pairing across two conflicting fields is audited"+rm -rf "$XC"+# a repeated command line field wins over an older alias for the same field, as on origin/main+OUT="$($AUDIT --name Android --title Journal --name Android --privacy_url https://j.test/p --support_url https://j.test/help 2>&1)"+echo "$OUT" | grep -q 'CROSS-PLATFORM' && ok "the last --name wins over an older --title alias" || bad "the last --name wins over an older --title alias"++# a locale value overrides a conflict between two parent files, so the overridden values raise nothing+OV="$(mktemp -d)"; mkdir -p "$OV/en-US"+printf '{"privacy_url":"broken"}' > "$OV/a.json"+printf '{"privacy_url":"https://common.test/privacy"}' > "$OV/b.json"+printf '{"name":"Journal","privacy_url":"https://j.test/privacy","support_url":"https://j.test/help"}' > "$OV/en-US/metadata.json"+OUT="$($AUDIT "$OV" 2>&1)"+! echo "$OUT" | grep -q 'INVALID-METADATA-URL' && ok "a locale value overrides a parent conflict" || bad "a locale value overrides a parent conflict"+rm -rf "$OV"++# fastlane's default folder fills every locale that lacks a field, so the name and keywords are audited together+DF="$(mktemp -d)"; mkdir -p "$DF/default" "$DF/en-US"+printf 'Journal' > "$DF/default/name.txt"+printf 'https://j.test/privacy' > "$DF/default/privacy_url.txt"; printf 'https://j.test/help' > "$DF/default/support_url.txt"+printf 'journal' > "$DF/en-US/keywords.txt"+OUT="$($AUDIT "$DF" 2>&1)"+echo "$OUT" | grep -q 'KEYWORD-FORMAT' && ! echo "$OUT" | grep -q 'MISSING-PRIVACY' && ok "a locale inherits the default folder" || bad "a locale inherits the default folder"+rm -rf "$DF"+# A URL scheme is case-insensitive, so an upper case HTTPS terms link counts+UC="$(mktemp -d)"; mkdir -p "$UC/en-US"+printf 'Journal' > "$UC/en-US/name.txt"+printf 'https://j.test/privacy' > "$UC/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$UC/en-US/support_url.txt"+printf 'Monthly subscription. Terms of Use. HTTPS://journal.test/terms' > "$UC/en-US/description.txt"+OUT="$($AUDIT "$UC" 2>&1)"+! echo "$OUT" | grep -q 'MISLEADING-PRICING' && ok "an upper case HTTPS terms link counts" || bad "an upper case HTTPS terms link counts"+rm -rf "$UC"+# fastlane review_information holds app review notes, it is not a locale needing its own URLs+RV="$(mktemp -d)"; mkdir -p "$RV/en-US" "$RV/review_information"+printf 'Journal' > "$RV/en-US/name.txt"+printf 'https://j.test/privacy' > "$RV/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$RV/en-US/support_url.txt"+printf 'Use demo account to sign in.' > "$RV/review_information/notes.txt"+OUT="$($AUDIT "$RV" 2>&1)"+! echo "$OUT" | grep -q 'review_information' && ok "review_information is not audited as a locale" || bad "review_information is not audited as a locale"+rm -rf "$RV"+# review notes are still audited for their content, once, with the first listing+RN="$(mktemp -d)"; mkdir -p "$RN/en-US" "$RN/review_information"+printf 'Journal' > "$RN/en-US/name.txt"+printf 'https://j.test/privacy' > "$RN/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$RN/en-US/support_url.txt"+printf 'TODO add a working review account.' > "$RN/review_information/notes.txt"+OUT="$($AUDIT "$RN" 2>&1)"+echo "$OUT" | grep -q 'BOTH-PLACEHOLDER' && ok "a placeholder in the review notes is still found" || bad "a placeholder in the review notes is still found"+rm -rf "$RN"+# each app's review notes are audited with that app, never overwritten by another app's notes+TA="$(mktemp -d)"+for a in app-a app-b; do mkdir -p "$TA/$a/metadata/en-US" "$TA/$a/metadata/review_information"+ printf 'Journal' > "$TA/$a/metadata/en-US/name.txt"+ printf 'https://j.test/privacy' > "$TA/$a/metadata/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$TA/$a/metadata/en-US/support_url.txt"; done+printf 'TODO add a working review account.' > "$TA/app-a/metadata/review_information/notes.txt"+printf 'Sign in with the supplied account.' > "$TA/app-b/metadata/review_information/notes.txt"+OUT="$($AUDIT "$TA" 2>&1)"+echo "$OUT" | grep -q 'BOTH-PLACEHOLDER' && ok "one app's review notes never hide another app's placeholder" || bad "one app's review notes never hide another app's placeholder"+rm -rf "$TA"+# fastlane's default folder is not a listing of its own when real locales sit beside it+DF2="$(mktemp -d)"; mkdir -p "$DF2/default" "$DF2/en-US"+printf 'writing' > "$DF2/default/keywords.txt"+printf 'Journal' > "$DF2/en-US/name.txt"+printf 'https://j.test/privacy' > "$DF2/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$DF2/en-US/support_url.txt"+OUT="$($AUDIT "$DF2" 2>&1)"+! echo "$OUT" | grep -q 'MISSING-PRIVACY' && ! echo "$OUT" | grep -q 'MISSING-SUPPORT' && ok "default/ is not audited as a listing beside real locales" || bad "default/ is not audited as a listing beside real locales"+rm -rf "$DF2"+# fastlane's default folder wins over a file further up, and the global review notes win over a locale's+DP="$(mktemp -d)"; mkdir -p "$DP/default" "$DP/en-US"+printf 'Journal' > "$DP/name.txt"; printf 'https://j.test/privacy' > "$DP/privacy_url.txt"; printf 'https://j.test/help' > "$DP/support_url.txt"+printf 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' > "$DP/default/name.txt"; printf 'writing' > "$DP/en-US/keywords.txt"+OUT="$($AUDIT "$DP" 2>&1)"+echo "$OUT" | grep -q 'BOTH-METADATA-DECORATION' && ok "the default folder's overlong name is audited over a root name" || bad "the default folder's overlong name is audited over a root name"+rm -rf "$DP"+GN="$(mktemp -d)"; mkdir -p "$GN/review_information" "$GN/en-US"+printf 'TODO add a working review account.' > "$GN/review_information/notes.txt"; printf 'Sign in.' > "$GN/en-US/review_notes.txt"+printf 'Journal' > "$GN/en-US/name.txt"; printf 'https://j.test/privacy' > "$GN/en-US/privacy_url.txt"; printf 'https://j.test/help' > "$GN/en-US/support_url.txt"+OUT="$($AUDIT "$GN" 2>&1)"+echo "$OUT" | grep -q 'BOTH-PLACEHOLDER' && ok "the global review notes are audited over a locale's notes" || bad "the global review notes are audited over a locale's notes"+rm -rf "$GN"echo "metadata-audit-test: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/metadata-audit.py b/scripts/metadata-audit.pyindex 3387bcc..7464ab2 100755--- a/scripts/metadata-audit.py+++ b/scripts/metadata-audit.py@@ -19,140 +19,379 @@ Usage:metadata-audit.py --name "..." --keywords "..." --description "..." audit fieldsmetadata-audit.py <dir> --propose write <dir>/.metadata-fixes.md with suggested fixesmetadata-audit.py <dir> --check-urls also HEAD-check URLs (needs network)+ metadata-audit.py <dir> --platform google use the Google Play limits and rules (default apple)++Every locale folder is audited on its own and each finding names its locale.+A folder named android in the path is audited with the Google rules unless+--platform is given.Exit codes: 0 clean or advisory, 1 the directory held nothing to audit, 2 a critical finding."""++import itertoolsimport osimport sysimport reimport jsonimport glob--FIELD_LIMITS = {"name": 30, "subtitle": 30, "keywords": 100, "promotional_text": 170, "description": 4000}+from urllib.parse import urlparse++FIELD_LIMITS = {+ "name": 30,+ "subtitle": 30,+ "keywords": 100,+ "promotional_text": 170,+ "description": 4000,+}+# Google Play listing limits, verified 2026-10-15 at support.google.com/googleplay/android-developer/answer/9859152+GOOGLE_FIELD_LIMITS = {"name": 30, "short_description": 80, "description": 4000}+PLATFORMS = ("apple", "google")+APPLE_STD_EULA = "apple.com/legal/internet-services/itunes/dev/stdeula"+URL_FIELDS = ("privacy_url", "support_url", "marketing_url", "terms_url")# fastlane / asc field file name aliases -> canonical fieldALIASES = {- "name": "name", "title": "name", "app_name": "name",+ "name": "name",+ "title": "name",+ "app_name": "name","subtitle": "subtitle","keywords": "keywords",- "description": "description", "full_description": "description",- "promotional_text": "promotional_text", "promo_text": "promotional_text", "short_description": "promotional_text",- "release_notes": "release_notes", "whats_new": "release_notes",- "review_notes": "review_notes", "notes": "review_notes",- "privacy_url": "privacy_url", "privacy_policy_url": "privacy_url",- "support_url": "support_url", "marketing_url": "marketing_url",+ "description": "description",+ "full_description": "description",+ "promotional_text": "promotional_text",+ "promo_text": "promotional_text",+ "short_description": "promotional_text",+ "release_notes": "release_notes",+ "whats_new": "release_notes",+ "review_notes": "review_notes",+ "notes": "review_notes",+ "privacy_url": "privacy_url",+ "privacy_policy_url": "privacy_url",+ "support_url": "support_url",+ "marketing_url": "marketing_url",+ "terms_url": "terms_url",+ "eula_url": "terms_url",+ "license_agreement_url": "terms_url",+ "contact_email": "contact_email",+ "email": "contact_email",}--OTHER_PLATFORMS = ["android", "google play", "play store", "windows phone", "blackberry"]-FUTURE = ["coming soon", "coming-soon", "will be available", "in a future update", "stay tuned", "future release"]+# On Google Play short_description is its own 80 char field, not Apple promotional text.+GOOGLE_ALIASES = dict(ALIASES, short_description="short_description")++OTHER_PLATFORMS = [+ "android",+ "google play",+ "play store",+ "windows phone",+ "blackberry",+]+FUTURE = [+ "coming soon",+ "coming-soon",+ "will be available",+ "in a future update",+ "stay tuned",+ "future release",+]NEGATIVE_APPLE = ["ios bug", "apple bug", "broken on ios", "fix for ios bug"]-PLACEHOLDER = ["lorem ipsum", "placeholder", "todo", "fixme", "test data", "dummy", "example.com"]+PLACEHOLDER = [+ "lorem ipsum",+ "placeholder",+ "todo",+ "fixme",+ "test data",+ "dummy",+ "example.com",+]CHINA_AI = ["chatgpt", "openai", "gemini", "claude", "anthropic", "copilot"]RANKING = ["#1", "number one", "best app", "top app", "free", "no.1", "no. 1"]# small safe profanity sample; teams extend in their own configCURSE = ["fuck", "shit", "asshole", "bitch", "bastard"]+def add(findings, sev, rule, field, msg, fix):- findings.append({"severity": sev, "rule": rule, "field": field, "message": msg, "fix": fix})+ findings.append(+ {"severity": sev, "rule": rule, "field": field, "message": msg, "fix": fix}+ )+++def url_syntax_ok(u):+ """True when u is an http or https URL with a host."""+ u = (u or "").strip()+ try:+ p = urlparse(u)+ host = p.hostname+ except ValueError:+ return False+ return p.scheme in ("http", "https") and bool(host) and " " not in u+++def is_terms_url(u):+ low = (u or "").lower()+ if not url_syntax_ok(low):+ return False+ p = urlparse(low)+ # Apple's standard EULA counts only as that page itself, never as text inside another URL.+ if p.netloc in ("apple.com", "www.apple.com") and p.path.startswith("/" + APPLE_STD_EULA.split("/", 1)[1]):+ return True+ if "privacy" in p.path:+ return False+ return bool(+ re.search(+ r"(^|[^a-z])(terms|eula|conditions|licen[cs]e)|(^|[^a-z])(tos|agb|legal)([^a-z]|$)",+ p.path,+ )+ )+def has_emoji(s):for ch in s:o = ord(ch)- if 0x1F000 <= o <= 0x1FAFF or 0x2600 <= o <= 0x27BF or 0x2190 <= o <= 0x21FF or o in (0x2122, 0x2B50, 0xFE0F):+ if (+ 0x1F000 <= o <= 0x1FAFF+ or 0x2600 <= o <= 0x27BF+ or 0x2190 <= o <= 0x21FF+ or o in (0x2122, 0x2B50, 0xFE0F)+ ):return Truereturn False+def lc(s):return (s or "").lower()-def audit_fields(fields, check_urls=False):++def audit_fields(fields, check_urls=False, platform="apple"):findings = []+ apple = platform == "apple"name = fields.get("name", "")subtitle = fields.get("subtitle", "")keywords = fields.get("keywords", "")# char limits- for f, limit in FIELD_LIMITS.items():+ for f, limit in (FIELD_LIMITS if apple else GOOGLE_FIELD_LIMITS).items():v = fields.get(f, "")if v and len(v) > limit:- add(findings, "high", "BOTH-METADATA-DECORATION", f,- f"{f} is {len(v)} chars, over the {limit} limit", f"Trim {f} to {limit} characters or fewer")+ add(+ findings,+ "high",+ "BOTH-METADATA-DECORATION",+ f,+ f"{f} is {len(v)} chars, over the {limit} limit",+ f"Trim {f} to {limit} characters or fewer",+ )# decoration in name / subtitlefor f in ("name", "subtitle"):v = fields.get(f, "")if v and has_emoji(v):- add(findings, "medium", "BOTH-METADATA-DECORATION", f, f"{f} contains an emoji", f"Remove emoji from {f}")+ add(+ findings,+ "medium",+ "BOTH-METADATA-DECORATION",+ f,+ f"{f} contains an emoji",+ f"Remove emoji from {f}",+ )for r in RANKING:if r in lc(v):- add(findings, "high", "BOTH-METADATA-DECORATION", f,- f"{f} contains a ranking or price claim ({r})", f"Remove ranking and price claims from {f}")+ add(+ findings,+ "high",+ "BOTH-METADATA-DECORATION",+ f,+ f"{f} contains a ranking or price claim ({r})",+ f"Remove ranking and price claims from {f}",+ )words = [w for w in re.findall(r"[A-Za-z]{3,}", v) if w.isupper()]if len(words) >= 2:- add(findings, "medium", "BOTH-METADATA-DECORATION", f, f"{f} uses ALL CAPS words", f"Use normal case in {f} except a real brand")-- # other platform mentions (Apple side)- for f, v in fields.items():+ add(+ findings,+ "medium",+ "BOTH-METADATA-DECORATION",+ f,+ f"{f} uses ALL CAPS words",+ f"Use normal case in {f} except a real brand",+ )++ # other platform mentions (Apple side only, an Android listing may say Android)+ for f, v in fields.items() if apple else ():for term in OTHER_PLATFORMS:if term in lc(v):- add(findings, "high", "APPLE-2.3-CROSS-PLATFORM-REFERENCE", f,- f"{f} mentions another platform ({term})", f"Remove the reference to {term} from {f}")+ add(+ findings,+ "high",+ "APPLE-2.3-CROSS-PLATFORM-REFERENCE",+ f,+ f"{f} mentions another platform ({term})",+ f"Remove the reference to {term} from {f}",+ )# future functionality- for f, v in fields.items():+ for f, v in fields.items() if apple else ():for term in FUTURE:if term in lc(v):- add(findings, "medium", "APPLE-2.3-FUTURE-FUNCTIONALITY", f,- f"{f} promises future functionality ({term})", "Describe only what the build does today")+ add(+ findings,+ "medium",+ "APPLE-2.3-FUTURE-FUNCTIONALITY",+ f,+ f"{f} promises future functionality ({term})",+ "Describe only what the build does today",+ )# negative apple sentiment- for f, v in fields.items():+ for f, v in fields.items() if apple else ():for term in NEGATIVE_APPLE:if term in lc(v):- add(findings, "medium", "APPLE-2.3-NEGATIVE-APPLE-SENTIMENT", f,- f"{f} references an iOS bug or Apple negatively", "Remove negative Apple references")+ add(+ findings,+ "medium",+ "APPLE-2.3-NEGATIVE-APPLE-SENTIMENT",+ f,+ f"{f} references an iOS bug or Apple negatively",+ "Remove negative Apple references",+ )# placeholder / testfor f, v in fields.items():for term in PLACEHOLDER:if term in lc(v):- add(findings, "high", "BOTH-PLACEHOLDER", f, f"{f} contains placeholder text ({term})", "Replace placeholder with real content")+ add(+ findings,+ "high",+ "BOTH-PLACEHOLDER",+ f,+ f"{f} contains placeholder text ({term})",+ "Replace placeholder with real content",+ )# curse wordsfor f, v in fields.items():for term in CURSE:if re.search(r"\b" + re.escape(term) + r"\b", lc(v)):- add(findings, "high", "APPLE-2.3-CURSE-WORD", f, f"{f} contains profanity", "Remove profanity from the listing")-- # keywords formatting- if keywords:+ add(+ findings,+ "high",+ "APPLE-2.3-CURSE-WORD",+ f,+ f"{f} contains profanity",+ "Remove profanity from the listing",+ )++ # keywords formatting (Apple only, Google Play has no keywords field)+ if keywords and apple:if ", " in keywords:- add(findings, "low", "APPLE-2.3-KEYWORD-FORMAT", "keywords",- "keywords field has spaces after commas, which wastes the 100 char budget", "Use commas with no spaces between keywords")+ add(+ findings,+ "low",+ "APPLE-2.3-KEYWORD-FORMAT",+ "keywords",+ "keywords field has spaces after commas, which wastes the 100 char budget",+ "Use commas with no spaces between keywords",+ )kw = set(w for w in re.split(r"[,\s]+", lc(keywords)) if w)dup = kw & set(re.findall(r"[a-z]{3,}", lc(name + " " + subtitle)))if dup:- add(findings, "low", "APPLE-2.3-KEYWORD-FORMAT", "keywords",- f"keywords repeat words already in name or subtitle ({', '.join(sorted(dup))})", "Drop duplicated words, the name and subtitle are already indexed")+ add(+ findings,+ "low",+ "APPLE-2.3-KEYWORD-FORMAT",+ "keywords",+ f"keywords repeat words already in name or subtitle ({', '.join(sorted(dup))})",+ "Drop duplicated words, the name and subtitle are already indexed",+ )# missing privacy policy urlif not fields.get("privacy_url"):- add(findings, "high", "BOTH-MISSING-PRIVACY-POLICY", "privacy_url",- "no privacy policy URL found in the metadata", "Set the Privacy Policy URL in App Store Connect and the Play listing")-- # subscription ToS / PP in description- desc = lc(fields.get("description", "") + " " + fields.get("promotional_text", ""))- if any(t in desc for t in ("subscription", "subscribe", "auto-renew", "per month", "per year")):- if "terms" not in desc and "eula" not in desc:- add(findings, "high", "APPLE-3.1.2-MISLEADING-PRICING", "description",- "subscription mentioned but no Terms of Use or EULA link in the description", "Add functional Terms of Use and Privacy Policy links to the description and the paywall")-- # china AI references (advisory, storefront dependent)- for f in ("name", "subtitle", "keywords", "description"):+ add(+ findings,+ "high",+ "BOTH-MISSING-PRIVACY-POLICY",+ "privacy_url",+ "no privacy policy URL found in the metadata",+ "Set the Privacy Policy URL in App Store Connect and the Play listing",+ )++ # URL fields must be real http or https URLs, checked before any network call+ for f in URL_FIELDS:+ v = fields.get(f, "")+ if v and not url_syntax_ok(v):+ add(+ findings,+ "high",+ "BOTH-INVALID-METADATA-URL",+ f,+ f"{f} is not an http or https URL with a host ({v[:60]})",+ f"Set {f} to a full https URL",+ )++ if apple and not fields.get("support_url"):+ add(+ findings,+ "high",+ "APPLE-MISSING-SUPPORT-URL",+ "support_url",+ "no support URL found in the metadata, App Store Connect requires one",+ "Set the Support URL in App Store Connect",+ )+ if not apple:+ email = fields.get("contact_email", "")+ if not email:+ add(+ findings,+ "medium",+ "GOOGLE-MISSING-CONTACT-EMAIL",+ "contact_email",+ "no contact email found, the Play listing requires one",+ "Set the contact email in the Play Console store listing",+ )+ elif not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email.strip()):+ add(+ findings,+ "medium",+ "GOOGLE-MISSING-CONTACT-EMAIL",+ "contact_email",+ f"contact email is not a valid address ({email[:60]})",+ "Set a working contact email in the Play Console",+ )++ # subscription terms, a real Terms or EULA URL is required, the word alone is not enough+ raw_desc = fields.get("description", "") + " " + fields.get("promotional_text", "")+ desc = lc(raw_desc)+ if apple and any(+ t in desc+ for t in ("subscription", "subscribe", "auto-renew", "per month", "per year")+ ):+ links = re.findall(+ r"https?://[^\s)\"']+|(?:www\.)?apple\.com/legal/[^\s)\"']+",+ fields.get("description", ""),+ re.IGNORECASE,+ )+ # Apple reads the link in the description itself, so promotional text or a terms_url field never replaces it.+ has_terms = any(is_terms_url(u) for u in links) and ("terms" in desc or "eula" in desc)+ if not has_terms:+ add(+ findings,+ "high",+ "APPLE-3.1.2-MISLEADING-PRICING",+ "description",+ "subscription mentioned but no Terms of Use or EULA link in the description",+ "Add functional Terms of Use and Privacy Policy links to the description and the paywall",+ )++ # china AI references (advisory, storefront dependent, Apple only)+ for f in ("name", "subtitle", "keywords", "description") if apple else ():v = lc(fields.get(f, ""))for term in CHINA_AI:if term in v:- add(findings, "medium", "CHINA-AI-REFERENCES", f,- f"{f} references an external AI service ({term}), which can trigger a China storefront rejection", "Remove or localize external AI references for the China storefront")+ add(+ findings,+ "medium",+ "CHINA-AI-REFERENCES",+ f,+ f"{f} references an external AI service ({term}), which can trigger a China storefront rejection",+ "Remove or localize external AI references for the China storefront",+ )break# unreachable URLs@@ -160,65 +399,221 @@ def audit_fields(fields, check_urls=False):urls = set()for v in fields.values():urls.update(re.findall(r"https?://[^\s)\"']+", v or ""))- for u in sorted(urls):+ for u in sorted(u for u in urls if not url_syntax_ok(u)):+ add(+ findings,+ "high",+ "BOTH-UNREACHABLE-METADATA-URL",+ "url",+ f"URL is malformed: {u}",+ "Fix or remove the broken URL before submission",+ )+ for u in sorted(u for u in urls if url_syntax_ok(u)):ok = _url_ok(u)if ok is False:- add(findings, "high", "BOTH-UNREACHABLE-METADATA-URL", "url", f"URL does not load: {u}", "Fix or remove the broken URL before submission")+ add(+ findings,+ "high",+ "BOTH-UNREACHABLE-METADATA-URL",+ "url",+ f"URL does not load: {u}",+ "Fix or remove the broken URL before submission",+ )return findings+def _url_ok(u):try:import urllib.request- req = urllib.request.Request(u, method="HEAD", headers={"User-Agent": "metadata-audit"})++ req = urllib.request.Request(+ u, method="HEAD", headers={"User-Agent": "metadata-audit"}+ )with urllib.request.urlopen(req, timeout=8) as r:return 200 <= r.status < 400except Exception:return False-def load_dir(d):- fields = {}- for path in glob.glob(os.path.join(d, "**", "*.txt"), recursive=True):- base = os.path.splitext(os.path.basename(path))[0].lower()- canon = ALIASES.get(base)- if not canon:++def _read_text(path):+ try:+ with open(path, encoding="utf-8", errors="ignore") as fh:+ return fh.read().strip()+ except Exception:+ return None+++def _read_json(path):+ try:+ with open(path, encoding="utf-8", errors="ignore") as fh:+ return json.load(fh)+ except Exception:+ return None+++def _read_group_files(d):+ """Return {folder relative to d: [(path, base or None, text or dict)]} for listing files."""+ groups = {}+ for path in sorted(glob.glob(os.path.join(d, "**", "*.txt"), recursive=True)):+ txt = _read_text(path)+ if txt is None:continue- try:- txt = open(path, encoding="utf-8", errors="ignore").read().strip()- except Exception:+ rel = os.path.relpath(os.path.dirname(path), d)+ groups.setdefault(rel, []).append(+ (path, os.path.splitext(os.path.basename(path))[0].lower(), txt)+ )+ for path in sorted(glob.glob(os.path.join(d, "**", "*.json"), recursive=True)):+ data = _read_json(path)+ if isinstance(data, dict):+ groups.setdefault(os.path.relpath(os.path.dirname(path), d), []).append(+ (path, None, data)+ )+ return groups+++def group_platform(rel, root=None):+ # The root's own name and its parent count too, so metadata/android and metadata/android/en-US stay Google.+ parts = rel.split(os.sep)+ if root:+ parts = os.path.abspath(root).split(os.sep)[-2:] + parts+ return "google" if "android" in [p.lower() for p in parts] else "apple"+++def _fields_from(entries, aliases, conflicts=None):+ """Two files for one field keep the longest value, as origin/main did, and the clash goes to conflicts."""+ fields, src = {}, {}+ for path, base, val in entries:+ pairs = (+ [(aliases.get(base), val)]+ if base is not None+ else [+ (aliases.get(str(k).lower()), v.strip() if isinstance(v, str) else "")+ for k, v in val.items()+ ]+ )+ for canon, v in pairs:+ if not canon or not v:+ continue+ name = os.path.basename(path)+ if canon in fields and fields[canon] != v:+ keep_old = len(v) <= len(fields[canon])+ if conflicts is not None:+ conflicts.append((canon, src[canon], name, v if keep_old else fields[canon]))+ if keep_old:+ continue+ fields[canon], src[canon] = v, name+ return fields+++def _is_below(child, parent):+ return child != parent and (parent == "." or child.startswith(parent + os.sep))+++NON_LOCALE_DIRS = {"review_information", "trade_representative_contact_information"}+++def load_locales(d, platform=None):+ """One audit unit per locale folder, each audited on its own.+ Files in a parent folder fill gaps in every locale below it.+ Returns a list of (label, platform, fields, conflicts)."""+ groups = _read_group_files(d)+ rels = sorted(groups)+ units = []+ unit_rels = []+ app_level = {}+ for rel in rels:+ # fastlane keeps app review and trade contact details in these folders, they are not store listings+ if os.path.basename(rel) in NON_LOCALE_DIRS:+ app_level.setdefault(os.path.dirname(rel), {}).update(_fields_from(groups[rel], ALIASES))continue- # keep the longest value if multiple locales- if len(txt) > len(fields.get(canon, "")):- fields[canon] = txt- # also look for a json metadata file with urls- for jp in glob.glob(os.path.join(d, "**", "*.json"), recursive=True):- try:- data = json.load(open(jp, encoding="utf-8", errors="ignore"))- except Exception:+ plat = platform or group_platform(rel, d)+ aliases = GOOGLE_ALIASES if plat == "google" else ALIASES+ # fastlane's default folder only fills the real locales beside it, it is not a listing of its own+ if os.path.basename(rel) == "default" and any(+ o != rel and os.path.dirname(o) == os.path.dirname(rel)+ and os.path.basename(o) not in NON_LOCALE_DIRS and _fields_from(groups[o], aliases)+ for o in rels+ ):continue- if isinstance(data, dict):- for k, v in data.items():- kk = ALIASES.get(k.lower())- if kk and isinstance(v, str) and v.strip() and len(v) > len(fields.get(kk, "")):- fields[kk] = v.strip()+ clash = []+ own = _fields_from(groups[rel], aliases, clash)+ if not own:+ continue+ # a folder that holds only shared values (urls, email) is not a locale when locales sit below it+ has_children = any(+ _is_below(o, rel) and _fields_from(groups[o], aliases) for o in rels+ )+ if has_children and not (set(own) - set(URL_FIELDS) - {"contact_email"}):+ continue+ merged, inherited = {}, []+ for a in sorted((o for o in rels if _is_below(rel, o)), key=len):+ near = []+ got = _fields_from(groups[a], aliases, near)+ inherited = [c for c in inherited if c[0] not in got] + near+ merged.update(got)+ # fastlane fills a locale from its default folder, which wins over a file further up, and both values are audited+ sib = os.path.join(os.path.dirname(rel), "default") if rel != "." else None+ if sib and sib.startswith("." + os.sep):+ sib = sib[2:]+ if sib and sib != rel and sib in groups and os.path.basename(rel) != "default":+ near = []+ got = _fields_from(groups[sib], aliases, near)+ up = [(k, "default", "parent folder", merged[k]) for k, v in got.items() if k in merged and merged[k] != v]+ inherited = [c for c in inherited if c[0] not in got] + near + up+ merged.update(got)+ merged.update(own)+ clash += [c for c in inherited if c[0] not in own]+ label = rel if rel != "." else (os.path.basename(os.path.abspath(d)) or d)+ units.append((label, plat, merged, sorted(set(clash))))+ unit_rels.append(rel)+ # review notes belong to their own app, so each app's notes are audited once with that app's first listing+ for parent, fields in sorted(app_level.items()):+ home = next((i for i, r in enumerate(unit_rels) if parent in ("", ".") or r == parent or _is_below(r, parent)), None)+ if home is None:+ units.append((os.path.join(parent, "review_information") if parent else "review_information", platform or "apple", fields, []))+ else:+ label, plat, merged, clash = units[home]+ extra = [(k, "review_information", "locale", merged[k]) for k, v in fields.items() if k in merged and merged[k] != v]+ units[home] = (label, plat, {**merged, **fields}, sorted(set(list(clash) + extra)))+ return units+++def load_dir(d):+ """Backward compatible flat view, the union of every locale, the longest value wins as on origin/main."""+ fields = {}+ for _label, _plat, f, _clash in load_locales(d):+ for k, v in f.items():+ if len(v) > len(fields.get(k, "")):+ fields[k] = vreturn fields+def main():args = sys.argv[1:]check_urls = "--check-urls" in argspropose = "--propose" in argsargs = [a for a in args if a not in ("--check-urls", "--propose")]- fields = {}+ platform = None+ if "--platform" in args:+ i = args.index("--platform")+ platform = (args[i + 1] if i + 1 < len(args) else "").lower()+ del args[i : i + 2]+ if platform not in PLATFORMS:+ print(+ f"metadata-audit. unknown platform '{platform}'. Use apple or google.",+ file=sys.stderr,+ )+ return 1++ raw = []d = Nonei = 0while i < len(args):a = args[i]if a.startswith("--"):- key = a[2:]- val = args[i+1] if i+1 < len(args) else ""- canon = ALIASES.get(key, key)- fields[canon] = val+ raw.append((a[2:], args[i + 1] if i + 1 < len(args) else ""))i += 2elif os.path.isdir(a) or d is None:d = a@@ -227,21 +622,81 @@ def main():i += 1if d and not os.path.isdir(d):- print(f"metadata-audit. {d} is not a directory. Nothing was audited.", file=sys.stderr)+ print(+ f"metadata-audit. {d} is not a directory. Nothing was audited.",+ file=sys.stderr,+ )return 1- if d:- fields.update({k: v for k, v in load_dir(d).items() if k not in fields})- if not fields and d:+ def cli_fields(plat):+ aliases = GOOGLE_ALIASES if plat == "google" else ALIASES+ out = {}+ for k, v in raw:+ out[aliases.get(k, k)] = v+ return out++ units = []+ if d:+ for label, plat, f, clash in load_locales(d, platform):+ cli = cli_fields(plat)+ f.update(cli)+ units.append((label, plat, f, [c for c in clash if c[0] not in cli]))+ if not units and raw:+ plat = platform or "apple"+ units.append(("command line", plat, cli_fields(plat), []))++ if not units and d:print(f"metadata-audit. no listing files found in {d}. Nothing was audited.")- print("Add name.txt, subtitle.txt, keywords.txt and description.txt (the fastlane metadata layout),")- print("or pull them with scripts/pull-metadata.sh, or pass --name, --keywords and --description.")+ print(+ "Add name.txt, subtitle.txt, keywords.txt and description.txt (the fastlane metadata layout),"+ )+ print(+ "or pull them with scripts/pull-metadata.sh, or pass --name, --keywords and --description."+ )return 1- if not fields:- print("metadata-audit. nothing to audit. Pass a metadata directory, or --name, --keywords and --description.")+ if not units:+ print(+ "metadata-audit. nothing to audit. Pass a metadata directory, or --name, --keywords and --description."+ )return 0- findings = audit_fields(fields, check_urls=check_urls)+ findings = []+ print("== Metadata Audit ==")+ for label, plat, fields, clash in units:+ print(+ f"Locale {label} ({plat}). Fields audited. {', '.join(sorted(fields.keys()))}"+ )+ unit = audit_fields(fields, check_urls=check_urls, platform=plat)+ seen = {(f["severity"], f["rule"], f["field"], f["message"]) for f in unit}+ # Every combination of the conflicting values is audited, so no pairing across fields hides a rejection risk.+ options = {}+ for canon, a, b, alt in clash:+ options.setdefault(canon, [fields.get(canon)])+ if alt not in options[canon]:+ options[canon].append(alt)+ names = sorted(options)+ total = 1+ for n in names:+ total *= len(options[n])+ for combo in itertools.islice(itertools.product(*(options[n] for n in names)), 1, 4096):+ for f in audit_fields({**fields, **dict(zip(names, combo))}, check_urls=check_urls, platform=plat):+ key = (f["severity"], f["rule"], f["field"], f["message"])+ if key not in seen:+ seen.add(key)+ unit.append(f)+ for canon, a, b, alt in clash:+ add(+ unit,+ "medium",+ "BOTH-METADATA-DECORATION",+ canon,+ f"{canon} has conflicting values in {a} and {b}, both were audited"+ + ("" if total <= 4096 else f" (the first 4096 of {total} value combinations)"),+ f"Keep one file for {canon} so the store gets the value you audited",+ )+ for f in unit:+ f["locale"] = label+ findings.append(f)order = {"critical": 0, "high": 1, "medium": 2, "low": 3}findings.sort(key=lambda f: order.get(f["severity"], 9))@@ -250,13 +705,11 @@ def main():med = sum(1 for f in findings if f["severity"] == "medium")low = sum(1 for f in findings if f["severity"] == "low")- print("== Metadata Audit ==")- print(f"Fields audited. {', '.join(sorted(fields.keys()))}")print("")if not findings:print("Clean. No metadata rejection risks found.")for f in findings:- print(f" [{f['severity'].upper()}] {f['rule']} ({f['field']})")+ print(f" [{f['severity'].upper()}] {f['rule']} ({f['field']}, {f['locale']})")print(f" {f['message']}")print(f" fix. {f['fix']}")print("")@@ -264,15 +717,23 @@ def main():if propose and d:report = os.path.join(d, ".metadata-fixes.md")- lines = ["# Metadata fix suggestions", "",- "Proposed fixes from metadata-audit. Review each before applying. Source copy is not overwritten.", ""]+ lines = [+ "# Metadata fix suggestions",+ "",+ "Proposed fixes from metadata-audit. Review each before applying. Source copy is not overwritten.",+ "",+ ]for f in findings:- lines.append(f"- [{f['severity']}] {f['field']}. {f['message']}")+ lines.append(+ f"- [{f['severity']}] {f['locale']} {f['field']}. {f['message']}"+ )lines.append(f" - fix. {f['fix']}")- open(report, "w").write("\n".join(lines) + "\n")+ with open(report, "w", encoding="utf-8") as fh:+ fh.write("\n".join(lines) + "\n")print(f"Wrote suggestions to {report}")return 2 if crit > 0 else 0+if __name__ == "__main__":sys.exit(main())diff --git a/scripts/monitor-ai-policy-test.sh b/scripts/monitor-ai-policy-test.shindex 8841655..8cbd8c7 100755--- a/scripts/monitor-ai-policy-test.sh+++ b/scripts/monitor-ai-policy-test.sh@@ -171,6 +171,69 @@ assert not m.analyze_announcements(items, ["llm"]), "matched a word that only apPYrm -rf "$HT"+# Issue #1000. Feed edge cases found in the October review, one fixture per case.+I1000="$(mktemp -d)"+MOD="$(dirname "$0")/monitor-ai-policy.py"+feed_case() {+ # $1 label, $2 feed file, $3 python assertions over the parsed items+ python3 - "$2" "$MOD" "$3" <<'PY' && ok "$1" || bad "$1"+import importlib.util, sys+spec = importlib.util.spec_from_file_location("m", sys.argv[2]); m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)+items = m.parse_rss_feed("file://" + sys.argv[1])+exec(sys.argv[3])+PY+}+cat > "$I1000/rel.atom" <<'XML'+<feed xmlns="http://www.w3.org/2005/Atom"><entry><title>Policy</title>+<link rel="alternate" href="https://example.invalid/news/policy"/>+<link rel="self" href="https://example.invalid/feeds/entry/1"/>+<summary>AI update</summary></entry>+<entry><title>Policy two</title>+<link rel="self" href="https://example.invalid/feeds/entry/2"/>+<link href="https://example.invalid/news/two"/>+<summary>AI update</summary></entry></feed>+XML+feed_case "#1000 an Atom citation prefers rel alternate or no rel over rel self" "$I1000/rel.atom" \+ 'assert [i["link"] for i in items] == ["https://example.invalid/news/policy", "https://example.invalid/news/two"], items'+cat > "$I1000/base.atom" <<'XML'+<feed xmlns="http://www.w3.org/2005/Atom" xml:base="https://example.invalid/news/"><entry><title>Policy</title>+<link rel="alternate" href="policy"/><summary>AI update</summary></entry></feed>+XML+feed_case "#1000 an inherited xml:base resolves a relative Atom link" "$I1000/base.atom" \+ 'assert items[0]["link"] == "https://example.invalid/news/policy", items'+mkdir -p "$I1000/feeds"+cat > "$I1000/feeds/rel-base.atom" <<'XML'+<feed xmlns="http://www.w3.org/2005/Atom" xml:base="../news/"><entry><title>Policy</title>+<link rel="alternate" href="policy"/><summary>AI update</summary></entry></feed>+XML+feed_case "#1000 a relative xml:base resolves against the feed's own URL" "$I1000/feeds/rel-base.atom" \+ 'assert items[0]["link"] == "file://" + sys.argv[1].rsplit("/feeds/", 1)[0] + "/news/policy", items'+cat > "$I1000/encoded.rss" <<'XML'+<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><item><title>Platform news</title>+<description>Short teaser.</description>+<content:encoded><![CDATA[<p>Apps that call an <b>LLM</b> must disclose it.</p>]]></content:encoded>+<link>https://example.invalid/encoded</link></item></channel></rss>+XML+feed_case "#1000 the RSS Content module body is read for keyword matching" "$I1000/encoded.rss" \+ 'assert "LLM" in items[0]["description"], items; assert m.analyze_announcements(items, ["llm"]), "keyword only in content:encoded was missed"'+cat > "$I1000/dates.atom" <<'XML'+<feed xmlns="http://www.w3.org/2005/Atom"><entry><title>A</title>+<published>2026-01-01T00:00:00Z</published><updated>2026-02-02T00:00:00Z</updated><summary>x</summary></entry>+<entry><title>B</title>+<updated>2026-02-02T00:00:00Z</updated><published>2026-01-01T00:00:00Z</published><summary>x</summary></entry>+<entry><title>C</title><updated>2026-02-02T00:00:00Z</updated><summary>x</summary></entry></feed>+XML+cat > "$I1000/dc.rdf" <<'XML'+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/">+<item rdf:about="https://example.invalid/rdf"><title>RDF item</title><link>https://example.invalid/rdf</link>+<description>x</description><dc:date>2026-03-03T00:00:00Z</dc:date></item></rdf:RDF>+XML+feed_case "#1000 dates prefer published, then updated, regardless of element order" "$I1000/dates.atom" \+ 'assert [i["pubDate"] for i in items] == ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z", "2026-02-02T00:00:00Z"], items'+feed_case "#1000 an RSS 1.0 dc:date is read when no published or updated exists" "$I1000/dc.rdf" \+ 'assert items[0]["pubDate"] == "2026-03-03T00:00:00Z", items'+rm -rf "$I1000"+echo ""echo "AI Policy Monitor test suite: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/monitor-ai-policy.py b/scripts/monitor-ai-policy.pyindex 4a07d10..bc57545 100755--- a/scripts/monitor-ai-policy.py+++ b/scripts/monitor-ai-policy.py@@ -6,6 +6,7 @@ import osimport sysimport reimport argparse+import urllib.parseimport urllib.requestimport xml.etree.ElementTree as ETimport json@@ -42,6 +43,9 @@ def _visible_markup(m):FEED_NAMESPACES = ("", "http://www.w3.org/2005/Atom", "http://purl.org/rss/1.0/")+RSS_CONTENT_NS = "http://purl.org/rss/1.0/modules/content/"+DC_NS = "http://purl.org/dc/elements/1.1/"+XML_BASE = "{http://www.w3.org/XML/1998/namespace}base"_XHTML_INLINE = {"a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "del", "dfn", "em", "font", "i","ins", "kbd", "label", "mark", "q", "s", "samp", "small", "span", "strong", "sub", "sup",@@ -267,6 +271,20 @@ def parse_rss_feed(url):def ns(e):return e.tag[1:].split("}", 1)[0] if e.tag.startswith("{") else ""+ parents = {c: p for p in root.iter() for c in p}++ def base_of(e):+ """The xml:base in scope at e, resolved from the fetched URL down."""+ chain = []+ while e is not None:+ chain.append(e.get(XML_BASE))+ e = parents.get(e)+ base = url+ for b in reversed(chain):+ if b and b.strip():+ base = urllib.parse.urljoin(base, b.strip())+ return base+for elem in root.iter():if not isinstance(elem.tag, str):continue@@ -274,13 +292,23 @@ def parse_rss_feed(url):if tag in ("item", "entry") and ns(elem) in FEED_NAMESPACES:title = ""desc_parts = []- link = ""- pub_date = ""+ links = [] # (preferred, href, element)+ dates = {}for child in elem:- if not isinstance(child.tag, str) or ns(child) != ns(elem):- continue # an extension element never stands in for the feed's own+ if not isinstance(child.tag, str):+ continuectag = clean_tag(child.tag)+ if ns(child) == RSS_CONTENT_NS and ctag == "encoded":+ part = clean_html_text(child.text or "")+ if part:+ desc_parts.append(part) # the RSS Content module body is HTML+ continue+ if ns(child) == DC_NS and ctag == "date":+ dates.setdefault("dc", child.text or "")+ continue+ if ns(child) != ns(elem):+ continue # an extension element never stands in for the feed's ownif ctag == "title":title = _feed_text(child, tag == "entry", "title")elif ctag in ("description", "summary", "content"):@@ -288,13 +316,24 @@ def parse_rss_feed(url):if part:desc_parts.append(part) # summary and content both countelif ctag == "link":- link_val = child.get("href")- if link_val:- link = link_val- else:- link = child.text or ""- elif ctag in ("pubDate", "published", "updated"):- pub_date = child.text or ""+ href = (child.get("href") or child.text or "").strip()+ rel = (child.get("rel") or "alternate").strip().lower()+ if href:+ links.append((rel == "alternate", href, child))+ elif ctag in ("pubDate", "published"):+ dates.setdefault("published", child.text or "")+ elif ctag == "updated":+ dates.setdefault("updated", child.text or "")++ link = ""+ if links: # alternate or no rel first, any other relation only as a fallback+ _, href, link_elem = next((x for x in links if x[0]), links[0])+ base = base_of(link_elem)+ link = urllib.parse.urljoin(base, href)+ pub_date = next(+ (dates[k] for k in ("published", "updated", "dc") if dates.get(k, "").strip()),+ "",+ )items.append({diff --git a/scripts/monitor-privacy-test.sh b/scripts/monitor-privacy-test.shindex 0ec993f..155ff0d 100755--- a/scripts/monitor-privacy-test.sh+++ b/scripts/monitor-privacy-test.sh@@ -119,6 +119,36 @@ elsebad "PR Draft file was not created"fi+# Source trust is decided by the URL host, never by text+if python3 - scripts/monitor-privacy.py <<'TRUSTPY'+import importlib.util, sys+spec = importlib.util.spec_from_file_location("mon", sys.argv[1])+mon = importlib.util.module_from_spec(spec)+spec.loader.exec_module(mon)+cases = [+ ("spoofed host suffix", {"title": "Rule", "description": "", "link": "https://ftc.gov.attacker.invalid/article"}, False),+ ("agency word in title", {"title": "FTC announces a new rule", "description": "", "link": "https://news.example.invalid/story"}, False),+ ("official domain in text only", {"title": "Rule", "description": "see ftc.gov and developer.apple.com", "link": "https://news.example.invalid/story"}, False),+ ("userinfo trick", {"title": "Rule", "description": "", "link": "https://[email protected]/"}, False),+ ("lookalike vendor host", {"title": "Rule", "description": "", "link": "https://developer.apple.com.attacker.invalid/x"}, False),+ ("legitimate subdomain", {"title": "Rule", "description": "", "link": "https://www.ftc.gov/news"}, True),+ ("uppercase host", {"title": "Rule", "description": "", "link": "https://DEVELOPER.APPLE.COM/news"}, True),+]+failed = 0+for name, ann, official in cases:+ prio, verified = mon.classify_source_and_verify(ann, None)+ if official and (prio, verified) != (1, True):+ print(" %s: expected (1, True), got (%s, %s)" % (name, prio, verified)); failed += 1+ if not official and (prio == 1 or verified):+ print(" %s: expected untrusted, got (%s, %s)" % (name, prio, verified)); failed += 1+sys.exit(1 if failed else 0)+TRUSTPY+then+ ok "Source trust follows the URL host with a domain boundary match"+else+ bad "Source trust can be raised by a spoofed host or by text"+fi+# Assert no emojis are present in outputs or scriptsecho "Checking for emojis in scripts and generated files..."has_emojis() {diff --git a/scripts/monitor-privacy.py b/scripts/monitor-privacy.pyindex 1a22fbf..3b9713e 100755--- a/scripts/monitor-privacy.py+++ b/scripts/monitor-privacy.py@@ -7,6 +7,7 @@ Tracks 16 distinct Apple, Android, and Web privacy requirements.import osimport sysimport re+import urllib.parseimport argparseimport urllib.requestimport xml.etree.ElementTree as ET@@ -297,12 +298,27 @@ MOCK_ANNOUNCEMENTS = []+def source_host(link):+ """Lowercased URL hostname with userinfo and port removed, or empty."""+ try:+ host = urllib.parse.urlsplit((link or "").strip()).hostname or ""+ except ValueError:+ return ""+ return host.rstrip(".").lower()+++def host_matches(host, domains):+ """True only when host equals a domain or is a subdomain of it."""+ return bool(host) and any(host == d or host.endswith("." + d) for d in domains)++def classify_source_and_verify(announcement, all_announcements=None):"""Classifies an announcement by TRUST_HIERARCHY priority (1-5) andverification status. Returns (priority_level, is_verified)."""link = announcement.get("link", "").lower()+ host = source_host(announcement.get("link", ""))title = announcement.get("title", "").lower()desc = announcement.get("description", "").lower()combined = f"{title} {desc} {link}"@@ -314,17 +330,10 @@ def classify_source_and_verify(announcement, all_announcements=None):"imda.gov.sg", "pdpc.gov.sg", "anpd.gov.br", "esafety.gov.au","apple.com", "developer.apple.com", "android.com", "developer.android.com", "support.google.com"]- p1_keywords = [- "european commission", "eur-lex", "official journal", "enisa", "edpb",- "ftc", "nist", "cisa", "ico", "government publication", "imda", "pdpc",- "anpd", "esafety commissioner", "federal register", "apple developer", "android developer"- ]p2_domains = ["reuters.com", "apnews.com", "bloomberg.com"]- p2_keywords = ["reuters", "associated press", "bloomberg"]p3_domains = ["arxiv.org", "ssrn.com"]- p3_keywords = ["academic paper", "academic study", "university research", "peer-reviewed"]p4_domains = ["techcrunch.com", "wired.com", "medium.com", "blog", "randomblogsite.com"]p4_keywords = ["industry blog", "tech blog", "blog post", "editorial"]@@ -334,39 +343,32 @@ def classify_source_and_verify(announcement, all_announcements=None):priority = 4 # Default to 4 if nothing matches- if any(d in link for d in p5_domains) or any(kw in combined for kw in p5_keywords):+ # Source classification uses only the URL host, matched on a domain+ # boundary. Text can lower trust (P4/P5 words) but never raise it.+ p4_hosts = [d for d in p4_domains if "." in d]+ if host_matches(host, p5_domains) or any(kw in combined for kw in p5_keywords):priority = 5- elif any(d in link for d in p4_domains) or any(kw in combined for kw in p4_keywords):+ elif (+ host_matches(host, p4_hosts)+ or "blog" in host+ or any(kw in combined for kw in p4_keywords)+ ):priority = 4- elif any(d in link for d in p3_domains) or any(kw in combined for kw in p3_keywords) or ".edu" in link:+ elif host_matches(host, p3_domains) or host_matches(host, ["edu"]):priority = 3- elif any(d in link for d in p2_domains) or any(kw in combined for kw in p2_keywords):+ elif host_matches(host, p2_domains):priority = 2- if any(d in link for d in p1_domains) or any(kw in combined for kw in p1_keywords) or ".gov" in link:+ if host_matches(host, p1_domains) or host_matches(host, ["gov"]):priority = 1+ # Verification is separate. P4 and P5 need a P1-hosted announcement on+ # the same topic. Agency names or domains in the text never count.is_verified = Falseif priority <= 3:is_verified = Trueelse:- # Priority 4 or 5: Must be verified by a Priority 1 official source- has_p1_ref_in_text = False- for d in p1_domains:- if d in combined:- has_p1_ref_in_text = True- break- if not has_p1_ref_in_text:- for kw in p1_keywords:- if kw in combined:- has_p1_ref_in_text = True- break- if ".gov" in combined:- has_p1_ref_in_text = True-- if has_p1_ref_in_text:- is_verified = True- elif all_announcements:+ if all_announcements:words = set(re.findall(r"[a-z]+", combined))for other in all_announcements:if other == announcement:diff --git a/scripts/monitor-regulatory-test.sh b/scripts/monitor-regulatory-test.shindex 533b8bf..679119f 100755--- a/scripts/monitor-regulatory-test.sh+++ b/scripts/monitor-regulatory-test.sh@@ -111,6 +111,33 @@ if echo "$EU_JSON" | grep -q '"proposed_pull_request": null'; thenfiecho "[PASS] Allowed verified Priority 1 sources successfully"+# Test 8: Source trust is decided by the URL host, never by text+echo "[TEST] Verifying host based source trust (spoofed hosts and agency words)..."+python3 - "$MON_SCRIPT" <<'TRUSTPY'+import importlib.util, sys+spec = importlib.util.spec_from_file_location("mon", sys.argv[1])+mon = importlib.util.module_from_spec(spec)+spec.loader.exec_module(mon)+cases = [+ ("spoofed host suffix", {"title": "Rule", "description": "", "link": "https://ftc.gov.attacker.invalid/article"}, False),+ ("agency word in title", {"title": "FTC announces a new rule", "description": "", "link": "https://news.example.invalid/story"}, False),+ ("official domain in text only", {"title": "Rule", "description": "see ftc.gov and eur-lex.europa.eu", "link": "https://news.example.invalid/story"}, False),+ ("userinfo trick", {"title": "Rule", "description": "", "link": "https://[email protected]/"}, False),+ ("legitimate subdomain", {"title": "Rule", "description": "", "link": "https://www.ftc.gov/news"}, True),+ ("uppercase host", {"title": "Rule", "description": "", "link": "https://WWW.FTC.GOV/news"}, True),+ ("gov top level domain", {"title": "Rule", "description": "", "link": "https://www.federalregister.gov/documents/x"}, True),+]+failed = 0+for name, ann, official in cases:+ prio, verified = mon.classify_source_and_verify(ann, None)+ if official and (prio, verified) != (1, True):+ print("[ERROR] %s: expected (1, True), got (%s, %s)" % (name, prio, verified)); failed += 1+ if not official and (prio == 1 or verified):+ print("[ERROR] %s: expected untrusted, got (%s, %s)" % (name, prio, verified)); failed += 1+sys.exit(1 if failed else 0)+TRUSTPY+echo "[PASS] Source trust follows the URL host with a domain boundary match"+echo ""echo "[SUCCESS] All tests passed successfully."exit 0diff --git a/scripts/monitor-regulatory.py b/scripts/monitor-regulatory.pyindex 54d6489..1cefe1e 100755--- a/scripts/monitor-regulatory.py+++ b/scripts/monitor-regulatory.py@@ -5,6 +5,7 @@import osimport sysimport re+import urllib.parseimport jsonimport argparsefrom datetime import datetime@@ -553,10 +554,25 @@ def scan_target_repo(repo_path, track_name, metadata):return affected_files, verdict+def source_host(link):+ """Lowercased URL hostname with userinfo and port removed, or empty."""+ try:+ host = urllib.parse.urlsplit((link or "").strip()).hostname or ""+ except ValueError:+ return ""+ return host.rstrip(".").lower()+++def host_matches(host, domains):+ """True only when host equals a domain or is a subdomain of it."""+ return bool(host) and any(host == d or host.endswith("." + d) for d in domains)++def classify_source_and_verify(announcement, all_announcements=None):"""Classifies announcement by TRUST_HIERARCHY priority (1-5) andverification status. Returns (priority_level, is_verified)."""link = announcement.get("link", "").lower()+ host = source_host(announcement.get("link", ""))title = announcement.get("title", "").lower()desc = announcement.get("description", "").lower()combined = f"{title} {desc} {link}"@@ -578,36 +594,12 @@ def classify_source_and_verify(announcement, all_announcements=None):"anpd.gov.br","esafety.gov.au",]- p1_keywords = [- "european commission",- "eur-lex",- "official journal",- "enisa",- "edpb",- "ftc",- "nist",- "cisa",- "ico",- "government publication",- "imda",- "pdpc",- "anpd",- "esafety commissioner",- "federal register",- ]# Priority 2 patternsp2_domains = ["reuters.com", "apnews.com", "bloomberg.com"]- p2_keywords = ["reuters", "associated press", "bloomberg"]# Priority 3 patternsp3_domains = ["arxiv.org", "ssrn.com"]- p3_keywords = [- "academic paper",- "academic study",- "university research",- "peer-reviewed",- ]# Priority 4 patternsp4_domains = ["techcrunch.com", "wired.com", "medium.com", "blog"]@@ -628,54 +620,32 @@ def classify_source_and_verify(announcement, all_announcements=None):# Determine base prioritypriority = 4 # Default to 4 if nothing matches- # Check Priority 5 first- if any(d in link for d in p5_domains) or any(kw in combined for kw in p5_keywords):+ # Source classification uses only the URL host, matched on a domain+ # boundary. Text can lower trust (P4/P5 words) but never raise it.+ p4_hosts = [d for d in p4_domains if "." in d]+ if host_matches(host, p5_domains) or any(kw in combined for kw in p5_keywords):priority = 5- elif any(d in link for d in p4_domains) or any(- kw in combined for kw in p4_keywords- ):- priority = 4elif (- any(d in link for d in p3_domains)- or any(kw in combined for kw in p3_keywords)- or ".edu" in link+ host_matches(host, p4_hosts)+ or "blog" in host+ or any(kw in combined for kw in p4_keywords)):+ priority = 4+ elif host_matches(host, p3_domains) or host_matches(host, ["edu"]):priority = 3- elif any(d in link for d in p2_domains) or any(- kw in combined for kw in p2_keywords- ):+ elif host_matches(host, p2_domains):priority = 2- # Priority 1 has absolute priority- if (- any(d in link for d in p1_domains)- or any(kw in combined for kw in p1_keywords)- or ".gov" in link- ):+ if host_matches(host, p1_domains) or host_matches(host, ["gov"]):priority = 1- # Verification Logic+ # Verification is separate. P4 and P5 need a P1-hosted announcement on+ # the same topic. Agency names or domains in the text never count.is_verified = Falseif priority <= 3:is_verified = Trueelse:- # Priority 4 or 5. Must be verified by a Priority 1 official source.- has_p1_ref_in_text = False- for d in p1_domains:- if d in combined:- has_p1_ref_in_text = True- break- if not has_p1_ref_in_text:- for kw in p1_keywords:- if kw in combined:- has_p1_ref_in_text = True- break- if ".gov" in combined:- has_p1_ref_in_text = True-- if has_p1_ref_in_text:- is_verified = True- elif all_announcements:+ if all_announcements:words = set(re.findall(r"[a-z]+", combined))for other in all_announcements:if other == announcement:diff --git a/scripts/monitor-test.sh b/scripts/monitor-test.shindex bb4efa5..90290c2 100644--- a/scripts/monitor-test.sh+++ b/scripts/monitor-test.sh@@ -235,6 +235,21 @@ assert "Accessibility requirements" in by.get("WCAG2.2 alignment", set()), by' && ok "keywords match whole words on stripped text (issue 833)" || bad "keywords match whole words on stripped text (issue 833)"rm -rf "$T"+# Issue #1000. Inline markup joins, so L<em>LM</em> reads LLM. Block markup still separates.+python3 - "$HERE" <<'PY' && ok "inline markup joins a split keyword, block markup still separates (issue 1000)" || bad "inline markup joins a split keyword, block markup still separates (issue 1000)"+import importlib.util, os, sys+spec = importlib.util.spec_from_file_location("mon", os.path.join(sys.argv[1], "monitor.py"))+mon = importlib.util.module_from_spec(spec)+spec.loader.exec_module(mon)+assert mon.strip_html("<p>Apps that call an L<em>LM</em> must disclose it.</p>") == "Apps that call an LLM must disclose it.", mon.strip_html("<p>L<em>LM</em></p>")+assert mon.strip_html("<p>Hello</p><p>World</p>") == "Hello World"+assert mon.strip_html("Hello<br>World") == "Hello World"+item = {"title": "Platform news", "description": "<p>Apps that call an L<em>LM</em> must disclose it.</p>"}+assert mon.match_announcement_to_tracks(item), "an inline element split the llm keyword"+item = {"title": "Platform news", "description": "<p>New Store<b>Kit</b> APIs.</p>"}+assert "In-App Purchase policies" in mon.match_announcement_to_tracks(item), "an inline element split storekit"+PY+echo ""echo "monitor-test: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/monitor.py b/scripts/monitor.pyindex 70b8f62..190a7a5 100644--- a/scripts/monitor.py+++ b/scripts/monitor.py@@ -683,13 +683,22 @@ HTML_MARKUP = re.compile(_CDATA_MARKUP = re.compile(_COMMENT + "|" + _BOGUS + "|" + _TAG, re.S | re.I | re.A)+_TAG_NAME = re.compile(r"</?([A-Za-z][A-Za-z0-9-]*)", re.A)+_INLINE_TAGS = {+ "a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "del", "dfn", "em", "font", "i",+ "ins", "kbd", "label", "mark", "q", "s", "samp", "small", "span", "strong", "sub", "sup",+ "time", "tt", "u", "var",+} # same set as monitor-ai-policy.py, so an unknown block can never join two words++def _visible_markup(m):- """CDATA and textarea or title content is visible text. Everything else is markup."""+ """CDATA and textarea or title content is visible text. Inline tags join, other markup separates."""if m.group(1) is not None:return " " + _CDATA_MARKUP.sub(" ", m.group(1)) + " "if m.group(3) is not None:return " " + m.group(3) + " "- return " "+ t = _TAG_NAME.match(m.group(0))+ return "" if t and t.group(1).lower() in _INLINE_TAGS else " "def strip_html(text):diff --git a/scripts/release-audit-test.sh b/scripts/release-audit-test.shindex f045183..50bf222 100755--- a/scripts/release-audit-test.sh+++ b/scripts/release-audit-test.sh@@ -17,7 +17,7 @@ printf '<plist><dict><key>NSCameraUsageDescription</key><string>camera</string><printf 'let s = "lorem ipsum"\n' > "$FX/App/A.swift"BEFORE="$(git status --porcelain)"-OUT="$(python3 scripts/release-audit.py "$FX" 2>&1)"+OUT="$(python3 scripts/release-audit.py "$FX" 2>&1)"; RUN_RC=$?AFTER="$(git status --porcelain)"REPORT="$FX/RELEASE-READINESS-REPORT.md"@@ -58,5 +58,60 @@ fn = getattr(ra, "is_deadline_line", None)sys.exit(0 if fn and not fn(keep) and not fn(keep2) and all(fn(d) for d in drop) else 1)PYT+# The harmless app above has a high placeholder finding and no listing, so it is never cleared.+[ "$RUN_RC" -ne 0 ] && ! echo "$OUT" | grep -q "CLEAR TO SUBMIT" && ok "an app with a high finding is not cleared to submit" || bad "an app with a high finding is not cleared to submit (rc=$RUN_RC)"++# The installed layout. scripts sit in skills/app-store-compliance and the guard sits in hooks, with no agent-os folder.+W="$(mktemp -d)"+SK="$W/c/skills/app-store-compliance"+mkdir -p "$SK" "$W/c/hooks"+cp -R data docs references templates scripts VERSION "$SK/"+cp agent-os/hooks/app-store-compliance-guard.sh "$W/c/hooks/"+CL="$W/clean"; mkdir -p "$CL/en-US"+printf 'Lumina Studio' > "$CL/en-US/name.txt"+printf 'A focused editor with layers and presets.' > "$CL/en-US/description.txt"+printf '{"privacy_policy_url":"https://lumina.app/privacy","support_url":"https://lumina.app/support"}' > "$CL/m.json"+NOMETA="$W/nometa"; mkdir -p "$NOMETA"; printf 'let a = 1\n' > "$NOMETA/A.swift"+STUB_PASS="$W/pass.sh"; printf '#!/usr/bin/env bash\necho "app-store-compliance-guard. 0 critical risks"\nexit 0\n' > "$STUB_PASS"+STUB_NC="$W/nc.sh"; printf '#!/usr/bin/env bash\necho "NOT CHECKED. No iOS or Android project was found."\nexit 1\n' > "$STUB_NC"+STUB_HIGH="$W/high.sh"; printf '#!/usr/bin/env bash\necho " [HIGH] BOTH-PLACEHOLDER Placeholder text found"\necho " fix. Replace placeholder text"\nexit 0\n' > "$STUB_HIGH"+STUB_ERR="$W/err.sh"; printf '#!/usr/bin/env bash\necho "guard crashed" >&2\nexit 2\n' > "$STUB_ERR"++OUT="$(python3 "$SK/scripts/release-audit.py" "$CL" 2>&1)"+echo "$OUT" | grep -qF "Guard. $W/c/hooks/app-store-compliance-guard.sh" && echo "$OUT" | grep -q "Scanning your app" && ! echo "$OUT" | grep -q "guard tests failed" && ok "the installed layout finds the installed guard and never needs its test file" || bad "the installed layout finds the installed guard and never needs its test file"++OUT="$(APP_STORE_GUARD_PATH="$STUB_PASS" python3 "$SK/scripts/release-audit.py" "$CL" 2>&1)"; RC=$?+[ "$RC" -eq 0 ] && echo "$OUT" | grep -q "Overall Status: PASSED" && ok "a clean app with complete scans passes the gate" || bad "a clean app with complete scans passes the gate (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_HIGH" python3 "$SK/scripts/release-audit.py" "$CL" 2>&1)"; RC=$?+[ "$RC" -eq 2 ] && echo "$OUT" | grep -q "Overall Status: BLOCKED" && ! echo "$OUT" | grep -q "CLEAR TO SUBMIT" && ok "a single high finding blocks the release" || bad "a single high finding blocks the release (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_NC" python3 "$SK/scripts/release-audit.py" "$CL" 2>&1)"; RC=$?+[ "$RC" -ne 0 ] && ! echo "$OUT" | grep -q "Overall Status: PASSED" && ! echo "$OUT" | grep -q "CLEAR TO SUBMIT" && echo "$OUT" | grep -q "NOT CHECKED" && ok "a guard that did not check the app fails the gate" || bad "a guard that did not check the app fails the gate (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_ERR" python3 "$SK/scripts/release-audit.py" "$CL" 2>&1)"; RC=$?+[ "$RC" -ne 0 ] && ! echo "$OUT" | grep -q "Overall Status: PASSED" && echo "$OUT" | grep -q "guard crashed" && ok "a guard error fails the gate and keeps its diagnostics" || bad "a guard error fails the gate and keeps its diagnostics (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_PASS" python3 "$SK/scripts/release-audit.py" "$NOMETA" 2>&1)"; RC=$?+[ "$RC" -ne 0 ] && ! echo "$OUT" | grep -q "Overall Status: PASSED" && echo "$OUT" | grep -q "Nothing was audited" && ok "a listing that was not audited fails the gate" || bad "a listing that was not audited fails the gate (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$W/no-such-guard.sh" python3 scripts/release-audit.py "$CL" 2>&1)"; RC=$?+[ "$RC" -ne 0 ] && echo "$OUT" | grep -q "guard not found" && ! echo "$OUT" | grep -q "Starting Release Readiness" && ok "a missing guard is reported before any scan" || bad "a missing guard is reported before any scan (rc=$RC)"+# --metadata points the listing audit at a pulled metadata folder instead of the app folder.+MD="$W/pulled"; mkdir -p "$MD/en-US"+printf 'Lumina Studio' > "$MD/en-US/name.txt"+printf 'A focused editor with layers and presets.' > "$MD/en-US/description.txt"+printf '{"privacy_policy_url":"https://lumina.app/privacy","support_url":"https://lumina.app/support"}' > "$MD/m.json"+OUT="$(APP_STORE_GUARD_PATH="$STUB_PASS" python3 "$SK/scripts/release-audit.py" "$NOMETA" --metadata "$MD" 2>&1)"; RC=$?+[ "$RC" -eq 0 ] && echo "$OUT" | grep -q "Overall Status: PASSED" && echo "$OUT" | grep -q "CLEAR TO SUBMIT" && ok "a clean pulled listing passed with --metadata reaches CLEAR" || bad "a clean pulled listing passed with --metadata reaches CLEAR (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_PASS" python3 "$SK/scripts/release-audit.py" "$NOMETA" 2>&1)"; RC=$?+[ "$RC" -eq 3 ] && echo "$OUT" | grep -q "Overall Status: INCOMPLETE" && echo "$OUT" | grep -q "Store listing not audited. Pull it with scripts/pull-metadata.sh, then pass --metadata <dir>." && ok "no listing and no --metadata is INCOMPLETE with the command to run" || bad "no listing and no --metadata is INCOMPLETE with the command to run (rc=$RC)"++OUT="$(APP_STORE_GUARD_PATH="$STUB_PASS" python3 "$SK/scripts/release-audit.py" "$NOMETA" --metadata "$W/no-such-dir" 2>&1)"; RC=$?+[ "$RC" -eq 1 ] && echo "$OUT" | grep -q "not a directory" && ! echo "$OUT" | grep -q "Starting Release Readiness" && ok "a missing --metadata folder is rejected before any scan" || bad "a missing --metadata folder is rejected before any scan (rc=$RC)"++rm -rf "$W"+echo "release-audit-test: $PASS passed, $FAIL failed"[ "$FAIL" -eq 0 ]diff --git a/scripts/release-audit.py b/scripts/release-audit.pyindex ede299a..d0802af 100755--- a/scripts/release-audit.py+++ b/scripts/release-audit.py@@ -1,6 +1,6 @@#!/usr/bin/env python3-"""Runs metadata/guard scans against a target project and compiles a-release-readiness report. Exits non-zero on any critical finding."""+"""Release readiness audit. Usage. release-audit.py <app-dir> [--metadata <pulled-listing-dir>]+Exit 0 clear, 2 blocked on a critical or high finding, 3 incomplete scan, 1 bad input."""import osimport sys@@ -9,6 +9,9 @@ import jsonimport reROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+GUARD_NAME = "app-store-compliance-guard.sh"+BLOCKING = ("critical", "high")+LISTING_HINT = "Store listing not audited. Pull it with scripts/pull-metadata.sh, then pass --metadata <dir>."# 13 Required areasREQUIRED_AREAS = [@@ -103,9 +106,66 @@ MAP_PATTERNS_TO_AREAS = {"APPLE-2.1-DEBUG-FEATURES": ["Apple requirements", "Security"],"APPLE-2.1-CLOUD-NOT-IN-PRODUCTION": ["Apple requirements"],"APPLE-2.1-REVIEW-NOTES-INCOMPLETE": ["Apple requirements", "Store metadata"],+ "BOTH-INVALID-METADATA-URL": ["Store metadata"],+ "APPLE-MISSING-SUPPORT-URL": ["Apple requirements", "Store metadata"],+ "GOOGLE-MISSING-CONTACT-EMAIL": ["Google Play requirements", "Store metadata"],}+def resolve_guard():+ """Find the guard. APP_STORE_GUARD_PATH wins, then the repo layout, then an installed skill.+ Returns (path, None) or (None, reason)."""+ env = os.environ.get("APP_STORE_GUARD_PATH", "").strip()+ if env:+ if os.path.isfile(env):+ return os.path.abspath(env), None+ return None, f"APP_STORE_GUARD_PATH points at {env}, which is not a file"+ candidates = [+ os.path.join(ROOT, "agent-os", "hooks", GUARD_NAME),+ # installed. <config>/skills/app-store-compliance/scripts -> <config>/hooks+ os.path.normpath(os.path.join(ROOT, "..", "..", "hooks", GUARD_NAME)),+ ]+ # shared skill in ~/.agents. the installer records each tool's guard path in .guards+ try:+ with open(os.path.join(ROOT, ".guards"), encoding="utf-8") as f:+ candidates += [ln.rstrip("\n").partition("\t")[2] for ln in f if "\t" in ln]+ except OSError:+ pass+ for c in candidates:+ if c and os.path.isfile(c):+ return c, None+ return None, "looked in " + " and ".join(candidates)+++def scan_problems(name, code, out, err, ok_codes=(0, 2)):+ """Reasons a scanner run cannot be trusted as a complete check. Empty means it ran fine."""+ problems = []+ text = (out or "") + "\n" + (err or "")+ if code not in ok_codes:+ problems.append(f"{name} exited {code}")+ for marker in ("NOT CHECKED", "Nothing was audited"):+ if marker in text:+ line = next((ln.strip() for ln in text.splitlines() if marker in ln), marker)+ problems.append(f"{name} did not check everything. {line}")+ return problems+++def tail(text, n=8):+ lines = [ln for ln in (text or "").splitlines() if ln.strip()]+ return lines[-n:]+++def decide_status(findings, problems):+ """Overall status and exit code. A failed or partial scan never passes, a high finding blocks."""+ if problems:+ return "INCOMPLETE", 3+ if any(f["severity"] in BLOCKING for f in findings):+ return "BLOCKED", 2+ if findings:+ return "ADVISORY", 0+ return "PASSED", 0++def run_command(args, cwd=ROOT):try:res = subprocess.run(args, cwd=cwd, capture_output=True, text=True)@@ -302,15 +362,33 @@ def find_affected_files(target_dir, patterns_dict):def main():+ args = sys.argv[1:]+ meta_dir = None+ if "--metadata" in args:+ i = args.index("--metadata")+ meta_dir = args[i + 1] if i + 1 < len(args) else ""+ del args[i:i + 2]+ if not os.path.isdir(meta_dir):+ print(f"release-audit. --metadata '{meta_dir}' is not a directory.", file=sys.stderr)+ return 1+ meta_dir = os.path.abspath(meta_dir)target_dir = ROOT- if len(sys.argv) > 1:- if not os.path.isdir(sys.argv[1]):- print(f"release-audit. '{sys.argv[1]}' is not a directory.", file=sys.stderr)+ if args:+ if not os.path.isdir(args[0]):+ print(f"release-audit. '{args[0]}' is not a directory.", file=sys.stderr)return 1- target_dir = os.path.abspath(sys.argv[1])+ target_dir = os.path.abspath(args[0])++ guard_path, guard_missing = resolve_guard()+ if not guard_path:+ print(f"release-audit. compliance guard not found, {guard_missing}.", file=sys.stderr)+ print("Set APP_STORE_GUARD_PATH to the guard script, or reinstall with scripts/install.sh.", file=sys.stderr)+ return 1print("== Starting Release Readiness Compliance Audit ==")print(f"Target Directory: {target_dir}")+ print(f"Guard. {guard_path}")+ print(f"Store listing. {meta_dir or target_dir + ' (pass --metadata to audit a pulled listing)'}")print("")# --- Step 1. Run Internal Validation and Test Engines ---@@ -323,14 +401,16 @@ def main():print(val_err)return 1- guard_test_code, guard_test_out, guard_test_err = run_command(- ["bash", "agent-os/hooks/app-store-compliance-guard-test.sh"]- )- if guard_test_code != 0:- print(" ERROR: compliance guard tests failed")- print(guard_test_out)- print(guard_test_err)- return 1+ guard_test = os.path.join(ROOT, "agent-os", "hooks", "app-store-compliance-guard-test.sh")+ if os.path.isfile(guard_test):+ guard_test_code, guard_test_out, guard_test_err = run_command(["bash", guard_test])+ if guard_test_code != 0:+ print(" ERROR: compliance guard tests failed")+ print(guard_test_out)+ print(guard_test_err)+ return 1+ else:+ print(" The guard's own tests ship only with the repository, skipped in this installed copy.")meta_test_code, meta_test_out, meta_test_err = run_command(["bash", "scripts/metadata-audit-test.sh"]@@ -348,22 +428,46 @@ def main():print("Step 2 of 2. Scanning your app...", flush=True)# Run the compliance guard- guard_code, guard_out, guard_err = run_command(- ["bash", "agent-os/hooks/app-store-compliance-guard.sh", target_dir]- )+ guard_code, guard_out, guard_err = run_command(["bash", guard_path, target_dir])# Run metadata-audit.py- # If en-US metadata exists, use it, otherwise let it run with default empty metadata scan+ # The pulled listing from --metadata when given, otherwise the app folder itselfmeta_code, meta_out, meta_err = run_command(- ["python3", "scripts/metadata-audit.py", target_dir]+ ["python3", "scripts/metadata-audit.py", meta_dir or target_dir])- # Parse findingspatterns_dict = load_patterns()- findings = []+ findings = parse_findings(guard_out + "\n" + meta_out)++ problems = scan_problems("compliance guard", guard_code, guard_out, guard_err)+ listing_missing = meta_dir is None and "Nothing was audited" in meta_out + meta_err+ if listing_missing:+ problems.append(LISTING_HINT)+ else:+ problems += scan_problems("metadata audit", meta_code, meta_out, meta_err)+ if guard_code == 2 and not any(f["severity"] == "critical" for f in parse_findings(guard_out)):+ problems.append("compliance guard exited 2 but reported no critical finding")+ if problems:+ print("")+ print("Scan problems. The release cannot be approved until every scan completes.")+ for p in problems:+ print(f" - {p}")+ for name, out, err in (("compliance guard", guard_out, guard_err), ("metadata audit", meta_out, meta_err)):+ if name in " ".join(problems):+ for ln in tail(err) or tail(out):+ print(f" {name}. {ln}")+ if listing_missing:+ seen = next((ln.strip() for ln in (meta_out + meta_err).splitlines() if "Nothing was audited" in ln), "")+ print(f" metadata audit. {seen}")+ print("")++ # Programmatically scan for affected files+ affected_files_map = find_affected_files(target_dir, patterns_dict)+ return compile_report(target_dir, findings, problems, patterns_dict, affected_files_map)- # Simple parse function for stdout of guard and metadata scripts- all_scanner_stdout = guard_out + "\n" + meta_out++def parse_findings(all_scanner_stdout):+ findings = []lines = all_scanner_stdout.splitlines()i = 0while i < len(lines):@@ -402,20 +506,17 @@ def main():{"id": pid, "severity": sev, "title": title, "fix": fix})i += 1+ return findings- # Programmatically scan for affected files- affected_files_map = find_affected_files(target_dir, patterns_dict)+def compile_report(target_dir, findings, problems, patterns_dict, affected_files_map):# --- Step 3. Compile Report and Map to 13 Areas ---area_findings = {area: [] for area in REQUIRED_AREAS}- has_critical = False+ overall_status, exit_code = decide_status(findings, problems)+ has_blocking = any(f["severity"] in BLOCKING for f in findings)for f in findings:pid = f["id"]- sev = f["severity"]- if sev == "critical":- has_critical = True-areas = get_areas_for_pattern(pid, patterns_dict)for area in areas:if area in area_findings:@@ -428,16 +529,21 @@ def main():report_lines.append("")report_lines.append(f"Target Directory: {target_dir}")- overall_status = (- "BLOCKED" if has_critical else ("ADVISORY" if findings else "PASSED")- )report_lines.append(f"Overall Compliance Status: {overall_status}")report_lines.append("")report_lines.append("## Executive Summary")- if has_critical:+ if problems:+ report_lines.append(+ "The audit is INCOMPLETE. One or more scans failed or did not check the app, so the release cannot be approved. Fix the scan problems below and run the audit again."+ )+ report_lines.append("")+ report_lines.append("## Scan Problems")+ for p in problems:+ report_lines.append(f"- {p}")+ elif has_blocking:report_lines.append(- "The release is currently BLOCKED due to one or more critical compliance issues that must be resolved before submitting to the platforms."+ "The release is currently BLOCKED due to one or more critical or high compliance issues that must be resolved before submitting to the platforms.")elif findings:report_lines.append(@@ -458,7 +564,7 @@ def main():area_status = "PASSED"area_f = area_findings[area]if area_f:- if any(af["severity"] == "critical" for af in area_f):+ if any(af["severity"] in BLOCKING for af in area_f):area_status = "BLOCKED"else:area_status = "ADVISORY"@@ -475,7 +581,7 @@ def main():area_f = area_findings[area]area_status = "PASSED"if area_f:- if any(af["severity"] == "critical" for af in area_f):+ if any(af["severity"] in BLOCKING for af in area_f):area_status = "BLOCKED"else:area_status = "ADVISORY"@@ -527,12 +633,13 @@ def main():)print(f"Overall Status: {overall_status}")- if has_critical:- print("Release is BLOCKED. Resolve critical issues.")- return 2+ if overall_status == "INCOMPLETE":+ print("Release is NOT APPROVED. A scan failed or did not check the app, see Scan problems above.")+ elif overall_status == "BLOCKED":+ print("Release is BLOCKED. Resolve the critical and high issues.")else:print("Release is CLEAR TO SUBMIT.")- return 0+ return exit_codeif __name__ == "__main__":diff --git a/scripts/test-validate.py b/scripts/test-validate.pyindex e066d7b..c8ae861 100644--- a/scripts/test-validate.py+++ b/scripts/test-validate.py@@ -133,5 +133,31 @@ class TestDateOrder(unittest.TestCase):self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+class TestVersionsAgree(unittest.TestCase):+ """VERSION, the data files and CITATION.cff must name one release."""++ def run_with(self, text):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "VERSION")+ with open(path, "w") as f:+ f.write(text)+ env = {k: v for k, v in os.environ.items() if k != "DEADLINES_FILE"}+ env["VERSION_FILE"] = path+ cmd = [sys.executable, os.path.join(ROOT, "scripts", "validate.py")]+ r = subprocess.run(cmd, capture_output=True, text=True, env=env)+ return r.returncode, r.stdout + r.stderr++ def test_mismatch_fails(self):+ rc, out = self.run_with("9.9.9\n")+ self.assertEqual(rc, 1, out)+ self.assertIn("9.9.9", out)+ self.assertIn("CITATION.cff", out)++ def test_real_version_matches(self):+ with open(os.path.join(ROOT, "VERSION")) as f:+ rc, out = self.run_with(f.read())+ self.assertEqual(rc, 0, out)++if __name__ == "__main__":unittest.main()diff --git a/scripts/validate.py b/scripts/validate.pyindex 9280035..86d0a09 100644--- a/scripts/validate.py+++ b/scripts/validate.py@@ -197,6 +197,7 @@ def main():except Exception as e:errors.append(f"Failed to parse regulatory-deadlines.json: {e}")+ check_versions()return finish(len(patterns),len(recipes) if "recipes" in locals() else 0,@@ -204,6 +205,33 @@ def main():)+def check_versions():+ """VERSION, both data files and CITATION.cff must name the same release."""+ vfile = os.environ.get("VERSION_FILE", os.path.join(ROOT, "VERSION"))+ try:+ with open(vfile, encoding="utf-8") as f:+ want = f.read().strip()+ except OSError:+ errors.append(f"VERSION file not found at {vfile}")+ return+ for name in ("rejection-patterns.json", "regulatory-deadlines.json"):+ try:+ with open(os.path.join(ROOT, "data", name), encoding="utf-8") as f:+ got = json.load(f).get("version")+ except Exception:+ continue+ if got != want:+ errors.append(f"data/{name} says version {got}, VERSION says {want}")+ try:+ with open(os.path.join(ROOT, "CITATION.cff"), encoding="utf-8") as f:+ cff = f.read()+ except OSError:+ return+ m = re.search(r"^version:\s*['\"]?([^'\"\s]+)", cff, re.M)+ if not m or m.group(1) != want:+ errors.append(f"CITATION.cff says version {m.group(1) if m else 'nothing'}, VERSION says {want}")++def finish(npat=0, nrec=0, ndead=0):for w in warnings:print(f" warn. {w}")