Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Run the heavy CI jobs on the tip of a stack only
v0lumehi31d6fc86a358
diff --git a/.github/scripts/build_wanted.py b/.github/scripts/build_wanted.pynew file mode 100644index 00000000..5a037315--- /dev/null+++ b/.github/scripts/build_wanted.py@@ -0,0 +1,100 @@+"""Does this run need the app build? A step of the `stack` job of build-mac-app.yml.++The app build (build-mac-app.yml, `build`) is the second macOS job of a pull request, and it adds a lot of minutes. `swift test` already+checks the launcher's code. The build adds the packaging: bundle assembly, bundled tools, the signing steps, the icon. So a pull request+builds the app only when++ - it carries the label `full-build` (read live, so "Re-run all jobs" after adding the label works), or+ - the changes against the default branch touch a file that goes into the packaging (PACKAGING below).++The changes are taken against the default branch, not against the PR's base: in a stack the tip then counts every PR below it, and a+packaging change in a lower PR (whose own run skipped the heavy jobs) is built at the tip. Everything but a pull request (push to main, a+tag, workflow_dispatch) always builds. A failed lookup builds too (fail open).++Inputs are environment variables: EVENT_NAME, PR_NUMBER, HEAD_SHA, GH_REPO, DEFAULT_BRANCH, GH_TOKEN. Writes `build=true|false` to+GITHUB_OUTPUT and the reason to GITHUB_STEP_SUMMARY.+"""+import os+import sys++from stack_tip import gh++LABEL = 'full-build'+PAGE = 100+MAX_PAGES = 3 # the compare API lists at most 300 files; a change that big builds++# What build-mac-app.yml consumes besides Swift sources: a path ending in / is a folder.+PACKAGING = (+ '.github/workflows/build-mac-app.yml',+ '.upstream-ref',+ 'patches/series',+ 'tools/engine.py',+ 'tools/release_manifest.py',+ 'tools/release_notes.py',+ 'tools/requirements-release.txt',+ 'frontend/Package.swift',+ 'frontend/Package.resolved',+ 'frontend/engine-signing.pub',+ 'frontend/Resources/',+ 'frontend/AppIcon.icon/',+ 'frontend/bundled-python/',+ 'frontend/fonts/',+ 'frontend/tools/',+ 'frontend-ios/Package.swift',+)+++def is_packaging(path):+ return any(path == p or (p.endswith('/') and path.startswith(p)) for p in PACKAGING)+++def changed_files(repo, default_branch, head_sha):+ files = []+ for page in range(1, MAX_PAGES + 1):+ out = gh('api', f'repos/{repo}/compare/{default_branch}...{head_sha}?per_page={PAGE}&page={page}', '--jq', '.files[].filename')+ got = [line for line in out.splitlines() if line]+ files += got+ if len(got) < PAGE:+ return files, False+ return files, True+++def decide(env):+ """(build, reason)."""+ if env.get('EVENT_NAME') != 'pull_request':+ return True, 'not a pull request: it always builds'+ repo, number = env.get('GH_REPO', ''), env.get('PR_NUMBER', '')+ sha, default_branch = env.get('HEAD_SHA', ''), env.get('DEFAULT_BRANCH') or 'main'+ if not (repo and number and sha):+ return True, 'missing inputs: it builds'+ try:+ labels = gh('api', f'repos/{repo}/issues/{number}/labels', '--paginate', '--jq', '.[].name').split()+ if LABEL in labels:+ return True, f'label {LABEL}'+ files, truncated = changed_files(repo, default_branch, sha)+ except Exception as e: # fail open+ print(f'::warning::Lookup failed, so the app builds: {e}')+ return True, 'lookup failed: it builds'+ if truncated:+ return True, 'more than 300 files changed: it builds'+ hit = [f for f in files if is_packaging(f)]+ if hit:+ return True, 'packaging files changed: ' + ', '.join(hit[:5]) + (' and more' if len(hit) > 5 else '')+ return False, f'no packaging file changed (label {LABEL} or workflow_dispatch builds anyway)'+++def main():+ build, reason = decide(os.environ)+ line = f'build={"true" if build else "false"}'+ print(line, '-', reason)+ if path := os.environ.get('GITHUB_OUTPUT'):+ with open(path, 'a') as f:+ f.write(line + '\n')+ if path := os.environ.get('GITHUB_STEP_SUMMARY'):+ with open(path, 'a') as f:+ f.write(f'App build: {"yes" if build else "no"}, {reason}\n')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/.github/scripts/stack_rerun.py b/.github/scripts/stack_rerun.pynew file mode 100644index 00000000..38e68096--- /dev/null+++ b/.github/scripts/stack_rerun.py@@ -0,0 +1,90 @@+"""A pull request that was not the tip of its stack becomes the tip when its child is closed, merged or retargeted. Nothing re-triggers its+checks: the heavy jobs stay skipped. This script, run by stack-parent-rerun.yml when a child changes, finds the parent and re-runs the `stack`+job of its latest runs (tests and the app build) for its head commit. `gh run rerun --job` re-runs that job and every job that needs it, so+the heavy jobs start, and the `stack` job asks GitHub again, live, whether the parent is the tip now.++ parent the open PR (same repository) whose head branch is the child's old base: for `closed` the base the child had, for `edited` the base+ it had before (`changes.base.ref.from`). Nothing to do when there is none (the parent was merged, or the child had no parent).+ only if the parent has no other open child now (it is the tip), and a run of the workflow is finished and has a `Stack` job+ nothing runs in progress are left alone, and nothing is re-run twice++The event data arrives as environment variables and is only ever an argument of `gh`, never part of a shell command. No code of the pull+request is checked out or run. Inputs: ACTION, BASE_REF, OLD_BASE_REF, PR_NUMBER, GH_REPO, GH_TOKEN. DRY_RUN=1 only prints.+"""+import json+import os+import sys++from stack_tip import gh, open_children++WORKFLOWS = ('tests', 'Build the NX2Apple app (macOS)')+++def parent_branch(env):+ """The head branch of the child's former parent, or ''."""+ if env.get('ACTION') == 'closed':+ return env.get('BASE_REF', '')+ if env.get('ACTION') == 'edited':+ return env.get('OLD_BASE_REF', '') # empty unless the base changed+ return ''+++def find_parent(repo, branch):+ out = json.loads(gh('pr', 'list', '--repo', repo, '--state', 'open', '--head', branch, '--limit', '10',+ '--json', 'number,headRefName,headRefOid,isCrossRepository'))+ for pr in out:+ if pr.get('headRefName') == branch and not pr.get('isCrossRepository'):+ return pr+ return None+++def latest_runs(repo, sha):+ """The newest pull_request run of each workflow in WORKFLOWS for this commit."""+ runs = json.loads(gh('run', 'list', '--repo', repo, '--commit', sha, '--event', 'pull_request', '--limit', '50',+ '--json', 'databaseId,workflowName,status'))+ latest = {}+ for r in runs:+ if r.get('workflowName') in WORKFLOWS and r['databaseId'] > latest.get(r['workflowName'], {'databaseId': 0})['databaseId']:+ latest[r['workflowName']] = r+ return list(latest.values())+++def stack_job(repo, run_id):+ view = json.loads(gh('run', 'view', str(run_id), '--repo', repo, '--json', 'status,jobs'))+ if view.get('status') != 'completed':+ return None+ for job in view.get('jobs', []):+ if job.get('name', '').startswith('Stack'):+ return job.get('databaseId')+ return None+++def main(env=os.environ):+ repo = env.get('GH_REPO', '')+ branch = parent_branch(env)+ if not repo or not branch:+ print('Not a close or a base change of a child: nothing to do.')+ return 0+ try:+ parent = find_parent(repo, branch)+ if not parent:+ print(f'No open pull request has the head branch {branch}: nothing to do.')+ return 0+ if open_children(repo, branch):+ print(f'#{parent["number"]} still has an open child: it is not the tip.')+ return 0+ for run in latest_runs(repo, parent['headRefOid']):+ job_id = stack_job(repo, run['databaseId'])+ if not job_id:+ print(f'{run["workflowName"]} (run {run["databaseId"]}) is not finished or has no Stack job: left alone.')+ continue+ print(f'#{parent["number"]} is the tip now: re-running the Stack job of {run["workflowName"]} (run {run["databaseId"]}).')+ if env.get('DRY_RUN') != '1':+ gh('run', 'rerun', str(run['databaseId']), '--repo', repo, '--job', str(job_id))+ except Exception as e: # the worst case is a skipped check that stays skipped: re-run it by hand+ print(f'::warning::Could not re-run the parent: {e}')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/.github/scripts/stack_tip.py b/.github/scripts/stack_tip.pynew file mode 100644index 00000000..2a861c39--- /dev/null+++ b/.github/scripts/stack_tip.py@@ -0,0 +1,102 @@+"""Is this pull request the tip of a stack? The first job of tests.yml and build-mac-app.yml runs this, and the heavy macOS jobs wait for it.++The maintainers work in stacks: one PR per step, each PR based on the head branch of the one below. The heavy checks (swift test, the app+build, the engine jobs) run on the tip only. A PR is the tip when no open PR has its head branch as base. That is true for GitHub stacks+and for plain stacked branches alike. The PRs below the tip still report every required check: their heavy jobs are skipped by a job-level+`if` (a skipped job counts as passed, a workflow that never starts would block the merge).++ not a pull request push to main, a tag, workflow_dispatch, workflow_call: always the tip+ pull request a tip when it has no open child. A draft child counts, a closed or merged one does not+ fork a PR from a fork has no children: the tip+ gh fails fail open, the tip, so CI runs rather than being skipped by a broken lookup++Inputs are environment variables (no event data goes through the shell): EVENT_NAME, PR_NUMBER, HEAD_REF, HEAD_REPO, BASE_REPO,+GH_REPO (the repository to ask), GH_TOKEN. Writes `is_tip=true|false` to GITHUB_OUTPUT and a line to GITHUB_STEP_SUMMARY and the log.+"""+import json+import os+import subprocess+import sys++MAX_DEPTH = 40 # longest stack followed to name its tip; a loop of branches cannot run away+++def gh(*args):+ r = subprocess.run(['gh', *args], capture_output=True, text=True, timeout=60)+ if r.returncode:+ raise RuntimeError(f'gh {args[0]} failed: {r.stderr.strip()[:300]}')+ return r.stdout+++def open_children(repo, head_ref):+ """The open PRs whose base is head_ref: [{'number', 'headRefName', 'isCrossRepository'}]. Drafts are open, so they count."""+ out = gh('pr', 'list', '--repo', repo, '--state', 'open', '--base', head_ref, '--limit', '100',+ '--json', 'number,headRefName,isCrossRepository')+ data = json.loads(out)+ if not isinstance(data, list):+ raise RuntimeError('unexpected answer from gh pr list')+ return data+++def tips_below(repo, children, seen):+ """The numbers of the tips above `children`, following same-repository children up the stack."""+ tips = []+ queue = [(c, 1) for c in children]+ while queue:+ pr, depth = queue.pop(0)+ number = pr['number']+ if number in seen:+ continue+ seen.add(number)+ nxt = []+ if depth < MAX_DEPTH and not pr.get('isCrossRepository'):+ nxt = open_children(repo, pr['headRefName'])+ if nxt:+ queue.extend((c, depth + 1) for c in nxt)+ else:+ tips.append(number)+ return sorted(tips)+++def decide(env):+ """(is_tip, message). message is empty for a tip."""+ if env.get('EVENT_NAME') not in ('pull_request', 'pull_request_target'):+ return True, ''+ head_ref = env.get('HEAD_REF', '')+ repo = env.get('GH_REPO') or env.get('BASE_REPO', '')+ if not head_ref or not repo:+ return True, ''+ if env.get('HEAD_REPO') and env.get('BASE_REPO') and env['HEAD_REPO'].lower() != env['BASE_REPO'].lower():+ return True, '' # a fork's branch is not a base anybody can target+ try:+ children = open_children(repo, head_ref)+ if not children:+ return True, ''+ try:+ tips = tips_below(repo, children, {int(env.get('PR_NUMBER') or 0)})+ except Exception:+ tips = sorted(c['number'] for c in children) # the walk failed: name the direct children+ except Exception as e: # fail open: a broken lookup must never skip the checks+ print(f'::warning::Stack lookup failed, so this PR counts as the tip: {e}')+ return True, ''+ names = ', '.join(f'#{n}' for n in tips)+ return False, f'Not the tip of a stack: heavy checks run on {names}'+++def main():+ is_tip, message = decide(os.environ)+ line = f'is_tip={"true" if is_tip else "false"}'+ print(line)+ if path := os.environ.get('GITHUB_OUTPUT'):+ with open(path, 'a') as f:+ f.write(line + '\n')+ if message:+ print(f'::notice title=Stack::{message}')+ if path := os.environ.get('GITHUB_STEP_SUMMARY'):+ with open(path, 'a') as f:+ f.write((message or 'This is the tip of its stack (or not a pull request): the heavy checks run here.') + '\n')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/.github/scripts/tests/test_build_wanted.py b/.github/scripts/tests/test_build_wanted.pynew file mode 100644index 00000000..a8d98630--- /dev/null+++ b/.github/scripts/tests/test_build_wanted.py@@ -0,0 +1,93 @@+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import build_wanted as bw # noqa: E402++ENV = {'EVENT_NAME': 'pull_request', 'PR_NUMBER': '7', 'HEAD_SHA': 'abc', 'GH_REPO': 'LNPANDY/NX2Apple', 'DEFAULT_BRANCH': 'main'}+++def fake_gh(labels=(), files=(), fail=False, calls=None):+ """A fake `gh api`: the labels endpoint and the compare endpoint (paged by ?page=N, 100 per page)."""+ def run(*args):+ if calls is not None:+ calls.append(args)+ if fail:+ raise RuntimeError('gh api failed')+ url = args[1]+ if '/labels' in url:+ return '\n'.join(labels)+ page = int(url.rsplit('page=', 1)[1])+ return '\n'.join(files[(page - 1) * 100:page * 100])+ return run+++def decide(env=None, **kw):+ with mock.patch.object(bw, 'gh', fake_gh(**kw)):+ return bw.decide({**ENV, **(env or {})})+++class Decide(unittest.TestCase):+ def test_not_a_pull_request_always_builds(self):+ for ev in ('push', 'workflow_dispatch', ''):+ self.assertTrue(decide({'EVENT_NAME': ev}, files=['README.md'])[0], ev)++ def test_docs_only_does_not_build(self):+ self.assertFalse(decide(files=['README.md', 'frontend/Sources/NXCore/A.swift', 'frontend/Tests/T.swift', '.github/scripts/x.py'])[0])++ def test_packaging_files_build(self):+ for f in ('.github/workflows/build-mac-app.yml', 'frontend/Package.swift', 'frontend/Package.resolved', 'frontend/Resources/a.png',+ 'frontend/tools/bundle_tools.sh', 'frontend/AppIcon.icon/icon.json', '.upstream-ref', 'patches/series',+ 'tools/engine.py', 'frontend-ios/Package.swift'):+ self.assertTrue(decide(files=['README.md', f])[0], f)++ def test_a_patch_file_alone_does_not_build_but_the_series_does(self):+ self.assertFalse(decide(files=['patches/0001-x.patch'])[0])++ def test_similar_names_do_not_match(self):+ self.assertFalse(decide(files=['frontend/Package.swift.bak', 'frontend/Resourcesx/a', 'tools/engine.pyc'])[0])++ def test_label_builds(self):+ self.assertEqual(decide(labels=['ci', 'full-build'], files=['README.md'])[0], True)+ self.assertFalse(decide(labels=['ci'], files=['README.md'])[0])++ def test_compare_against_the_default_branch(self):+ calls = []+ decide(files=['README.md'], calls=calls)+ self.assertIn('compare/main...abc', calls[-1][1])++ def test_more_than_one_page(self):+ files = ['docs/%d.md' % i for i in range(150)] + ['frontend/Package.swift']+ self.assertTrue(decide(files=files)[0])++ def test_too_many_files_build(self):+ build, reason = decide(files=['docs/%d.md' % i for i in range(300)])+ self.assertTrue(build)+ self.assertIn('300', reason)++ def test_failure_fails_open(self):+ build, reason = decide(fail=True)+ self.assertTrue(build)+ self.assertIn('fail', reason)++ def test_missing_inputs_build(self):+ self.assertTrue(decide({'HEAD_SHA': ''}, files=[])[0])+++class Main(unittest.TestCase):+ def test_output(self):+ with tempfile.TemporaryDirectory() as d:+ out, summary = Path(d, 'out'), Path(d, 'summary')+ env = {**ENV, 'GITHUB_OUTPUT': str(out), 'GITHUB_STEP_SUMMARY': str(summary)}+ with mock.patch.object(bw, 'gh', fake_gh(files=['README.md'])), mock.patch.dict(os.environ, env, clear=True):+ self.assertEqual(bw.main(), 0)+ self.assertEqual(out.read_text(), 'build=false\n')+ self.assertIn('App build: no', summary.read_text())+++if __name__ == '__main__':+ unittest.main()diff --git a/.github/scripts/tests/test_stack_rerun.py b/.github/scripts/tests/test_stack_rerun.pynew file mode 100644index 00000000..4cc0ec66--- /dev/null+++ b/.github/scripts/tests/test_stack_rerun.py@@ -0,0 +1,107 @@+import io+import json+import sys+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import stack_rerun as sr # noqa: E402+import stack_tip # noqa: E402++PARENT = {'number': 482, 'headRefName': 'v0lumehi/b', 'headRefOid': 'sha1', 'isCrossRepository': False}+RUNS = [{'databaseId': 10, 'workflowName': 'tests', 'status': 'completed'},+ {'databaseId': 9, 'workflowName': 'tests', 'status': 'completed'},+ {'databaseId': 11, 'workflowName': 'Build the NX2Apple app (macOS)', 'status': 'completed'},+ {'databaseId': 12, 'workflowName': 'PR labeler', 'status': 'completed'}]+VIEW = {'status': 'completed', 'jobs': [{'name': 'Changed areas', 'databaseId': 1}, {'name': 'Stack (is this the tip?)', 'databaseId': 77}]}+++class Fake:+ def __init__(self, parents=(PARENT,), children=(), runs=RUNS, view=VIEW):+ self.calls, self.parents, self.children, self.runs, self.view = [], list(parents), list(children), runs, view++ def __call__(self, *args):+ self.calls.append(args)+ if args[:2] == ('pr', 'list'):+ if '--head' in args:+ return json.dumps(self.parents)+ return json.dumps(self.children)+ if args[:2] == ('run', 'list'):+ return json.dumps(self.runs)+ if args[:2] == ('run', 'view'):+ return json.dumps(self.view)+ return ''++ def reruns(self):+ return [c for c in self.calls if c[:2] == ('run', 'rerun')]+++def run(env, **kw):+ fake = Fake(**kw)+ out = io.StringIO()+ with mock.patch.object(sr, 'gh', fake), mock.patch.object(stack_tip, 'gh', fake), redirect_stdout(out):+ code = sr.main({'GH_REPO': 'LNPANDY/NX2Apple', **env})+ return code, fake, out.getvalue()+++class Rerun(unittest.TestCase):+ def test_closed_child_reruns_the_stack_job_of_each_workflow(self):+ code, fake, _ = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b'})+ self.assertEqual(code, 0)+ self.assertEqual(fake.reruns(), [('run', 'rerun', '10', '--repo', 'LNPANDY/NX2Apple', '--job', '77'),+ ('run', 'rerun', '11', '--repo', 'LNPANDY/NX2Apple', '--job', '77')])+ self.assertIn('headRefOid', ' '.join(next(c for c in fake.calls if '--head' in c)))++ def test_retargeted_child_uses_the_old_base(self):+ _, fake, _ = run({'ACTION': 'edited', 'BASE_REF': 'main', 'OLD_BASE_REF': 'v0lumehi/b'})+ self.assertEqual(len(fake.reruns()), 2)+ self.assertEqual(fake.calls[0][fake.calls[0].index('--head') + 1], 'v0lumehi/b')++ def test_edit_without_base_change_does_nothing(self):+ _, fake, _ = run({'ACTION': 'edited', 'BASE_REF': 'v0lumehi/b', 'OLD_BASE_REF': ''})+ self.assertEqual(fake.calls, [])++ def test_other_actions_do_nothing(self):+ _, fake, _ = run({'ACTION': 'opened', 'BASE_REF': 'v0lumehi/b'})+ self.assertEqual(fake.calls, [])++ def test_no_open_parent(self):+ _, fake, out = run({'ACTION': 'closed', 'BASE_REF': 'main'}, parents=[])+ self.assertEqual(fake.reruns(), [])+ self.assertIn('nothing to do', out)++ def test_fork_parent_is_ignored(self):+ _, fake, _ = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b'}, parents=[{**PARENT, 'isCrossRepository': True}])+ self.assertEqual(fake.reruns(), [])++ def test_parent_with_another_open_child_is_not_the_tip(self):+ _, fake, out = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b'}, children=[{'number': 500, 'headRefName': 'x', 'isCrossRepository': False}])+ self.assertEqual(fake.reruns(), [])+ self.assertIn('not the tip', out)++ def test_run_in_progress_is_left_alone(self):+ _, fake, _ = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b'}, view={**VIEW, 'status': 'in_progress'})+ self.assertEqual(fake.reruns(), [])++ def test_run_without_stack_job_is_left_alone(self):+ _, fake, _ = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b'}, view={'status': 'completed', 'jobs': [{'name': 'x', 'databaseId': 1}]})+ self.assertEqual(fake.reruns(), [])++ def test_dry_run_does_not_rerun(self):+ _, fake, out = run({'ACTION': 'closed', 'BASE_REF': 'v0lumehi/b', 'DRY_RUN': '1'})+ self.assertEqual(fake.reruns(), [])+ self.assertIn('re-running', out)++ def test_gh_failure_is_a_warning_not_a_failure(self):+ def boom(*a):+ raise RuntimeError('boom')+ out = io.StringIO()+ with mock.patch.object(sr, 'gh', boom), redirect_stdout(out):+ self.assertEqual(sr.main({'GH_REPO': 'r', 'ACTION': 'closed', 'BASE_REF': 'b'}), 0)+ self.assertIn('::warning::', out.getvalue())+++if __name__ == '__main__':+ unittest.main()diff --git a/.github/scripts/tests/test_stack_tip.py b/.github/scripts/tests/test_stack_tip.pynew file mode 100644index 00000000..91c0674c--- /dev/null+++ b/.github/scripts/tests/test_stack_tip.py@@ -0,0 +1,125 @@+import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import stack_tip as st # noqa: E402++PR = {'EVENT_NAME': 'pull_request', 'PR_NUMBER': '482', 'HEAD_REF': 'v0lumehi/b', 'HEAD_REPO': 'LNPANDY/NX2Apple',+ 'BASE_REPO': 'LNPANDY/NX2Apple', 'GH_REPO': 'LNPANDY/NX2Apple'}+++def child(number, head, cross=False):+ return {'number': number, 'headRefName': head, 'isCrossRepository': cross}+++def fake_gh(table, calls=None):+ """A fake `gh pr list --base X --state open`: answers table[X] (a list, a raw string, or an Exception for a failed gh)."""+ def run(*args):+ if calls is not None:+ calls.append(args)+ v = table.get(args[args.index('--base') + 1], [])+ if isinstance(v, Exception):+ raise v+ return v if isinstance(v, str) else json.dumps(v)+ return run+++def decide(env, table, calls=None):+ with mock.patch.object(st, 'gh', fake_gh(table, calls)):+ return st.decide({**PR, **env})+++class Decide(unittest.TestCase):+ def test_no_children_is_tip(self):+ self.assertEqual(decide({}, {}), (True, ''))++ def test_one_child_is_not_tip(self):+ tip, msg = decide({}, {'v0lumehi/b': [child(485, 'v0lumehi/c')]})+ self.assertFalse(tip)+ self.assertEqual(msg, 'Not the tip of a stack: heavy checks run on #485')++ def test_names_the_tip_through_the_stack(self):+ table = {'v0lumehi/b': [child(485, 'v0lumehi/c')], 'v0lumehi/c': [child(490, 'v0lumehi/d')]}+ self.assertEqual(decide({}, table)[1], 'Not the tip of a stack: heavy checks run on #490')++ def test_two_children_not_tip_both_children_are_tips(self):+ table = {'v0lumehi/b': [child(485, 'x'), child(486, 'y')]}+ tip, msg = decide({}, table)+ self.assertFalse(tip)+ self.assertEqual(msg, 'Not the tip of a stack: heavy checks run on #485, #486')+ self.assertEqual(decide({'PR_NUMBER': '485', 'HEAD_REF': 'x'}, table), (True, ''))+ self.assertEqual(decide({'PR_NUMBER': '486', 'HEAD_REF': 'y'}, table), (True, ''))++ def test_draft_child_still_counts(self):+ # gh lists drafts for --state open and the script does not filter on isDraft+ table = {'v0lumehi/b': [{'number': 485, 'headRefName': 'c', 'isDraft': True, 'isCrossRepository': False}]}+ self.assertFalse(decide({}, table)[0])++ def test_closed_or_merged_child_does_not_count(self):+ calls = []+ # a closed child is not in the answer of `--state open`+ self.assertEqual(decide({}, {}, calls), (True, ''))+ args = calls[0]+ self.assertEqual(args[args.index('--state') + 1], 'open')++ def test_fork_is_tip_without_asking(self):+ calls = []+ self.assertEqual(decide({'HEAD_REPO': 'someone/NX2Apple'}, {'v0lumehi/b': [child(485, 'c')]}, calls), (True, ''))+ self.assertEqual(calls, [])++ def test_api_failure_fails_open(self):+ for bad in (RuntimeError('gh pr list failed: boom'), 'not json', '{"a": 1}'):+ self.assertEqual(decide({}, {'v0lumehi/b': bad}), (True, ''), bad)++ def test_walk_failure_still_not_tip(self):+ table = {'v0lumehi/b': [child(485, 'c')], 'c': RuntimeError('boom')}+ tip, msg = decide({}, table)+ self.assertFalse(tip)+ self.assertIn('#485', msg)++ def test_cross_repository_child_is_not_followed(self):+ calls = []+ table = {'v0lumehi/b': [child(485, 'c', cross=True)], 'c': [child(999, 'z')]}+ self.assertEqual(decide({}, table, calls)[1], 'Not the tip of a stack: heavy checks run on #485')+ self.assertEqual(len(calls), 1)++ def test_loop_of_branches_ends(self):+ table = {'v0lumehi/b': [child(485, 'c')], 'c': [child(482, 'v0lumehi/b')]}+ self.assertFalse(decide({}, table)[0])++ def test_other_events_are_always_tip(self):+ for ev in ('push', 'workflow_dispatch', 'workflow_call', 'schedule', ''):+ calls = []+ self.assertEqual(decide({'EVENT_NAME': ev}, {'v0lumehi/b': [child(485, 'c')]}, calls), (True, ''), ev)+ self.assertEqual(calls, [])++ def test_missing_inputs_is_tip(self):+ self.assertEqual(decide({'HEAD_REF': ''}, {}), (True, ''))+++class Main(unittest.TestCase):+ def run_main(self, table):+ with tempfile.TemporaryDirectory() as d:+ out, summary = Path(d, 'out'), Path(d, 'summary')+ env = {**PR, 'GITHUB_OUTPUT': str(out), 'GITHUB_STEP_SUMMARY': str(summary)}+ with mock.patch.object(st, 'gh', fake_gh(table)), mock.patch.dict(os.environ, env, clear=True):+ self.assertEqual(st.main(), 0)+ return out.read_text(), summary.read_text()++ def test_not_tip_output_and_summary(self):+ out, summary = self.run_main({'v0lumehi/b': [child(485, 'c')]})+ self.assertEqual(out, 'is_tip=false\n')+ self.assertIn('Not the tip of a stack: heavy checks run on #485', summary)++ def test_tip_output(self):+ out, _ = self.run_main({})+ self.assertEqual(out, 'is_tip=true\n')+++if __name__ == '__main__':+ unittest.main()diff --git a/.github/workflows/build-mac-app.yml b/.github/workflows/build-mac-app.ymlindex 9e062394..4299a437 100644--- a/.github/workflows/build-mac-app.yml+++ b/.github/workflows/build-mac-app.yml@@ -23,8 +23,9 @@# that names the engine the release X.Y.Z will carry (RELEASING.md)# - push a tag vX.Y.Z → the release: it ships the files of the newest release candidate on the same commit, its engine checked against this build.# A commit without a release candidate fails, unless a manual run on the tag sets release_without_rc-# - a push to main, or a pull request, that touches the paths below → artifact only (NX2Apple-macOS-arm64), which tools/try-pr opens.-# Nothing is published+# - a push to main that touches the paths below → artifact only (NX2Apple-macOS-arm64), which tools/try-pr opens. Nothing is published+# - a pull request → the same artifact, but only on the tip of its stack and only when it changes a packaging file (.github/scripts/build_wanted.py+# lists them) or has the label full-build. Every other PR reports the job as skipped (CONTRIBUTING.md, "CI on stacks")# - workflow_dispatch → artifact only, or on a tag ref the same as a push of that tagname: Build the NX2Apple app (macOS)@@ -34,8 +35,11 @@ on:tags: ['v*']# GitHub does not evaluate path filters for tag pushes: every v* tag builds. On main only a change to these paths builds.paths: ['frontend/**', 'tools/engine.py', 'tools/release_manifest.py', 'tools/requirements-release.txt', 'patches/**', '.upstream-ref', '.github/workflows/build-mac-app.yml']+ # No paths filter here: a workflow that does not start reports nothing. The `stack` job decides per job whether a pull request builds the app+ # (it is the tip of its stack, and it changes a packaging file or has the label full-build), see .github/scripts/build_wanted.py.+ # Explicit types: not `edited` or `labeled` (GitHub sends `edited` when it retargets a stack, and the second run only cancels the first).pull_request:- paths: ['frontend/**', 'tools/engine.py', 'tools/release_manifest.py', 'tools/requirements-release.txt', 'patches/**', '.upstream-ref', '.github/workflows/build-mac-app.yml']+ types: [opened, synchronize, reopened, ready_for_review]workflow_dispatch:inputs:release_without_rc:@@ -46,13 +50,51 @@ on:permissions:contents: write-# A newer push to a pull request replaces its running build. Every commit on main and every tag keeps its own run: each main commit has its-# app artifact, and a release is never cancelled halfway.+# A newer run for a pull request replaces its running build and reports instead. Every commit on main and every tag keeps its own run: each main+# commit has its app artifact, and a release is never cancelled halfway.concurrency:- group: build-mac-app-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}cancel-in-progress: ${{ github.event_name == 'pull_request' }}jobs:+ # The app build is the second macOS job of a pull request, so it runs on the tip of a stack only (stack_tip.py), and only when the PR+ # changes what goes into the packaging or has the label full-build (build_wanted.py). `swift test` (tests.yml) runs on every tip.+ # Push to main, a tag and workflow_dispatch always build. A skipped job still reports, and a failed lookup builds (fail open).+ stack:+ name: Stack (tip, packaging)+ runs-on: ubuntu-latest+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: read+ outputs:+ is_tip: ${{ steps.tip.outputs.is_tip }}+ build: ${{ steps.wanted.outputs.build }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts+ - id: tip+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ EVENT_NAME: ${{ github.event_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ HEAD_REF: ${{ github.event.pull_request.head.ref }}+ HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}+ BASE_REPO: ${{ github.event.pull_request.base.repo.full_name }}+ run: python3 .github/scripts/stack_tip.py+ - id: wanted+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ EVENT_NAME: ${{ github.event_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}+ run: python3 .github/scripts/build_wanted.py+# The app icon is AppIcon.icon (Icon Composer). The actool of Xcode 26.6 (the default on macos-latest) throws an exception on it, the one of# Xcode 27.2 compiles it. So actool runs on the xcode-27 runner, as in tests.yml, and the build job takes the two files it writes. Assets.car is# the icon for macOS 26 and later (Liquid Glass), AppIcon.icns the one for macOS 13 to 25.@@ -60,6 +102,8 @@ jobs:# On a pull request the icon is cached by the hash of frontend/AppIcon.icon. The icon-cache job looks the cache up on ubuntu-latest, which# queues in seconds, and the icon job (the scarce xcode-27 runner) runs only on a miss. A tag (rc or final) always compiles the icon.icon-cache:+ needs: stack+ if: ${{ !cancelled() && (needs.stack.result != 'success' || (needs.stack.outputs.is_tip == 'true' && needs.stack.outputs.build == 'true')) }}runs-on: ubuntu-latestoutputs:hit: ${{ steps.lookup.outputs.cache-hit }}@@ -130,9 +174,10 @@ jobs:COPILOT_TOKEN: ${{ secrets.COPILOT_TOKEN }}build:- needs: [icon-cache, icon, notes]- # icon is skipped on a pull request with a cache hit, and that must not skip the build.- if: ${{ !cancelled() && needs.icon-cache.result == 'success' && (needs.icon.result == 'success' || needs.icon.result == 'skipped') }}+ needs: [stack, icon-cache, icon, notes]+ # icon is skipped on a pull request with a cache hit, and that must not skip the build. icon-cache and icon are skipped with the stack+ # decision (not the tip, or no packaging change), so the build is skipped then too, and reports as skipped.+ if: ${{ !cancelled() && (needs.stack.result != 'success' || (needs.stack.outputs.is_tip == 'true' && needs.stack.outputs.build == 'true')) && needs.icon-cache.result == 'success' && (needs.icon.result == 'success' || needs.icon.result == 'skipped') }}# The same runner and compiler as tests.yml: the app that is shipped is compiled by the Xcode that the tests ran with. On macos-latest (Xcode 26.6)# a closure that Xcode 27.2 accepts failed only here, in #467, after the tests had passed.runs-on: xcode-27diff --git a/.github/workflows/pr-scope.yml b/.github/workflows/pr-scope.ymlindex 1ccb71b4..bff387a7 100644--- a/.github/workflows/pr-scope.yml+++ b/.github/workflows/pr-scope.yml@@ -11,6 +11,7 @@ name: PR scope (sync safety)on:pull_request:+ types: [opened, synchronize, reopened, ready_for_review]paths: ['dm/**', 'scripts/**', 'docs/**', 'ref/**', 'patches/**', '.upstream-ref', 'tools/**']permissions:diff --git a/.github/workflows/stack-parent-rerun.yml b/.github/workflows/stack-parent-rerun.ymlnew file mode 100644index 00000000..d0cf6ab9--- /dev/null+++ b/.github/workflows/stack-parent-rerun.yml@@ -0,0 +1,44 @@+# When the child of a stacked PR is closed, merged or retargeted, its parent may be the tip of the stack now. The parent's heavy jobs were skipped+# while it had a child, and nothing re-triggers them. This workflow re-runs the `Stack` job of the parent's latest runs (tests, the app build),+# which decides again, live, and starts the heavy jobs that depend on it. See .github/scripts/stack_rerun.py and CONTRIBUTING.md, "CI on stacks".+#+# pull_request_target, so that the token can write to Actions for a child from a fork too. It is safe here because no code of the pull request is+# checked out or run: the checkout is the base branch (only .github/scripts), and the event data goes into environment variables and from there+# into arguments of `gh`, never into a shell command. This workflow reports no required check, so a run that does not start blocks no merge.+# Residual risk: a parent whose run is still in progress when the child closes keeps its skipped jobs. Re-run it by hand (CONTRIBUTING.md).+name: Stack parent re-run++on:+ pull_request_target:+ types: [closed, edited]++permissions: {}++concurrency:+ group: ${{ github.workflow }}-${{ github.event.pull_request.number }}+ cancel-in-progress: false++jobs:+ rerun:+ name: Re-run the parent of a closed or retargeted PR+ # A title or body edit has no `changes.base`.+ if: ${{ github.event.action == 'closed' || github.event.changes.base != null }}+ runs-on: ubuntu-latest+ timeout-minutes: 5+ permissions:+ actions: write+ contents: read+ pull-requests: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts+ - env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ ACTION: ${{ github.event.action }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ OLD_BASE_REF: ${{ github.event.changes.base.ref.from }}+ run: python3 .github/scripts/stack_rerun.pydiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex d787c918..2b24db44 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -8,7 +8,10 @@name: testson:+ # Explicit types: the default three plus ready_for_review. Not `edited` or `labeled`: GitHub sends `edited` when it retargets a stack, and a+ # second run for the same head only cancels the first (2026-11-02, two runs of this workflow started in the same second).pull_request:+ types: [opened, synchronize, reopened, ready_for_review]push:branches: [main]workflow_dispatch:@@ -16,9 +19,11 @@ on:permissions:contents: read+# A newer run for the same pull request replaces the older one, which is cancelled, and the newer one reports. Every push to main, every tag and+# every manual run keeps its own group (run_id), so none of them is ever cancelled.concurrency:- group: tests-${{ github.event.pull_request.number || github.ref }}- cancel-in-progress: true+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}env:GAME: 010015100B514000 # Super Mario Bros. Wonder: the profile the host and gfx tests are built for (any profile does; the tests are about code, not the game)@@ -32,30 +37,71 @@ defaults:# Actions are pinned to commit SHAs (the tag in the comment): a tag can be moved, a SHA cannot. Dependabot (github-actions) can raise them.jobs:+ # Stacks: the maintainers open one PR per step, each based on the head branch of the one below. The heavy jobs (the ones that take an+ # xcode-27 runner) run on the tip of a stack only, see .github/scripts/stack_tip.py and CONTRIBUTING.md, "CI on stacks". The PRs below+ # the tip report these jobs as skipped by a job-level if, which counts as passed. Never skip a workflow as a whole: its required checks+ # would never report and the merge of the stack would wait for them. A failed lookup counts as the tip.+ stack:+ name: Stack (is this the tip?)+ runs-on: ubuntu-latest+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: read+ outputs:+ is_tip: ${{ steps.tip.outputs.is_tip }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts+ - id: tip+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ EVENT_NAME: ${{ github.event_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ HEAD_REF: ${{ github.event.pull_request.head.ref }}+ HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}+ BASE_REPO: ${{ github.event.pull_request.base.repo.full_name }}+ run: python3 .github/scripts/stack_tip.py+# Which areas the change touches, so a launcher-only or Qt-only PR skips the engine jobs on the scarce xcode-27 runners.# Everything but a pull request (push to main, workflow_dispatch) reports every area as changed. So does any failure to# find the diff. The jobs that wait for this one run when it did not succeed, so a broken filter never skips a check.# The five required checks (patch-queue, launcher, launcher-qt, tool-tests, triage-scripts) either do not wait for it# or are skipped by a job-level if, never by a paths: filter on the workflow (no run would leave the check pending).+ # The diff is taken against the default branch, not the PR's base: the tip of a stack then counts the changes of every PR below it,+ # whose own heavy jobs were skipped.changes:name: Changed areasruns-on: ubuntu-latesttimeout-minutes: 5+ permissions:+ contents: read+ pull-requests: readoutputs:engine: ${{ steps.diff.outputs.engine }}steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false- name: Which areas changedid: diffenv:+ GH_TOKEN: ${{ github.token }}EVENT: ${{ github.event_name }}- BASE: ${{ github.event.pull_request.base.sha }}+ REPO: ${{ github.repository }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}run: |engine=trueif [ "$EVENT" = pull_request ]; then- if git fetch --no-tags --depth=1 origin "$BASE" && files=$(git diff --name-only "$BASE" HEAD); then+ files=''+ complete=false+ for page in 1 2 3; do+ got=$(gh api "repos/$REPO/compare/$DEFAULT_BRANCH...$HEAD_SHA?per_page=100&page=$page" --jq '.files[].filename') || { files=''; break; }+ files="$files$got"$'\n'+ [ "$(echo "$got" | grep -c .)" -lt 100 ] && { complete=true; break; }+ done+ if [ "$complete" = true ]; thenecho "$files"# What the engine jobs read: engine/ is made from .upstream-ref and patches/ by tools/engine.py (dm/, scripts/ and docs/ are# listed in case a change reaches them), the iOS shell package, and this file. A launcher (frontend/) or Qt (frontend-qt/)@@ -66,7 +112,7 @@ jobs:engine=falsefielse- echo "::warning::No diff against the base, so every area counts as changed"+ echo "::warning::No complete diff against $DEFAULT_BRANCH, so every area counts as changed"fifiecho "engine=$engine" >> "$GITHUB_OUTPUT"@@ -75,8 +121,8 @@ jobs:tool-tests:name: Tool testsruns-on: xcode-27- needs: changes- if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}+ needs: [stack, changes]+ if: ${{ !cancelled() && (needs.stack.result != 'success' || needs.stack.outputs.is_tip == 'true') && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}timeout-minutes: 15defaults:run:@@ -183,8 +229,8 @@ jobs:build:name: Build check (Mac host, gfx tests, iOS sources)runs-on: xcode-27- needs: changes- if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}+ needs: [stack, changes]+ if: ${{ !cancelled() && (needs.stack.result != 'success' || needs.stack.outputs.is_tip == 'true') && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}timeout-minutes: 40defaults:run:@@ -237,6 +283,8 @@ jobs:launcher:name: Mac launcher (frontend, swift test)+ needs: stack+ if: ${{ !cancelled() && (needs.stack.result != 'success' || needs.stack.outputs.is_tip == 'true') }}runs-on: xcode-27timeout-minutes: 20steps:@@ -246,7 +294,7 @@ jobs:- name: Engine (tools/engine.py sync, issue #214; the launcher's tests read engine/)run: python3 tools/engine.py sync# swift test builds the package in debug, so a pull request does not build it again. The release build (optimizer, whole-module- # compile, the code outside #if DEBUG) runs on main and on tags. build-mac-app.yml also builds the release for a PR that touches frontend/.+ # compile, the code outside #if DEBUG) runs on main and on tags. build-mac-app.yml builds the release app for a PR that changes the packaging.- name: Release buildif: ${{ github.event_name != 'pull_request' }}working-directory: frontend@@ -309,8 +357,8 @@ jobs:engine-checks:name: Host tests, iOS shell package and unsigned iOS appruns-on: xcode-27- needs: changes- if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}+ needs: [stack, changes]+ if: ${{ !cancelled() && (needs.stack.result != 'success' || needs.stack.outputs.is_tip == 'true') && (needs.changes.result != 'success' || needs.changes.outputs.engine == 'true') }}timeout-minutes: 60defaults:run:diff --git a/AGENTS.md b/AGENTS.mdindex 2cb728fa..f4c7cadb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -13,6 +13,7 @@ This is the fork's guide. The engine has its own, upstream's: [engine/AGENTS.md]- **Merging with admin rights.** An admin merge never goes over a red check. That holds even when @LNPANDY overrides an objection. If a re-review is slow, the other maintainer pings the reviewer and does not merge with admin rights.- **Mac launcher layers.** `frontend/` is four SwiftPM targets (`NXCore`, `NXModel`, `NXLauncher`, `NX2Apple`) and the compiler enforces which may import which. Read [frontend/ARCHITECTURE.md](frontend/ARCHITECTURE.md) before you add a file to `frontend/Sources`. It says where a new feature goes. `BuildModel` is gone: the stores are in `NXModel` and `LauncherStores` only wires them. No Swift file there is above 800 lines (`SourceSizeTests`), and the larger ones may only shrink.- **Checks.** `cd frontend && swift build && swift test` for the Mac launcher (its tests read `engine/`, so sync first), `python3 -m unittest discover -s frontend-qt/tests` for the Qt front end, `python3 -m unittest discover tools/tests` for the tools. The engine's own tests run in `engine/` as `tests.yml` does. The pre-commit hook runs `python3 tools/engine.py check` when `patches/` or `.upstream-ref` is staged. The pre-push hook runs the checks above for the files the push changes, `tools/githooks.py` has the list. Fix the failure, do not bypass the hook.+- **CI on stacks.** The heavy macOS jobs (Mac launcher with `swift test`, Tool tests, the engine jobs) run on the tip of a stack only, and the app build runs only for a packaging change or the label `full-build`. A lower PR of a stack shows them as skipped, which counts as passed. Never skip a whole workflow with a `paths:` filter, a required check must always report. Merge a stack through its top PR with the async API. [CONTRIBUTING.md](CONTRIBUTING.md), section "CI on stacks", has the details.- **No long sleeps.** A command never sleeps longer than 60 seconds. Poll a build, a workflow or a download with sleeps of 60 seconds or less, do other useful work in between, and report interim progress instead of leaving the chat silent.- **Language and text.** Everything is in English except the Chinese pages (`*.zh-CN.md`) and the launcher's strings. No semicolons in UI strings, READMEs and docs. The launcher's strings are not in Swift or Python code. They are one JSON file per language in `frontend/l10n/`, read by the Mac launcher and the Windows launcher. A new string is a line in `en.json` and `zh.json` (English and Chinese have every key, the other languages may miss one and then show English). The language list is in the files too (the `_language` entry: name, locale prefixes, order). `Lang` is not an enum, so a new language is one new file under `frontend/l10n/` for the Mac and Windows launchers (the iOS shell's texts come in a later step of #388). The files go into the apps by the build workflows, see `frontend/README.md`, section "Language".- **Release notes.** They follow `.github/release_notes_template.md`, English first, then Chinese, no emojis.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aedb8630..7029e6ec 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -95,6 +95,17 @@ A feature from the maintainers (v0lumehi and LNPANDY) merges after 48 hours. A fA patch in `patches/` takes the next free number from `patches/series` on `main` at merge time. Whoever merges renumbers the patch and notes it in the PR. You do not need to rebase to chase free numbers.+### CI on stacks++The maintainers work in stacks: one PR per step, each based on the head branch of the one below, with a PR of its own for traceability. GitHub has 5 macOS runners for the whole account, so the heavy checks run once, on the tip of a stack (the PR that no other open PR is based on).++- **What runs where.** Every PR runs the cheap checks (Patch queue, Qt front end, Triage script tests, Changed areas). The jobs that take a macOS runner (Mac launcher with `swift test`, Tool tests, the engine jobs) run on the tip. The app build (`Build the NX2Apple app (macOS)`) runs on the tip only when the PR changes a file that goes into the packaging (`.github/scripts/build_wanted.py` lists them) or has the label `full-build`. A push to `main`, a tag and a manual run always run everything. The changed files are counted against `main`, so the tip counts every PR below it.+- **Why a lower PR shows "skipped".** Its `Stack` job found an open PR on top of it and skipped the heavy jobs. The job summary says `Not the tip of a stack: heavy checks run on #N`. A skipped job counts as passed for the required checks, so the PR can merge. The checks are skipped per job, never per workflow, because a workflow that does not start reports nothing and blocks the merge.+- **When a PR becomes the tip.** If its child is closed, merged or retargeted, `Stack parent re-run` re-runs the `Stack` job of the parent's latest runs, and the heavy jobs start. If a parent still shows skipped (its run was still going when the child closed), open the run and press "Re-run all jobs", or run `gh run rerun <run id> --job <id of the Stack job>`.+- **Force a run.** Add the label `full-build`, then re-run the `Build the NX2Apple app (macOS)` run (the label is read when the job runs, not when the run starts). Or start the workflow by hand: `gh workflow run build-mac-app.yml --ref <branch>`. A run by hand is always the tip.+- **Merge a stack through its top PR.** Use the async API on the tip, it merges the PRs below it too: `gh api -X PUT repos/LNPANDY/NX2Apple/pulls/<n>/merge-async -f merge_method=merge -f merge_action=direct_merge`. The required checks of every PR in the stack must have reported, and a skipped heavy job has.+- **If the lookup fails** (GitHub API down), the PR counts as the tip and CI runs. A broken lookup never skips a check.+## For AI agents and other toolsIssue forms and the PR template apply in the browser only. `gh issue create`, the API and MCP tools skip the forms, so follow them yourself: