[js-api] More reorganizing
diff --git a/.github/workflows/ci-js-api.yml b/.github/workflows/ci-js-api.yml
index 7c924c8..6c13bdf 100644
--- a/.github/workflows/ci-js-api.yml
+++ b/.github/workflows/ci-js-api.yml
@@ -1,4 +1,4 @@
-name: CI for Wasm JS API tests
+name: CI for JS API tests
 
 on:
   push:
@@ -16,7 +16,7 @@
       - test/js-api/**
 
   schedule:
-    - cron: '23 6 * * 1'
+    - cron: '23 6 1 * *'
 
   workflow_dispatch:
     inputs:
@@ -42,29 +42,8 @@
     shell: bash
 
 jobs:
-  refresh-schedule:
-    name: Check browser refresh schedule
-    if: github.event_name == 'schedule'
-    runs-on: ubuntu-24.04
-    timeout-minutes: 2
-    permissions: {}
-    outputs:
-      due: ${{ steps.schedule.outputs.due }}
-    steps:
-      - name: Check four-week cadence
-        id: schedule
-        run: |
-          # Cron wakes the workflow weekly. Count UTC weeks from a fixed Monday.
-          anchor=$(date -u -d '2026-11-23' +%s)
-          now=$(date -u +%s)
-          if (( now >= anchor && (now - anchor) / 604800 % 4 == 0 )); then
-            echo 'due=true' >> "$GITHUB_OUTPUT"
-          fi
-
   js-api:
     name: JS API (${{ matrix.browser }})
-    needs: refresh-schedule
-    if: ${{ !cancelled() && (github.event_name != 'schedule' || needs.refresh-schedule.outputs.due == 'true') }}
     runs-on: ${{ matrix.os }}
     timeout-minutes: 15
     strategy:
@@ -83,6 +62,7 @@
     env:
       BROWSER: ${{ matrix.browser }}
       REFRESH: ${{ github.event_name == 'schedule' || inputs.refresh }}
+      PROPOSE: ${{ (github.event_name == 'schedule' || inputs.refresh) && github.ref_name == github.event.repository.default_branch }}
     steps:
       - name: Checkout repo
         uses: actions/checkout@v4
@@ -99,41 +79,12 @@
         env:
           OVERRIDE: ${{ matrix.version }}
         run: |
-          pin=$(jq -er --arg browser "$BROWSER" '.[$browser]' test/js-api/scripts/browser-versions.json)
+          args=(select-version "$BROWSER" --override "$OVERRIDE")
           if [[ "$REFRESH" == true ]]; then
-            case "$BROWSER" in
-              chrome)
-                latest=$(curl -fsSL --retry 3 --max-time 30 https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE)
-                ;;
-              firefox)
-                latest=$(curl -fsSL --retry 3 --max-time 30 https://product-details.mozilla.org/1.0/firefox_versions.json | jq -er '.LATEST_FIREFOX_VERSION')
-                ;;
-              safari)
-                latest=installed
-                ;;
-            esac
-            if [[ "$latest" == installed && "$BROWSER" == safari ]]; then
-              version=installed
-            elif [[ "$latest" =~ ^[0-9]+(\.[0-9]+)+$ ]]; then
-              # A release feed can lag behind the version already tested.
-              version=$(printf '%s\n%s\n' "$pin" "$latest" | sort -V | tail -n 1)
-            else
-              echo "Could not resolve a stable $BROWSER version" >&2
-              exit 1
-            fi
-          elif [[ -n "$OVERRIDE" ]]; then
-            version=$OVERRIDE
-          elif [[ "$BROWSER" == safari ]]; then
-            # The hosted runner supplies Safari. Normal CI checks only its major version.
-            version=${pin%%.*}
-          else
-            version=$pin
+            args+=(--refresh)
           fi
-          if [[ ! "$version" =~ ^[0-9]+(\.[0-9]+)*$ && ( "$BROWSER" != safari || "$version" != installed ) ]]; then
-            echo "Invalid $BROWSER version" >&2
-            exit 1
-          fi
-          printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT"
+          version=$(python test/js-api/scripts/ci.py "${args[@]}")
+          echo "version=$version" >> "$GITHUB_OUTPUT"
       - name: Enable Safari Remote Automation
         if: matrix.browser == 'safari'
         run: sudo /usr/bin/safaridriver --enable
@@ -142,14 +93,14 @@
           BROWSER_VERSION: ${{ steps.browser.outputs.version }}
           SE_SKIP_DRIVER_IN_PATH: 'true'
         run: |
-          args=(--browser "$BROWSER" --json wasm-js-api.json)
-          if [[ "$BROWSER" != safari || "$BROWSER_VERSION" != installed ]]; then
+          args=(--browser "$BROWSER" --json wasm-js-api.json --summary "$GITHUB_STEP_SUMMARY")
+          if [[ -n "$BROWSER_VERSION" ]]; then
             args+=(--browser-version "$BROWSER_VERSION")
           fi
           status=0
           python test/js-api/scripts/run.py "${args[@]}" || status=$?
-          # Candidate test failures are expected. The PR job validates the report.
-          if [[ "$REFRESH" == true && "$status" == 1 && -s wasm-js-api.json ]]; then
+          # Candidate test failures are expected. The proposal job validates the report.
+          if [[ "$PROPOSE" == true && "$status" == 1 && -s wasm-js-api.json ]]; then
             exit 0
           fi
           exit "$status"
@@ -160,21 +111,6 @@
           name: wasm-js-api-${{ matrix.browser }}
           path: wasm-js-api.json
           if-no-files-found: error
-      - name: Summarize browser results
-        if: ${{ !cancelled() && hashFiles('wasm-js-api.json') != '' }}
-        run: |
-          python - <<'PY' >> "$GITHUB_STEP_SUMMARY"
-          from collections import Counter
-          import json
-          from pathlib import Path
-
-          report = json.loads(Path('wasm-js-api.json').read_text(encoding='utf-8'))
-          counts = Counter(case['outcome'] for case in report['results'])
-          print(f"### Wasm JS API in {report['browser']} {report['version']}\n")
-          print('| Pass | Fail | Expected failure | Unexpected pass | Skip |')
-          print('| ---: | ---: | ---: | ---: | ---: |')
-          print('| ' + ' | '.join(str(counts[outcome]) for outcome in ('PASS', 'FAIL', 'XFAIL', 'XPASS', 'SKIP')) + ' |')
-          PY
 
   propose-browser-update:
     name: Propose browser update
@@ -184,6 +120,7 @@
     timeout-minutes: 5
     concurrency: js-api-browser-update
     permissions:
+      actions: write
       contents: write
       pull-requests: write
     steps:
@@ -196,46 +133,24 @@
         with:
           pattern: wasm-js-api-*
           path: ${{ runner.temp }}/js-api-reports
-      - name: Update pins and expectations
+      - name: Check the default branch is unchanged
         env:
-          REPORTS: ${{ runner.temp }}/js-api-reports
           BASE_BRANCH: ${{ github.event.repository.default_branch }}
         run: |
           if [[ "$(git ls-remote origin "refs/heads/$BASE_BRANCH" | cut -f1)" != "$GITHUB_SHA" ]]; then
             echo "The default branch moved during testing. Run the refresh again." >&2
             exit 1
           fi
-          proposal=$(mktemp -d)
-          pins=test/js-api/scripts/browser-versions.json
-          manifest=test/js-api/scripts/expectations.json
-          cp "$pins" "$proposal/pins.json"
-          cp "$manifest" "$proposal/manifest.json"
-          for browser in chrome firefox safari; do
-            report="$REPORTS/wasm-js-api-$browser/wasm-js-api.json"
-            pin=$(jq -er --arg browser "$browser" '.[$browser]' "$pins")
-            version=$(jq -er --arg browser "$browser" \
-              'select(.browser == $browser) | .version | select(test("^[0-9]+([.][0-9]+)+$"))' "$report")
-            python3 test/js-api/scripts/update-expectations.py --require-complete \
-              --manifest "$proposal/manifest.json" "$report" > "$proposal/manifest.next.json"
-            if [[ "$version" == "$pin" ]]; then
-              continue
-            fi
-            if [[ "$(printf '%s\n%s\n' "$pin" "$version" | sort -V | tail -n 1)" != "$version" ]]; then
-              echo "$browser $version is older than the tested pin $pin" >&2
-              exit 1
-            fi
-            jq --arg browser "$browser" --arg version "$version" '.[$browser] = $version' \
-              "$proposal/pins.json" > "$proposal/pins.next.json"
-            mv "$proposal/pins.next.json" "$proposal/pins.json"
-            mv "$proposal/manifest.next.json" "$proposal/manifest.json"
-            printf -- '- %s %s → %s\n' "$browser" "$pin" "$version" >> "$GITHUB_STEP_SUMMARY"
-          done
-          cp "$proposal/pins.json" "$pins"
-          cp "$proposal/manifest.json" "$manifest"
+      - name: Update pins and expectations
+        id: update
+        run: python3 test/js-api/scripts/ci.py propose "$RUNNER_TEMP/js-api-reports" | tee -a "$GITHUB_STEP_SUMMARY"
+      # A rejected browser fails the job, but the other browsers are still proposed.
       - name: Open or update browser bump PR
+        if: ${{ !cancelled() && steps.update.outcome != 'skipped' }}
         env:
           GH_TOKEN: ${{ github.token }}
           BASE_BRANCH: ${{ github.event.repository.default_branch }}
+          UPDATE_OUTCOME: ${{ steps.update.outcome }}
         run: |
           branch=automation/js-api-browser-versions
           ref="refs/heads/$branch"
@@ -243,7 +158,7 @@
           lease="--force-with-lease=$ref:$previous"
           git add -- test/js-api/scripts/browser-versions.json test/js-api/scripts/expectations.json
           if git diff --cached --quiet; then
-            if [[ -n "$previous" ]]; then
+            if [[ -n "$previous" && "$UPDATE_OUTCOME" == success ]]; then
               gh auth setup-git
               git push "$lease" origin ":$ref"
             fi
@@ -275,6 +190,8 @@
           gh auth setup-git
           # Rebuild the bot branch from the tested default-branch commit.
           git push "$lease" origin "HEAD:$ref"
+          # Pushes made with GITHUB_TOKEN do not trigger pull_request runs, so start CI on the PR head.
+          gh workflow run ci-js-api.yml --repo "$GITHUB_REPOSITORY" --ref "$branch"
           if [[ -n "$pr" ]]; then
             gh api --method PATCH "repos/$GITHUB_REPOSITORY/pulls/$pr" \
               -F body=@"$body_file" --jq .html_url
diff --git a/test/js-api/README.md b/test/js-api/README.md
index d8603dc..0e5a8f0 100644
--- a/test/js-api/README.md
+++ b/test/js-api/README.md
@@ -90,11 +90,17 @@
 the file records the full version last tested on the GitHub-hosted image.
 
 The [CI workflow](../../.github/workflows/ci-js-api.yml) checks for browser
-updates every four weeks. After complete runs, it opens a PR with newer versions
-and their expectations.
+updates monthly. After complete runs, it opens a PR with newer versions
+and their expectations. This requires the repository setting "Allow GitHub
+Actions to create and approve pull requests".
 
 ### Browser expectations
 
 The test runner uses [scripts/expectations.json](scripts/expectations.json) to
-track expected results of tests. Run `scripts/update-expectations.py test-results.json > scripts/expectations.json`
-to update expectations based on a test run.
+track expected results of tests. To update expectations from a test run, save a
+JSON report and apply it to the expectations file:
+
+```sh
+/tmp/wasm-js-api-venv/bin/python test/js-api/scripts/run.py --browser firefox --json firefox.json
+python3 test/js-api/scripts/update-expectations.py --in-place firefox.json
+```
diff --git a/test/js-api/scripts/ci.py b/test/js-api/scripts/ci.py
new file mode 100644
index 0000000..91a0d9b
--- /dev/null
+++ b/test/js-api/scripts/ci.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Browser version selection and update proposals for the JS API CI workflow."""
+
+import argparse
+import json
+import sys
+import time
+from pathlib import Path
+from urllib.request import urlopen
+
+from lib.expectations import apply_report
+from lib.tests import (
+    BROWSERS,
+    EXPECTATIONS,
+    PINS,
+    VERSION,
+    discover_tests,
+    read_json,
+    version_key,
+    write_json,
+)
+
+LATEST_RELEASE_URLS = {
+    "chrome": "https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE",
+    "firefox": "https://product-details.mozilla.org/1.0/firefox_versions.json",
+}
+
+
+def fetch(url, attempts=3):
+    for attempt in range(1, attempts + 1):
+        try:
+            with urlopen(url, timeout=30) as response:
+                return response.read().decode("utf-8")
+        except OSError:
+            if attempt == attempts:
+                raise
+            time.sleep(5 * attempt)
+
+
+def latest_release(browser):
+    body = fetch(LATEST_RELEASE_URLS[browser])
+    if browser == "firefox":
+        return json.loads(body)["LATEST_FIREFOX_VERSION"]
+    return body.strip()
+
+
+def select_version(browser, override, refresh):
+    """Return the version to require, or an empty string to accept any."""
+    pin = read_json(PINS)[browser]
+    if override:
+        version = override
+    elif browser == "safari":
+        # The hosted runner supplies Safari. Normal CI checks only its major version.
+        version = "installed" if refresh else pin.split(".")[0]
+    elif refresh:
+        latest = latest_release(browser)
+        if not VERSION.fullmatch(latest):
+            raise ValueError(f"Could not resolve a stable {browser} version: {latest}")
+        # A release feed can lag behind the version already tested.
+        version = max(pin, latest, key=version_key)
+    else:
+        version = pin
+
+    if browser == "safari" and version == "installed":
+        return ""
+    if not VERSION.fullmatch(version):
+        raise ValueError(f"Invalid {browser} version: {version}")
+    return version
+
+
+def propose(reports):
+    """Update pins and expectations from CI reports. Returns the rejected browsers."""
+    pins = read_json(PINS)
+    expectations = read_json(EXPECTATIONS)
+    _, tests = discover_tests()
+    rejected = []
+    for browser in BROWSERS:
+        pin = pins[browser]
+        try:
+            report = read_json(reports / f"wasm-js-api-{browser}" / "wasm-js-api.json")
+            version = report.get("version")
+            if report.get("browser") != browser or not (
+                isinstance(version, str) and VERSION.fullmatch(version)
+            ):
+                raise ValueError("report has no valid browser version")
+            if version == pin:
+                continue
+            if version_key(version) < version_key(pin):
+                raise ValueError(f"{version} is older than the tested pin {pin}")
+            expectations = apply_report(expectations, report, tests, require_complete=True)
+        except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
+            print(f"::error::{browser}: {error}", file=sys.stderr)
+            rejected.append(browser)
+            continue
+        pins[browser] = version
+        print(f"- {browser} {pin} → {version}")
+    write_json(PINS, pins)
+    write_json(EXPECTATIONS, expectations)
+    return rejected
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    commands = parser.add_subparsers(dest="command", required=True)
+
+    select = commands.add_parser(
+        "select-version", help="Print the browser version a CI run should require"
+    )
+    select.add_argument("browser", choices=BROWSERS)
+    select.add_argument("--override", help="Candidate version to test instead")
+    select.add_argument(
+        "--refresh", action="store_true", help="Test the latest stable release"
+    )
+
+    update = commands.add_parser(
+        "propose", help="Update pins and expectations from downloaded CI reports"
+    )
+    update.add_argument("reports", type=Path, help="Directory of report artifacts")
+
+    args = parser.parse_args()
+    if args.command == "select-version":
+        try:
+            print(select_version(args.browser, args.override, args.refresh))
+        except (OSError, ValueError, KeyError) as error:
+            parser.error(str(error))
+        return 0
+    return 1 if propose(args.reports) else 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/test/js-api/scripts/lib/__init__.py b/test/js-api/scripts/lib/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/test/js-api/scripts/lib/__init__.py
diff --git a/test/js-api/scripts/lib/expectations.py b/test/js-api/scripts/lib/expectations.py
new file mode 100644
index 0000000..23dd6d1
--- /dev/null
+++ b/test/js-api/scripts/lib/expectations.py
@@ -0,0 +1,230 @@
+"""Validate, evaluate and update the rules in expectations.json."""
+
+from .tests import BROWSERS, supported_globals
+
+# Rules without a subtest name apply to the whole browser case.
+WHOLE_CASE = None
+
+
+def validate_expectations(expectations, tests, browser):
+    """Validate all expectations and return one browser's rules by case."""
+    if not isinstance(expectations, dict):
+        raise ValueError("Expected an object keyed by test path")
+
+    rules = {}
+    required = {"browser", "expect", "reason"}
+    allowed = required | {"context", "subtest"}
+    for name, entries in expectations.items():
+        if name not in tests:
+            raise ValueError(f"Unknown test: {name}")
+        if not isinstance(entries, list):
+            raise ValueError(f"{name}: expected a list of rules")
+        supported = supported_globals(tests[name])
+        for index, entry in enumerate(entries, 1):
+            label = f"{name} rule {index}"
+            if (
+                not isinstance(entry, dict)
+                or not required <= entry.keys() <= allowed
+                or not all(
+                    isinstance(value, str) and value.strip() for value in entry.values()
+                )
+            ):
+                raise ValueError(
+                    f"{label}: provide browser, expect, reason and optional context or subtest"
+                )
+            product, expect = entry["browser"], entry["expect"]
+            subtest = entry.get("subtest", WHOLE_CASE)
+            if product not in BROWSERS or expect not in ("fail", "skip"):
+                raise ValueError(f"{label}: invalid browser or expectation")
+            if expect == "skip" and subtest is not WHOLE_CASE:
+                raise ValueError(f"{label}: skip applies to a whole test case")
+            requested_context = entry.get("context")
+            contexts = [
+                context
+                for context in supported
+                if requested_context is None or context == requested_context
+            ]
+            if not contexts:
+                raise ValueError(f"{label}: no supported browser context")
+            for context in contexts:
+                case_rules = rules.setdefault((product, name, context), {})
+                if (
+                    subtest in case_rules
+                    or WHOLE_CASE in case_rules
+                    or (subtest is WHOLE_CASE and case_rules)
+                ):
+                    raise ValueError(
+                        f"{label}: overlapping rules for {product} [{context}]"
+                    )
+                case_rules[subtest] = (expect, entry["reason"])
+
+    return {
+        (name, context): case_rules
+        for (product, name, context), case_rules in rules.items()
+        if product == browser
+    }
+
+
+def evaluate_result(result, rules):
+    """Apply failure expectations after the harness has completed successfully."""
+    subtests = result["subtests"]
+    failures = [test for test in subtests if test["status"] != "PASS"]
+    diagnostics = [
+        f"{test['status']} {test['name']}: {test['message']}" for test in failures
+    ]
+    if result["status"] != "OK":
+        return "FAIL", [f"{result['status']}: {result['message']}", *diagnostics]
+    # Only a subtest with status FAIL can satisfy a failure expectation.
+    if WHOLE_CASE in rules:
+        _, reason = rules[WHOLE_CASE]
+        if not failures:
+            return "XPASS", [f"Expected a failure: {reason}"]
+        if all(test["status"] == "FAIL" for test in failures):
+            return "XFAIL", [reason, *diagnostics]
+        return "FAIL", diagnostics
+
+    by_name = {test["name"]: test for test in subtests}
+    missing = rules.keys() - by_name.keys()
+    unexpected = [
+        test
+        for test in failures
+        if test["name"] not in rules or test["status"] != "FAIL"
+    ]
+    expected_failures_that_passed = [
+        name for name in rules if name in by_name and by_name[name]["status"] == "PASS"
+    ]
+    diagnostics += [f"Expected subtest missing: {name}" for name in sorted(missing)]
+    diagnostics += [
+        f"XPASS {name}: {rules[name][1]}" for name in expected_failures_that_passed
+    ]
+    # Missing expected subtests and unexpected failures take precedence over XPASS.
+    if missing or unexpected:
+        return "FAIL", diagnostics
+    if expected_failures_that_passed:
+        return "XPASS", diagnostics
+    if rules:
+        return "XFAIL", [
+            f"{name}: {reason}" for name, (_, reason) in rules.items()
+        ] + diagnostics
+    return "PASS", []
+
+
+def update_expectations(expectations, rules, report, tests):
+    """Refresh failure rules for the browser cases covered by a result report."""
+    browser, version = report["browser"], report.get("version")
+    updated = rules.copy()
+    seen = set()
+    changed = set()
+    for case in report["results"]:
+        name, context = case["test"], case["context"]
+        key = (name, context)
+        if (
+            name not in tests
+            or context not in supported_globals(tests[name])
+            or key in seen
+        ):
+            raise ValueError(f"Unknown or duplicate browser case: {name} [{context}]")
+        seen.add(key)
+        subtests = case["subtests"]
+        previous = rules.get(key, {})
+        # A skip or an incomplete run gives no reliable evidence about this case.
+        if (
+            case["status"] != "OK"
+            or not subtests
+            or any(test["status"] not in ("PASS", "FAIL") for test in subtests)
+            or previous.get(WHOLE_CASE, (None, None))[0] == "skip"
+        ):
+            continue
+        failures = {
+            test["name"]: test.get("message")
+            for test in subtests
+            if test["status"] == "FAIL"
+        }
+        whole_case = previous.get(WHOLE_CASE)
+        if whole_case and failures:
+            current = previous
+        else:
+            current = {}
+            for subtest, message in failures.items():
+                if subtest in previous:
+                    current[subtest] = previous[subtest]
+                else:
+                    reason = f"Observed in {browser.capitalize()}"
+                    if version:
+                        reason += f" {version}"
+                    if message:
+                        reason += f": {' '.join(message.split())}"
+                    current[subtest] = ("fail", reason)
+        if current != previous:
+            updated[key] = current
+            changed.add(name)
+
+    result = expectations.copy()
+    for name in sorted(changed):
+        supported = supported_globals(tests[name])
+        rule_contexts = {}
+        for context in supported:
+            for subtest, (expect, reason) in updated.get((name, context), {}).items():
+                rule_contexts.setdefault((subtest, expect, reason), []).append(context)
+
+        entries = [
+            entry for entry in expectations.get(name, []) if entry["browser"] != browser
+        ]
+        for (subtest, expect, reason), contexts in rule_contexts.items():
+            # A rule with no context applies to every supported browser global.
+            for context in (None,) if contexts == supported else contexts:
+                entry = {"browser": browser}
+                if context is not None:
+                    entry["context"] = context
+                if subtest is not WHOLE_CASE:
+                    entry["subtest"] = subtest
+                entries.append({**entry, "expect": expect, "reason": reason})
+        if entries:
+            result[name] = entries
+        else:
+            result.pop(name)
+    return dict(sorted(result.items())) if changed else result
+
+
+def check_complete_report(report, rules, tests):
+    expected_cases = {
+        (name, context)
+        for name, path in tests.items()
+        for context in supported_globals(path)
+    }
+    reported_cases = {(case["test"], case["context"]) for case in report["results"]}
+    missing = expected_cases - reported_cases
+    if missing:
+        examples = ", ".join(
+            f"{name} [{context}]" for name, context in sorted(missing)[:3]
+        )
+        raise ValueError(
+            f"Report is missing {len(missing)} browser cases, including {examples}"
+        )
+
+    for case in report["results"]:
+        name, context = case["test"], case["context"]
+        case_rules = rules.get((name, context), {})
+        if (
+            case_rules.get(WHOLE_CASE, (None, None))[0] == "skip"
+            and case["status"] == "SKIP"
+        ):
+            continue
+        outcome, _ = evaluate_result(case, case_rules)
+        if not case["subtests"] or outcome not in ("PASS", "XFAIL"):
+            raise ValueError(
+                f"Cannot update from an incomplete or unresolved case: {name} [{context}]"
+            )
+
+
+def apply_report(expectations, report, tests, require_complete=False):
+    """Return the expectations updated with a browser report's results."""
+    browser = report["browser"]
+    if browser not in BROWSERS or not isinstance(report["results"], list):
+        raise ValueError("Expected a browser report with a results list")
+    rules = validate_expectations(expectations, tests, browser)
+    updated = update_expectations(expectations, rules, report, tests)
+    updated_rules = validate_expectations(updated, tests, browser)
+    if require_complete:
+        check_complete_report(report, updated_rules, tests)
+    return updated
diff --git a/test/js-api/scripts/lib/tests.py b/test/js-api/scripts/lib/tests.py
new file mode 100644
index 0000000..5f92705
--- /dev/null
+++ b/test/js-api/scripts/lib/tests.py
@@ -0,0 +1,90 @@
+"""Test discovery, META parsing and shared helpers for the JS API scripts."""
+
+import json
+import re
+from functools import cache
+from pathlib import Path
+from urllib.parse import quote
+
+SCRIPTS = Path(__file__).resolve().parent.parent
+TEST_DIR = SCRIPTS.parent
+EXPECTATIONS = SCRIPTS / "expectations.json"
+PINS = SCRIPTS / "browser-versions.json"
+PREFIX = "/wasm/jsapi/"
+HARNESS = "/resources/testharness.js"
+BROWSERS = ("chrome", "firefox", "safari")
+BROWSER_GLOBALS = ("window", "dedicatedworker")
+VERSION = re.compile(r"\d+(?:\.\d+)*")
+
+
+def version_key(version):
+    return tuple(map(int, version.split(".")))
+
+
+@cache
+def test_metadata(path):
+    globals_ = set(BROWSER_GLOBALS)
+    helpers = []
+    timeout = "normal"
+    with path.open(encoding="utf-8-sig") as source:
+        for line in source:
+            line = line.strip()
+            if line and not line.startswith("//"):
+                break
+            if not line.startswith("// META:"):
+                continue
+            match = re.fullmatch(r"// META:\s*(\w+)=(.+)", line)
+            if not match:
+                raise ValueError(f"{path.name}: invalid metadata: {line}")
+            key, value = match.groups()
+            if key == "global":
+                globals_ = {name.strip() for name in value.split(",")}
+                # Accept globals used by WPT even when this runner cannot launch them.
+                unknown = globals_ - {*BROWSER_GLOBALS, "jsshell", "shadowrealm"}
+                if unknown:
+                    raise ValueError(
+                        f"{path.name}: unsupported globals: {', '.join(sorted(unknown))}"
+                    )
+            elif key == "script":
+                helpers.append(value)
+            elif key == "timeout" and value == "long":
+                timeout = value
+            else:
+                raise ValueError(f"{path.name}: unsupported metadata: {line}")
+    return globals_, helpers, timeout
+
+
+def supported_globals(path):
+    globals_, _, _ = test_metadata(path)
+    return [context for context in BROWSER_GLOBALS if context in globals_]
+
+
+def discover_tests():
+    sources = {
+        path.relative_to(TEST_DIR).as_posix(): path
+        for path in TEST_DIR.rglob("*.js")
+        if not path.is_relative_to(SCRIPTS)
+    }
+    scripts = {PREFIX + quote(name): path for name, path in sources.items()}
+    scripts[HARNESS] = TEST_DIR.parent / "harness" / "testharness.js"
+    tests = {name: path for name, path in sources.items() if name.endswith(".any.js")}
+    return scripts, tests
+
+
+def unique_json_keys(pairs):
+    result = {}
+    for key, value in pairs:
+        if key in result:
+            raise ValueError(f"Duplicate key: {key}")
+        result[key] = value
+    return result
+
+
+def read_json(path):
+    return json.loads(
+        path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys
+    )
+
+
+def write_json(path, data):
+    path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
diff --git a/test/js-api/scripts/run.py b/test/js-api/scripts/run.py
index 3637a3e..ebdf116 100755
--- a/test/js-api/scripts/run.py
+++ b/test/js-api/scripts/run.py
@@ -3,29 +3,33 @@
 
 import argparse
 import json
-import re
 from collections import Counter
 from contextlib import nullcontext
 from dataclasses import dataclass
-from functools import cache
 from html import escape
 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
 from pathlib import Path
 from threading import Thread
 from urllib.parse import quote, urljoin, urlsplit
 
-SCRIPTS = Path(__file__).resolve().parent
-SUITE = SCRIPTS.parent
-MANIFEST = SCRIPTS / "expectations.json"
-PREFIX = "/wasm/jsapi/"
-HARNESS = "/resources/testharness.js"
-BROWSERS = ("chrome", "firefox", "safari")
-BROWSER_GLOBALS = ("window", "dedicatedworker")
+from lib.expectations import WHOLE_CASE, evaluate_result, validate_expectations
+from lib.tests import (
+    BROWSER_GLOBALS,
+    BROWSERS,
+    HARNESS,
+    EXPECTATIONS,
+    PREFIX,
+    VERSION,
+    discover_tests,
+    read_json,
+    test_metadata,
+    write_json,
+)
+
 # Match the timeout values in testharness.js.
 HARNESS_TIMEOUT_SECONDS = {"normal": 10, "long": 60}
 WEBDRIVER_GRACE_SECONDS = 5
-# Manifest rules without a subtest name apply to the whole browser case.
-WHOLE_CASE = None
+OUTCOMES = ("PASS", "FAIL", "XFAIL", "XPASS", "SKIP")
 
 REPORTER = """\
 setup({output: false});
@@ -70,51 +74,7 @@
     timeout_seconds: int
 
 
-def test_metadata(path):
-    globals_ = set(BROWSER_GLOBALS)
-    helpers = []
-    timeout = "normal"
-    with path.open(encoding="utf-8-sig") as source:
-        for line in source:
-            line = line.strip()
-            if line and not line.startswith("//"):
-                break
-            if not line.startswith("// META:"):
-                continue
-            match = re.fullmatch(r"// META:\s*(\w+)=(.+)", line)
-            if not match:
-                raise ValueError(f"{path.name}: invalid metadata: {line}")
-            key, value = match.groups()
-            if key == "global":
-                globals_ = {name.strip() for name in value.split(",")}
-                # Accept globals used by WPT even when this runner cannot launch them.
-                unknown = globals_ - {*BROWSER_GLOBALS, "jsshell", "shadowrealm"}
-                if unknown:
-                    raise ValueError(
-                        f"{path.name}: unsupported globals: {', '.join(sorted(unknown))}"
-                    )
-            elif key == "script":
-                helpers.append(value)
-            elif key == "timeout" and value == "long":
-                timeout = value
-            else:
-                raise ValueError(f"{path.name}: unsupported metadata: {line}")
-    return globals_, helpers, timeout
-
-
-def discover_suite():
-    sources = {
-        path.relative_to(SUITE).as_posix(): path
-        for path in SUITE.rglob("*.js")
-        if not path.is_relative_to(SCRIPTS)
-    }
-    scripts = {PREFIX + quote(name): path for name, path in sources.items()}
-    scripts[HARNESS] = SUITE.parent / "harness" / "testharness.js"
-    tests = {name: path for name, path in sources.items() if name.endswith(".any.js")}
-    return scripts, tests
-
-
-def generate_test_pages(scripts, tests, selected, contexts, metadata_for):
+def generate_test_pages(scripts, tests, selected, contexts):
     unknown = selected - tests.keys()
     if unknown:
         raise ValueError(f"Unknown tests: {', '.join(sorted(unknown))}")
@@ -123,7 +83,7 @@
     for name in sorted(selected or tests):
         url = PREFIX + quote(name)
         stem = url.removesuffix(".js")
-        globals_, helpers, timeout_mode = metadata_for(tests[name])
+        globals_, helpers, timeout_mode = test_metadata(tests[name])
         sources = [urljoin(url, helper) for helper in helpers]
         for source in sources:
             if source not in scripts:
@@ -209,80 +169,6 @@
     return ThreadingHTTPServer(("127.0.0.1", 0), Handler)
 
 
-def unique_json_keys(pairs):
-    result = {}
-    for key, value in pairs:
-        if key in result:
-            raise ValueError(f"Duplicate key: {key}")
-        result[key] = value
-    return result
-
-
-def read_json(path):
-    return json.loads(
-        path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys
-    )
-
-
-def validate_expectations(by_test, tests, browser, metadata_for):
-    if not isinstance(by_test, dict):
-        raise ValueError("Expected an object keyed by test path")
-
-    rules = {}
-    required = {"browser", "expect", "reason"}
-    allowed = required | {"context", "subtest"}
-    for name, entries in by_test.items():
-        if name not in tests:
-            raise ValueError(f"Unknown test: {name}")
-        if not isinstance(entries, list):
-            raise ValueError(f"{name}: expected a list of rules")
-        globals_, _, _ = metadata_for(tests[name])
-        supported = [context for context in BROWSER_GLOBALS if context in globals_]
-        for index, entry in enumerate(entries, 1):
-            label = f"{name} rule {index}"
-            if (
-                not isinstance(entry, dict)
-                or not required <= entry.keys() <= allowed
-                or not all(
-                    isinstance(value, str) and value.strip() for value in entry.values()
-                )
-            ):
-                raise ValueError(
-                    f"{label}: provide browser, expect, reason and optional context or subtest"
-                )
-            product, expect = entry["browser"], entry["expect"]
-            subtest = entry.get("subtest", WHOLE_CASE)
-            if product not in BROWSERS or expect not in ("fail", "skip"):
-                raise ValueError(f"{label}: invalid browser or expectation")
-            if expect == "skip" and subtest is not WHOLE_CASE:
-                raise ValueError(f"{label}: skip applies to a whole test case")
-            requested_context = entry.get("context")
-            contexts = [
-                context
-                for context in supported
-                if requested_context is None or context == requested_context
-            ]
-            if not contexts:
-                raise ValueError(f"{label}: no supported browser context")
-            for context in contexts:
-                case_rules = rules.setdefault((product, name, context), {})
-                if (
-                    subtest in case_rules
-                    or WHOLE_CASE in case_rules
-                    or (subtest is WHOLE_CASE and case_rules)
-                ):
-                    raise ValueError(
-                        f"{label}: overlapping rules for {product} [{context}]"
-                    )
-                case_rules[subtest] = (expect, entry["reason"])
-
-    return {
-        (name, context): case_rules
-        for (product, name, context), case_rules in rules.items()
-        if product == browser
-    }
-
-
 def create_driver(browser, browser_version):
     try:
         from selenium import webdriver
@@ -334,58 +220,14 @@
         return {"status": "ERROR", "message": message, "subtests": []}
 
 
-def evaluate_result(result, rules):
-    """Apply failure expectations after the harness has completed successfully."""
-    subtests = result["subtests"]
-    failures = [test for test in subtests if test["status"] != "PASS"]
-    diagnostics = [
-        f"{test['status']} {test['name']}: {test['message']}" for test in failures
-    ]
-    if result["status"] != "OK":
-        return "FAIL", [f"{result['status']}: {result['message']}", *diagnostics]
-    # Only a subtest with status FAIL can satisfy a failure expectation.
-    if WHOLE_CASE in rules:
-        _, reason = rules[WHOLE_CASE]
-        if not failures:
-            return "XPASS", [f"Expected a failure: {reason}"]
-        if all(test["status"] == "FAIL" for test in failures):
-            return "XFAIL", [reason, *diagnostics]
-        return "FAIL", diagnostics
-
-    by_name = {test["name"]: test for test in subtests}
-    missing = rules.keys() - by_name.keys()
-    unexpected = [
-        test
-        for test in failures
-        if test["name"] not in rules or test["status"] != "FAIL"
-    ]
-    expected_failures_that_passed = [
-        name for name in rules if name in by_name and by_name[name]["status"] == "PASS"
-    ]
-    diagnostics += [f"Expected subtest missing: {name}" for name in sorted(missing)]
-    diagnostics += [
-        f"XPASS {name}: {rules[name][1]}" for name in expected_failures_that_passed
-    ]
-    # Missing expected subtests and unexpected failures take precedence over XPASS.
-    if missing or unexpected:
-        return "FAIL", diagnostics
-    if expected_failures_that_passed:
-        return "XPASS", diagnostics
-    if rules:
-        return "XFAIL", [
-            f"{name}: {reason}" for name, (_, reason) in rules.items()
-        ] + diagnostics
-    return "PASS", []
-
-
-def run_browser(browser, browser_version, base_url, cases, expectations):
+def run_browser(browser, browser_version, base_url, cases, rules):
     results = []
     counts = Counter()
     selected = [
-        (case, expectations.get((case.name, case.context), {})) for case in cases
+        (case, rules.get((case.name, case.context), {})) for case in cases
     ]
     has_runnable_cases = any(
-        rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, rules in selected
+        case_rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, case_rules in selected
     )
     with (
         create_driver(browser, browser_version)
@@ -409,8 +251,8 @@
             + (f" (version {version})" if version else ""),
             flush=True,
         )
-        for case, rules in selected:
-            expect, reason = rules.get(WHOLE_CASE, (None, None))
+        for case, case_rules in selected:
+            expect, reason = case_rules.get(WHOLE_CASE, (None, None))
             if expect == "skip":
                 result = {"status": "SKIP", "message": reason, "subtests": []}
                 outcome, diagnostics = "SKIP", [reason]
@@ -418,7 +260,7 @@
                 result = read_result(
                     driver, base_url + case.page_path, case.timeout_seconds
                 )
-                outcome, diagnostics = evaluate_result(result, rules)
+                outcome, diagnostics = evaluate_result(result, case_rules)
             counts[outcome] += 1
             print(
                 f"{outcome} {case.name} [{case.context}] ({len(result['subtests'])} subtests)",
@@ -436,17 +278,21 @@
                 }
             )
 
-    print(
-        ", ".join(
-            f"{counts[status]} {status}"
-            for status in ("PASS", "FAIL", "XFAIL", "XPASS", "SKIP")
-        ),
-        flush=True,
-    )
+    print(", ".join(f"{counts[outcome]} {outcome}" for outcome in OUTCOMES), flush=True)
     report = {"browser": browser, "version": version, "results": results}
     return report, int(counts["FAIL"] > 0 or counts["XPASS"] > 0)
 
 
+def write_summary(path, report):
+    counts = Counter(case["outcome"] for case in report["results"])
+    title = " ".join(filter(None, ("Wasm JS API in", report["browser"], report["version"])))
+    with path.open("a", encoding="utf-8") as summary:
+        summary.write(f"### {title}\n\n")
+        summary.write("| Pass | Fail | Expected failure | Unexpected pass | Skip |\n")
+        summary.write("| ---: | ---: | ---: | ---: | ---: |\n")
+        summary.write("| " + " | ".join(str(counts[outcome]) for outcome in OUTCOMES) + " |\n")
+
+
 def main():
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument(
@@ -466,9 +312,12 @@
     )
     parser.add_argument("--json", type=Path, help="Write a JSON report to this file")
     parser.add_argument(
-        "--manifest",
+        "--summary", type=Path, help="Append a Markdown results table to this file"
+    )
+    parser.add_argument(
+        "--expectations",
         type=Path,
-        default=MANIFEST,
+        default=EXPECTATIONS,
         help="Expectations file (default: test/js-api/scripts/expectations.json)",
     )
     parser.add_argument(
@@ -478,22 +327,16 @@
         "tests", nargs="*", help="Test paths relative to test/js-api (default: all)"
     )
     args = parser.parse_args()
-    if args.browser_version and not re.fullmatch(
-        r"\d+(?:\.\d+)*", args.browser_version
-    ):
+    if args.browser_version and not VERSION.fullmatch(args.browser_version):
         parser.error("--browser-version must be a version number")
-    scripts, tests = discover_suite()
-    metadata_for = cache(test_metadata)
+    scripts, tests = discover_tests()
 
     if not args.serve:
         try:
-            # Validate the full manifest even when the run selects only a few cases.
-            manifest = read_json(args.manifest)
-            expectations = validate_expectations(
-                manifest, tests, args.browser, metadata_for
-            )
+            # Validate all expectations even when the run selects only a few cases.
+            rules = validate_expectations(read_json(args.expectations), tests, args.browser)
         except (OSError, ValueError) as error:
-            parser.error(f"{args.manifest}: {error}")
+            parser.error(f"{args.expectations}: {error}")
 
     contexts = tuple(
         context
@@ -502,7 +345,7 @@
     )
     try:
         pages, cases = generate_test_pages(
-            scripts, tests, set(args.tests), contexts, metadata_for
+            scripts, tests, set(args.tests), contexts
         )
     except ValueError as error:
         parser.error(str(error))
@@ -520,13 +363,15 @@
         thread.start()
         try:
             report, status = run_browser(
-                args.browser, args.browser_version, base_url, cases, expectations
+                args.browser, args.browser_version, base_url, cases, rules
             )
         finally:
             server.shutdown()
             thread.join()
     if args.json:
-        args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+        write_json(args.json, report)
+    if args.summary:
+        write_summary(args.summary, report)
     return status
 
 
diff --git a/test/js-api/scripts/update-expectations.py b/test/js-api/scripts/update-expectations.py
index d354239..6619e24 100755
--- a/test/js-api/scripts/update-expectations.py
+++ b/test/js-api/scripts/update-expectations.py
@@ -3,134 +3,10 @@
 
 import argparse
 import json
-from functools import cache
 from pathlib import Path
 
-from run import (
-    BROWSER_GLOBALS,
-    BROWSERS,
-    MANIFEST,
-    WHOLE_CASE,
-    discover_suite,
-    evaluate_result,
-    read_json,
-    test_metadata,
-    validate_expectations,
-)
-
-
-def update_expectations(manifest, rules, report, tests, metadata_for):
-    """Refresh failure rules for the browser cases covered by a result report."""
-    browser, version = report["browser"], report.get("version")
-    updated = rules.copy()
-    seen = set()
-    changed = set()
-    for case in report["results"]:
-        name, context = case["test"], case["context"]
-        key = (name, context)
-        if (
-            name not in tests
-            or context not in BROWSER_GLOBALS
-            or context not in metadata_for(tests[name])[0]
-            or key in seen
-        ):
-            raise ValueError(f"Unknown or duplicate browser case: {name} [{context}]")
-        seen.add(key)
-        subtests = case["subtests"]
-        previous = rules.get(key, {})
-        # A skip or an incomplete run gives no reliable evidence about this case.
-        if (
-            case["status"] != "OK"
-            or not subtests
-            or any(test["status"] not in ("PASS", "FAIL") for test in subtests)
-            or previous.get(WHOLE_CASE, (None, None))[0] == "skip"
-        ):
-            continue
-        failures = {
-            test["name"]: test.get("message")
-            for test in subtests
-            if test["status"] == "FAIL"
-        }
-        whole_case = previous.get(WHOLE_CASE)
-        if whole_case and failures:
-            current = previous
-        else:
-            current = {}
-            for subtest, message in failures.items():
-                if subtest in previous:
-                    current[subtest] = previous[subtest]
-                else:
-                    reason = f"Observed in {browser.capitalize()}"
-                    if version:
-                        reason += f" {version}"
-                    if message:
-                        reason += f": {' '.join(message.split())}"
-                    current[subtest] = ("fail", reason)
-        if current != previous:
-            updated[key] = current
-            changed.add(name)
-
-    result = manifest.copy()
-    for name in sorted(changed):
-        supported = [
-            context
-            for context in BROWSER_GLOBALS
-            if context in metadata_for(tests[name])[0]
-        ]
-        rule_contexts = {}
-        for context in supported:
-            for subtest, (expect, reason) in updated.get((name, context), {}).items():
-                rule_contexts.setdefault((subtest, expect, reason), []).append(context)
-
-        entries = [
-            entry for entry in manifest.get(name, []) if entry["browser"] != browser
-        ]
-        for (subtest, expect, reason), contexts in rule_contexts.items():
-            # A rule with no context applies to every supported browser global.
-            for context in (None,) if contexts == supported else contexts:
-                entry = {"browser": browser}
-                if context is not None:
-                    entry["context"] = context
-                if subtest is not WHOLE_CASE:
-                    entry["subtest"] = subtest
-                entries.append({**entry, "expect": expect, "reason": reason})
-        if entries:
-            result[name] = entries
-        else:
-            result.pop(name)
-    return dict(sorted(result.items())) if changed else result
-
-
-def check_complete_report(report, rules, tests, metadata_for):
-    expected_cases = {
-        (name, context)
-        for name, path in tests.items()
-        for context in BROWSER_GLOBALS
-        if context in metadata_for(path)[0]
-    }
-    reported_cases = {(case["test"], case["context"]) for case in report["results"]}
-    missing = expected_cases - reported_cases
-    if missing:
-        examples = ", ".join(
-            f"{name} [{context}]" for name, context in sorted(missing)[:3]
-        )
-        raise ValueError(
-            f"Report is missing {len(missing)} browser cases, including {examples}"
-        )
-
-    for case in report["results"]:
-        name, context = case["test"], case["context"]
-        case_rules = rules.get((name, context), {})
-        if (
-            case_rules.get(WHOLE_CASE, (None, None))[0] == "skip"
-            and case["status"] == "SKIP"
-        ):
-            continue
-        outcome, _ = evaluate_result(case, case_rules)
-        if not case["subtests"] or outcome not in ("PASS", "XFAIL"):
-            raise ValueError(
-                f"Cannot update from an incomplete or unresolved case: {name} [{context}]"
-            )
+from lib.expectations import apply_report
+from lib.tests import EXPECTATIONS, discover_tests, read_json, write_json
 
 
 def main():
@@ -139,41 +15,28 @@
         "report", type=Path, help="Browser JSON report from run.py or CI"
     )
     parser.add_argument(
-        "--manifest",
+        "--expectations",
         type=Path,
-        default=MANIFEST,
-        help="Base expectations file (default: test/js-api/scripts/expectations.json)",
+        default=EXPECTATIONS,
+        help="Expectations file to update (default: test/js-api/scripts/expectations.json)",
     )
     parser.add_argument(
-        "--require-complete",
+        "--in-place",
         action="store_true",
-        help="Reject reports with missing or unresolved cases (used by CI)",
+        help="Write the result back to the expectations file instead of stdout",
     )
     args = parser.parse_args()
+    _, tests = discover_tests()
     try:
-        report = read_json(args.report)
-        browser = report["browser"]
-        if browser not in BROWSERS or not isinstance(report["results"], list):
-            raise ValueError("Expected a browser report with a results list")
-    except (OSError, ValueError, KeyError, TypeError) as error:
-        parser.error(f"{args.report}: {error}")
-
-    _, tests = discover_suite()
-    metadata_for = cache(test_metadata)
-    try:
-        manifest = read_json(args.manifest)
-        rules = validate_expectations(manifest, tests, browser, metadata_for)
-    except (OSError, ValueError) as error:
-        parser.error(f"{args.manifest}: {error}")
-
-    try:
-        updated = update_expectations(manifest, rules, report, tests, metadata_for)
-        updated_rules = validate_expectations(updated, tests, browser, metadata_for)
-        if args.require_complete:
-            check_complete_report(report, updated_rules, tests, metadata_for)
+        updated = apply_report(
+            read_json(args.expectations), read_json(args.report), tests
+        )
     except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
-        parser.error(f"{args.report}: {error}")
-    print(json.dumps(updated, indent=2))
+        parser.error(str(error))
+    if args.in_place:
+        write_json(args.expectations, updated)
+    else:
+        print(json.dumps(updated, indent=2))
 
 
 if __name__ == "__main__":