Modern Apps git

← MAOS.git

maos: multi-device build support and install-zip script.txt flash plan

Commit
1474b2a557f8fc0d02654bb09c59d1fc26052be5
Author
Vayun Mathur <[email protected]>
When
2026-08-11 02:29 UTC (3 months ago)
Parents
275c882

Diff

build-maos.sh
diff --git a/build-maos.sh b/build-maos.shindex 6b30a60..c0f716b 100755--- a/build-maos.sh+++ b/build-maos.sh@@ -8,16 +8,25 @@ # # It is phase-based and resumable — rerun a phase or the whole thing safely. #-#   ./build-maos.sh all                         # full pipeline+#   ./build-maos.sh all                         # full pipeline (cheetah) #   ./build-maos.sh sync                         # just one phase #   ./build-maos.sh -d panther -t 2026080500 all # override device/tag via flags+#   ./build-maos.sh -d all all                   # build EVERY supported Pixel+#   ./build-maos.sh -d cheetah,panther build     # a comma-separated subset # # Usage: ./build-maos.sh [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...> #   -d DEVICE    Pixel codename / build target   (default: cheetah)+#                 - a single codename (e.g. cheetah)+#                 - "all" to build every supported Pixel (see ALL_DEVICES)+#                 - a comma-separated subset (e.g. cheetah,panther) #   -t TAG       GrapheneOS base tag             (default: 2026080500) #   -c CHANNEL   OTA channel to publish          (default: stable; stable|beta|testing) #   phases: deps sync vendor overlay keys build release publish all #+# deps/sync/keys are device-independent and run ONCE; vendor/overlay/build/release/publish+# run per selected device. In a multi-device run a failed device is logged and the run+# continues to the next device, with a pass/fail summary printed at the end.+# # ── Signing keys ──────────────────────────────────────────────────────────────────────── # Keys live in ONE scrypt-encrypted file ($MAOS_KEYS_FILE), unlocked with a passphrase you # pass in the environment ($MAOS_KEYS_PASSPHRASE). On first run (file absent) the `keys` phase@@ -25,13 +34,17 @@ # script decrypts it into RAM (/dev/shm), uses it, and shreds the plaintext on exit — the # keys are never written to disk in the clear. #+# The key set is DEVICE-INDEPENDENT: one shared set signs every device (the GrapheneOS+# signing scripts read keys from keys/<device>, so unlock_keys symlinks the one shared+# plaintext set in as keys/<device> for whichever device is being built).+# # ── Required environment ──────────────────────────────────────────────────────────────── #   MAOS_KEYS_PASSPHRASE   passphrase for the encrypted key file (required for keys/build/release) # For publishing: #   R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY   Cloudflare R2 creds # # ── Optional environment ────────────────────────────────────────────────────────────────-#   MAOS_KEYS_FILE=$HOME/maos-keys/$DEVICE.keys.tar.gz.enc   encrypted key blob (outside the tree)+#   MAOS_KEYS_FILE=$HOME/maos-keys/maos.keys.tar.gz.scrypt   encrypted key blob (shared, outside the tree) #   MODERN_APPS_SRC=<path>         Modern-Apps checkout/dir with release APKs; if unset, the 9 #                                  APKs are downloaded from the Modern-Apps GitHub release #@@ -49,12 +62,26 @@ while getopts "d:t:c:h" _opt; do         d) DEVICE="$OPTARG" ;;         t) TAG="$OPTARG" ;;         c) OTA_CHANNEL="$OPTARG" ;;-        h) sed -n '2,15p' "$0"; exit 0 ;;+        h) sed -n '2,32p' "$0"; exit 0 ;;         *) echo "usage: $0 [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...>" >&2; exit 2 ;;     esac done shift $((OPTIND - 1)) +# Every supported Pixel (fastboot codenames), kept in sync with the web installer's DEVICES+# map (location_share_server/os_installer/installer.js). `-d all` expands to this list.+ALL_DEVICES=(stallion rango mustang blazer frankel tegu comet komodo caiman tokay \+             akita husky shiba felix tangorpro lynx cheetah panther bluejay raven oriole)++# Expand -d into DEVICES_LIST: "all" -> every device; "a,b,c" -> that subset; else a single device.+if [[ "$DEVICE" == "all" ]]; then+    DEVICES_LIST=("${ALL_DEVICES[@]}")+elif [[ "$DEVICE" == *,* ]]; then+    IFS=',' read -r -a DEVICES_LIST <<< "$DEVICE"+else+    DEVICES_LIST=("$DEVICE")+fi+ # ---- Hardcoded config ---- TREE="$HOME/maos"                              # AOSP checkout (ext4; never /mnt/c) R2_BUCKET="maos"                               # R2 bucket / ota.ma.vayunmathur.com@@ -69,11 +96,12 @@ MODERN_APPS_GH="vayun-mathur/Modern-Apps"      # source of the prebuilt APKs APPS=(web camera pdf contacts calculator clock files photos appstore keyboard speech calendar music networklocation)  # ---- Derived / optional-env config -----MAOS_KEYS_FILE="${MAOS_KEYS_FILE:-$HOME/maos-keys/$DEVICE.keys.tar.gz.scrypt}"+# ONE shared, device-independent key set (see the "Signing keys" note above).+MAOS_KEYS_FILE="${MAOS_KEYS_FILE:-$HOME/maos-keys/maos.keys.tar.gz.scrypt}" MODERN_APPS_SRC="${MODERN_APPS_SRC:-}"  # Plaintext keys are only ever materialized here (RAM-backed), and shredded on exit.-KEYS_PLAIN="/dev/shm/maos-keys-$DEVICE"+KEYS_PLAIN="/dev/shm/maos-keys"  # Prefer user-writable tool installs (a writable `repo` launcher so it can self-update instead # of warning, plus anything else we drop in ~/.local/bin) over system copies.@@ -94,8 +122,12 @@ wipe_plain_keys() {         find "$KEYS_PLAIN" -type f -exec shred -u {} + 2>/dev/null || true         rm -rf "$KEYS_PLAIN"     fi-    # Drop the in-tree symlink to the RAM keys, if we made one.-    [[ -L "$TREE/keys/$DEVICE" ]] && rm -f "$TREE/keys/$DEVICE" || true+    # Drop every in-tree symlink to the RAM keys we created (one keys/<device> per built device).+    if [[ -d "$TREE/keys" ]]; then+        for _l in "$TREE"/keys/*; do+            [[ -L "$_l" ]] && rm -f "$_l" || true+        done+    fi } trap wipe_plain_keys EXIT @@ -371,10 +403,13 @@ phase_publish() {         --only-show-errors      log "Publishing factory image for the web installer"+    # The web installer consumes the *install* zip (contains super_1..N.img already split to+    # the device max-download-size, plus script.txt — GrapheneOS's verified flash sequence).+    # prepare-factory.sh translates that script.txt into the ordered installer manifest.     R2_BUCKET="$R2_BUCKET" vendor/modern-apps/installer/prepare-factory.sh \-        -d "$DEVICE" -b "$BUILD" -f "$rel/$DEVICE-factory-$BUILD.zip" \-        || warn "prepare-factory.sh failed — see its output. For a real release pass -P plan.json \-mirroring flash-all (incl. flashing avb_custom_key before lock)."+        -d "$DEVICE" -b "$BUILD" -f "$rel/$DEVICE-install-$BUILD.zip" \+        || warn "prepare-factory.sh failed — see its output. For a factory-zip fallback pass -P \+plan.json mirroring flash-all (incl. flashing avb_custom_key before lock)."     log "Done. OTA: https://ota.ma.vayunmathur.com/$DEVICE-$OTA_CHANNEL" } @@ -389,14 +424,55 @@ run_phase() {         build) phase_build ;;         release) phase_release ;;         publish) phase_publish ;;-        all)-            phase_deps; phase_sync; phase_vendor; phase_overlay-            phase_keys; phase_build; phase_release; phase_publish ;;         *) die "Unknown phase '$1'. Use: deps sync vendor overlay keys build release publish all" ;;     esac } -[[ $# -gt 0 ]] || { echo "usage: $0 [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...>   (phases: deps sync vendor overlay keys build release publish all)"; exit 2; }-log "MAOS build — device=$DEVICE tag=$TAG build=$BUILD channel=$OTA_CHANNEL tree=$TREE bucket=$R2_BUCKET"-for p in "$@"; do run_phase "$p"; done+# deps/sync/keys are device-independent (run once); everything else runs per device.+is_independent() { case "$1" in deps|sync|keys) return 0 ;; *) return 1 ;; esac; }++[[ $# -gt 0 ]] || { echo "usage: $0 [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...>   (phases: deps sync vendor overlay keys build release publish all; -d accepts a codename, 'all', or a comma-separated subset)"; exit 2; }++# Expand 'all' and split the requested phases into run-once (device-independent) and+# per-device groups, preserving order within each group.+INDEP_PHASES=()+PERDEV_PHASES=()+for p in "$@"; do+    case "$p" in+        all)+            INDEP_PHASES+=(deps sync keys)+            PERDEV_PHASES+=(vendor overlay build release publish) ;;+        deps|sync|vendor|overlay|keys|build|release|publish)+            if is_independent "$p"; then INDEP_PHASES+=("$p"); else PERDEV_PHASES+=("$p"); fi ;;+        *) die "Unknown phase '$p'. Use: deps sync vendor overlay keys build release publish all" ;;+    esac+done++log "MAOS build — devices=[${DEVICES_LIST[*]}] tag=$TAG build=$BUILD channel=$OTA_CHANNEL tree=$TREE bucket=$R2_BUCKET"++# 1) Device-independent phases, once.+for p in ${INDEP_PHASES[@]+"${INDEP_PHASES[@]}"}; do+    run_phase "$p"+done++# 2) Per-device phases, once per selected device. Each device runs in a subshell so that a+#    failure (set -e) aborts only that device — we log it and continue to the next — and the+#    EXIT key-wipe trap (reset inside subshells) does not fire between devices.+if [[ "${#PERDEV_PHASES[@]}" -gt 0 ]]; then+    SUMMARY=()+    for dev in "${DEVICES_LIST[@]}"; do+        log "=== Device $dev: ${PERDEV_PHASES[*]} ==="+        if ( for p in "${PERDEV_PHASES[@]}"; do DEVICE="$dev"; run_phase "$p"; done ); then+            SUMMARY+=("$dev: OK")+        else+            warn "Device $dev FAILED during: ${PERDEV_PHASES[*]} — continuing with the next device."+            SUMMARY+=("$dev: FAILED")+        fi+    done+    log "Per-device summary (${#DEVICES_LIST[@]} device(s)):"+    for s in "${SUMMARY[@]}"; do printf '   %s\n' "$s"; done+    # Non-zero exit if any device failed, so callers/CI can detect a partial run.+    for s in "${SUMMARY[@]}"; do [[ "$s" == *": FAILED" ]] && exit 1; done+fi+ log "All requested phases complete."
installer/README.md
diff --git a/installer/README.md b/installer/README.mdindex 3db4ba8..bb51239 100644--- a/installer/README.md+++ b/installer/README.md@@ -9,8 +9,9 @@ flashes the MAOS factory image — no `adb`/`fastboot` tools or command line nee | Where | What | | --- | --- | | `location_share_server/os_installer/` | The static front-end: `install.html`, `install.css`, `installer.js` (wizard), `fastboot.js` (WebUSB fastboot client). Served at `/os/install` on `ma.vayunmathur.com`. |-| `MAOS/installer/prepare-factory.sh` | Build-host script: turns a factory image into a `manifest.json` + per-partition images (splitting oversized ones into sparse chunks) and uploads them to R2. |-| `MAOS/installer/sparse_split.py` | Splits a raw image into multiple Android sparse images, each under the device's max-download-size. |+| `MAOS/installer/prepare-factory.sh` | Build-host script: turns a release image into a `manifest.json` + per-partition images and uploads them to R2. For the **install zip** (preferred) it translates GrapheneOS's `script.txt` verbatim; for a legacy **factory zip** it builds a best-effort/`-P` plan and splits oversized images into sparse chunks. |+| `MAOS/installer/script_to_manifest.py` | Translates an install zip's `script.txt` (GrapheneOS's verified flash sequence) into ordered manifest steps. |+| `MAOS/installer/sparse_split.py` | Splits a raw image into multiple Android sparse images, each under the device's max-download-size (legacy factory-zip path only). | | R2 (`ota.ma.vayunmathur.com/factory/<device>/…`) | Hosts the manifest + images; the browser streams them directly. |  ## Flow@@ -24,9 +25,12 @@ factory image ──prepare-factory.sh──▶ manifest.json + images ──▶      Pixel in bootloader mode  ◀────────── streams images from R2 ────── ``` -The installer reads `factory/<device>/latest/manifest.json`, then for each step does-`flash` / `erase` / `reboot-bootloader` / `reboot` over WebUSB, streaming each referenced-image straight from R2.+The installer reads `factory/<device>/latest/manifest.json`, then for each step drives the+device over WebUSB — `check-var` / `check-requirements` (verify), `flash` (to the active or+inactive/"other" slot), `erase`, `run-cmd`, `toggle-active-slot` / `set-active`,+`snapshot-update-cancel`, `reboot-bootloader`, `reboot` — streaming each referenced image+straight from R2 and flashing it before fetching the next (so a multi-GB `super` never has+to fit in memory at once).  ## Before you have any builds @@ -50,32 +54,47 @@ either a 404 or `available: false` as "no build yet" (a friendly notice, not an ## Publishing a build for the installer  ```bash-# On the Linux build host, after producing a factory image (runbook step 8):+# On the Linux build host, after producing a release (runbook step 8): export R2_ACCESS_KEY_ID=...  R2_SECRET_ACCESS_KEY=...  R2_ACCOUNT_ID=...-installer/prepare-factory.sh -d shusky -b "$BUILD" -f <device>-factory-*.zip+installer/prepare-factory.sh -d cheetah -b "$BUILD" -f <device>-install-<build>.zip ```  This uploads to both `factory/<device>/<build>/` and `factory/<device>/latest/` (the-installer defaults to `latest`).+installer defaults to `latest`). `build-maos.sh`'s `publish` phase runs this for you with the+install zip. -### The flash plan (READ THIS)+### The flash plan -The exact partitions/slots/order for a real install are defined by the factory image's own-`flash-all.sh` and are device/release specific. `prepare-factory.sh` without `-P` generates-a **best-effort** plan and prints a warning — treat it as a scaffold, not a guarantee. For a-real release, pass an explicit plan mirroring that device's `flash-all`:+The correct, brick-safe flash sequence for a release is GrapheneOS's own — shipped as+`script.txt` inside the **install zip** (`<device>-install-<build>.zip`), alongside the whole+`super` already pre-split into `super_*.img`. When `prepare-factory.sh` sees a `script.txt`+it translates it verbatim (`script_to_manifest.py`) into ordered manifest steps and copies+the images as-is — no re-splitting, no invented plan. This is the default and what you should+use for a real release.++Supported step actions: `check-var`, `check-requirements`, `flash` (optional `slot:"other"`),+`erase`, `run-cmd`, `toggle-active-slot`, `set-active`, `snapshot-update-cancel`,+`reboot-bootloader`, `reboot`.++#### Legacy factory-zip fallback++If you only have a **factory zip** (no `script.txt`), `prepare-factory.sh` builds a+partition→image map and either follows an explicit `-P plan.json` or emits a **best-effort**+plan (and prints a warning). Oversized images (e.g. `super`) are split into sparse chunks+with `sparse_split.py`. Treat the auto plan as a scaffold — pass `-P` mirroring that device's+`flash-all` and validate on a device before publishing:  ```bash-installer/prepare-factory.sh -d shusky -b "$BUILD" -f factory.zip -P plan.json+installer/prepare-factory.sh -d cheetah -b "$BUILD" -f factory.zip -P plan.json ```  `plan.json` is a JSON array of steps, e.g.:  ```json [-  {"action":"flash","partition":"bootloader","image":"bootloader-shusky-*.img"},+  {"action":"flash","partition":"bootloader","image":"bootloader-cheetah-*.img"},   {"action":"reboot-bootloader"},-  {"action":"flash","partition":"radio","image":"radio-shusky-*.img"},+  {"action":"flash","partition":"radio","image":"radio-cheetah-*.img"},   {"action":"reboot-bootloader"},   {"action":"flash","partition":"boot","image":"boot.img"},   {"action":"flash","partition":"init_boot","image":"init_boot.img"},@@ -92,8 +111,6 @@ installer/prepare-factory.sh -d shusky -b "$BUILD" -f factory.zip -P plan.json over `-m` bytes (default 100 MiB, e.g. `super`) is auto-split into sparse chunks and expanded into multiple flash steps to the same partition. -Supported step actions: `flash`, `erase`, `reboot-bootloader`, `reboot`, `set-active`.- ## Required: R2 CORS  The installer page is served from `ma.vayunmathur.com` but fetches the manifest + images
installer/prepare-factory.sh
diff --git a/installer/prepare-factory.sh b/installer/prepare-factory.shindex 3e656ae..12e5f3a 100755--- a/installer/prepare-factory.sh+++ b/installer/prepare-factory.sh@@ -1,24 +1,31 @@ #!/usr/bin/env bash #-# prepare-factory.sh — turn a MAOS factory image into what the web installer consumes:-# a manifest.json flash plan plus per-partition images (splitting any image larger than-# the device's max-download-size into sparse chunks), uploaded to R2.+# prepare-factory.sh — turn a MAOS release image into what the web installer consumes:+# a manifest.json flash plan plus per-partition images, uploaded to R2. # # The web installer (ma.vayunmathur.com/os/install) fetches #   https://ota.ma.vayunmathur.com/factory/<device>/latest/manifest.json # and flashes each step, streaming the referenced images from the same directory. #-# ── IMPORTANT ──────────────────────────────────────────────────────────────────────────-# The exact flash sequence (which partitions, slots, and order) is device/release specific-# and is authoritatively defined by the factory image's own flash-all.sh. The auto-generated-# plan here is a BEST-EFFORT scaffold. For a real release, pass an explicit plan with -P-# (a JSON array of steps) that mirrors that device's flash-all, and validate on a device-# before publishing. See installer/README.md.+# ── Two input modes ────────────────────────────────────────────────────────────────────+# 1. INSTALL ZIP (preferred, correct):  <device>-install-<build>.zip+#    Ships GrapheneOS's *verified* `script.txt` flash sequence plus the whole `super`+#    already pre-split into `super_*.img` (sized to the device max-download-size, flashed in+#    bootloader mode — the lowest-brick-risk path). When a `script.txt` is present we+#    translate it verbatim (installer/script_to_manifest.py) into ordered manifest steps and+#    copy the images AS-IS (no re-splitting). This is what phase_publish in build-maos.sh+#    passes and what a real release should use.+#+# 2. FACTORY ZIP (legacy fallback):     <device>-factory-<build>.zip  (or any -P plan.json)+#    No script.txt. We build a partition->image map and either follow an explicit -P plan or+#    emit a BEST-EFFORT scaffold (prints a warning). Oversized images are split into sparse+#    chunks with sparse_split.py. Treat the auto plan as a scaffold, not a guarantee, and+#    validate on a device before publishing. See installer/README.md. # ───────────────────────────────────────────────────────────────────────────────────────── # # Usage:-#   installer/prepare-factory.sh -d shusky -b 2026080900 -f <factory-image.zip> \-#       [-P plan.json] [-m 104857600] [-O out/maos-factory] [-B maos-ota] [--no-upload]+#   installer/prepare-factory.sh -d cheetah -b 2026081000 -f <device>-install-<build>.zip \+#       [-P plan.json] [-m 104857600] [-O out/maos-factory] [-B maos] [--no-upload] # # R2 upload reuses the same env as ota/publish-ota.sh: #   R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and R2_ACCOUNT_ID (or R2_ENDPOINT).@@ -29,7 +36,7 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DEVICE="" ; BUILD="" ; FACTORY="" ; PLAN="" ; MAXB=$((100 * 1024 * 1024)) OUTDIR="out/maos-factory" ; BUCKET="${R2_BUCKET:-maos}" ; UPLOAD=1 -usage() { sed -n '2,30p' "$0" >&2; exit 2; }+usage() { sed -n '2,36p' "$0" >&2; exit 2; }  while [[ $# -gt 0 ]]; do     case "$1" in@@ -47,103 +54,132 @@ while [[ $# -gt 0 ]]; do done  [[ -n "$DEVICE" && -n "$BUILD" && -n "$FACTORY" ]] || usage-[[ -f "$FACTORY" ]] || { echo "factory image not found: $FACTORY" >&2; exit 1; }-command -v python3 >/dev/null || { echo "python3 required (for sparse_split.py)" >&2; exit 1; }+[[ -f "$FACTORY" ]] || { echo "image zip not found: $FACTORY" >&2; exit 1; }+command -v python3 >/dev/null || { echo "python3 required" >&2; exit 1; }  WORK="$(mktemp -d)" trap 'rm -rf "$WORK"' EXIT STAGE="$OUTDIR/$DEVICE/$BUILD" mkdir -p "$STAGE"+MANIFEST="$STAGE/manifest.json" -echo ">> unpacking factory image"+echo ">> unpacking $FACTORY" unzip -q -o "$FACTORY" -d "$WORK"-# Pixel factory images nest the partition images inside image-<device>-<build>.zip.-INNER="$(find "$WORK" -name 'image-*.zip' | head -1 || true)"-if [[ -n "$INNER" ]]; then-    unzip -q -o "$INNER" -d "$WORK/inner"-fi -# Collect a partition -> image-file map. Each *.img's partition is its basename sans .img.-declare -A IMG-add_img() { # add_img <path>-    local p; p="$(basename "$1")"; p="${p%.img}"-    # Normalize bootloader-/radio-<...> to bare partition names.-    case "$p" in-        bootloader-*) p="bootloader" ;;-        radio-*) p="radio" ;;-    esac-    IMG["$p"]="$1"-}-for f in "$WORK"/*.img "$WORK"/inner/*.img; do [[ -e "$f" ]] && add_img "$f"; done--# Stage an image for a partition, splitting into sparse chunks if it exceeds MAXB.-# Emits one or more manifest flash-step JSON objects on stdout.-stage_flash() { # stage_flash <partition> <src-image>-    local part="$1" src="$2" sz base steps=""-    sz="$(stat -c '%s' "$src")"-    base="$(basename "$src")"-    if (( sz <= MAXB )); then-        cp "$src" "$STAGE/$base"-        printf '{"action":"flash","partition":"%s","image":"%s"}' "$part" "$base"-    else-        echo "   splitting $base ($sz bytes) into sparse chunks <= $MAXB" >&2-        local prefix="$STAGE/${part}"-        # sparse_split prints each output path (one per line).-        local first=1-        while IFS= read -r chunk; do-            [[ $first -eq 1 ]] || steps+=","-            first=0-            steps+=$(printf '{"action":"flash","partition":"%s","image":"%s"}' \-                "$part" "$(basename "$chunk")")-        done < <(python3 "$HERE/sparse_split.py" "$src" "$prefix" --max-bytes "$MAXB")-        printf '%s' "$steps"+# Install-zip layout ships script.txt (GrapheneOS's verified flash sequence). Unless the+# caller forces an explicit -P plan, prefer translating that script verbatim.+SCRIPT_TXT="$(find "$WORK" -name script.txt | head -1 || true)"++if [[ -z "$PLAN" && -n "$SCRIPT_TXT" ]]; then+    # ---- Install-zip mode: translate script.txt, copy images as-is (no re-split) ----+    echo ">> install-zip detected (script.txt) — translating GrapheneOS flash sequence"+    SRCDIR="$(dirname "$SCRIPT_TXT")"+    python3 "$HERE/script_to_manifest.py" \+        --script "$SCRIPT_TXT" --device "$DEVICE" --build "$BUILD" --srcdir "$SRCDIR" \+        > "$MANIFEST" || { echo "script.txt translation failed" >&2; exit 1; }++    echo ">> copying referenced images as-is (super_*.img are already sized; no re-split)"+    # Every image the manifest's flash steps reference, from wherever it sits in the zip.+    while IFS= read -r img; do+        [[ -n "$img" ]] || continue+        src="$(find "$WORK" -name "$img" | head -1 || true)"+        [[ -n "$src" ]] || { echo "manifest references missing image: $img" >&2; exit 1; }+        cp "$src" "$STAGE/$img"+    done < <(python3 -c 'import json,sys+m=json.load(open(sys.argv[1]))+for s in m["steps"]:+    if s.get("action") == "flash":+        print(s["image"])' "$MANIFEST")+else+    # ---- Legacy factory-zip mode: partition map + (explicit or best-effort) plan ----+    # Pixel factory images nest the partition images inside image-<device>-<build>.zip.+    INNER="$(find "$WORK" -name 'image-*.zip' | head -1 || true)"+    if [[ -n "$INNER" ]]; then+        unzip -q -o "$INNER" -d "$WORK/inner"     fi-} -echo ">> building flash plan"-STEPS_JSON=""-append() { [[ -z "$STEPS_JSON" ]] || STEPS_JSON+=","; STEPS_JSON+="$1"; }--if [[ -n "$PLAN" ]]; then-    # Explicit plan: array of steps. `flash` steps name a partition + an image key that-    # must exist in IMG (or a literal file under the factory dir). We still split big ones.-    [[ -f "$PLAN" ]] || { echo "plan not found: $PLAN" >&2; exit 1; }-    command -v jq >/dev/null || { echo "jq required to use -P plan.json" >&2; exit 1; }-    while IFS= read -r line; do-        action="$(jq -r '.action' <<<"$line")"-        case "$action" in-            flash)-                part="$(jq -r '.partition' <<<"$line")"-                key="$(jq -r '.image' <<<"$line")"-                src="${IMG[$key]:-$WORK/$key}"-                [[ -e "$src" ]] || src="$WORK/inner/$key"-                [[ -e "$src" ]] || { echo "plan references missing image: $key" >&2; exit 1; }-                append "$(stage_flash "$part" "$src")"-                ;;-            *) append "$line" ;;+    # Collect a partition -> image-file map. Each *.img's partition is its basename sans .img.+    declare -A IMG+    add_img() { # add_img <path>+        local p; p="$(basename "$1")"; p="${p%.img}"+        # Normalize bootloader-/radio-<...> to bare partition names.+        case "$p" in+            bootloader-*) p="bootloader" ;;+            radio-*) p="radio" ;;         esac-    done < <(jq -c '.[]' "$PLAN")-else-    echo "   WARNING: no -P plan.json given; generating a best-effort plan. VERIFY against" >&2-    echo "            the device's real flash-all before trusting this for a release." >&2-    [[ -n "${IMG[bootloader]:-}" ]] && { append "$(stage_flash bootloader "${IMG[bootloader]}")"; append '{"action":"reboot-bootloader"}'; }-    [[ -n "${IMG[radio]:-}" ]] && { append "$(stage_flash radio "${IMG[radio]}")"; append '{"action":"reboot-bootloader"}'; }-    for part in "${!IMG[@]}"; do-        case "$part" in bootloader|radio) continue ;; esac-        append "$(stage_flash "$part" "${IMG[$part]}")"-    done-    append '{"action":"erase","partition":"userdata"}'-    append '{"action":"reboot"}'-fi+        IMG["$p"]="$1"+    }+    for f in "$WORK"/*.img "$WORK"/inner/*.img; do [[ -e "$f" ]] && add_img "$f"; done -MANIFEST="$STAGE/manifest.json"-cat > "$MANIFEST" <<EOF+    # Stage an image for a partition, splitting into sparse chunks if it exceeds MAXB.+    # Emits one or more manifest flash-step JSON objects on stdout.+    stage_flash() { # stage_flash <partition> <src-image>+        local part="$1" src="$2" sz base steps=""+        sz="$(stat -c '%s' "$src")"+        base="$(basename "$src")"+        if (( sz <= MAXB )); then+            cp "$src" "$STAGE/$base"+            printf '{"action":"flash","partition":"%s","image":"%s"}' "$part" "$base"+        else+            echo "   splitting $base ($sz bytes) into sparse chunks <= $MAXB" >&2+            local prefix="$STAGE/${part}"+            # sparse_split prints each output path (one per line).+            local first=1+            while IFS= read -r chunk; do+                [[ $first -eq 1 ]] || steps+=","+                first=0+                steps+=$(printf '{"action":"flash","partition":"%s","image":"%s"}' \+                    "$part" "$(basename "$chunk")")+            done < <(python3 "$HERE/sparse_split.py" "$src" "$prefix" --max-bytes "$MAXB")+            printf '%s' "$steps"+        fi+    }++    echo ">> building flash plan"+    STEPS_JSON=""+    append() { [[ -z "$STEPS_JSON" ]] || STEPS_JSON+=","; STEPS_JSON+="$1"; }++    if [[ -n "$PLAN" ]]; then+        # Explicit plan: array of steps. `flash` steps name a partition + an image key that+        # must exist in IMG (or a literal file under the factory dir). We still split big ones.+        [[ -f "$PLAN" ]] || { echo "plan not found: $PLAN" >&2; exit 1; }+        command -v jq >/dev/null || { echo "jq required to use -P plan.json" >&2; exit 1; }+        while IFS= read -r line; do+            action="$(jq -r '.action' <<<"$line")"+            case "$action" in+                flash)+                    part="$(jq -r '.partition' <<<"$line")"+                    key="$(jq -r '.image' <<<"$line")"+                    src="${IMG[$key]:-$WORK/$key}"+                    [[ -e "$src" ]] || src="$WORK/inner/$key"+                    [[ -e "$src" ]] || { echo "plan references missing image: $key" >&2; exit 1; }+                    append "$(stage_flash "$part" "$src")"+                    ;;+                *) append "$line" ;;+            esac+        done < <(jq -c '.[]' "$PLAN")+    else+        echo "   WARNING: no script.txt and no -P plan.json; generating a best-effort plan." >&2+        echo "            VERIFY against the device's real flash-all before trusting this." >&2+        [[ -n "${IMG[bootloader]:-}" ]] && { append "$(stage_flash bootloader "${IMG[bootloader]}")"; append '{"action":"reboot-bootloader"}'; }+        [[ -n "${IMG[radio]:-}" ]] && { append "$(stage_flash radio "${IMG[radio]}")"; append '{"action":"reboot-bootloader"}'; }+        for part in "${!IMG[@]}"; do+            case "$part" in bootloader|radio) continue ;; esac+            append "$(stage_flash "$part" "${IMG[$part]}")"+        done+        append '{"action":"erase","partition":"userdata"}'+        append '{"action":"reboot"}'+    fi++    cat > "$MANIFEST" <<EOF {   "device": "$DEVICE",   "build": "$BUILD",   "steps": [ $STEPS_JSON ] } EOF+fi+ echo ">> manifest: $MANIFEST" echo "   $(find "$STAGE" -type f | wc -l) file(s) staged in $STAGE" @@ -169,11 +205,13 @@ s3() { aws s3 --endpoint-url "$ENDPOINT" "$@"; }  # Images first (immutable), manifest last (uncacheable) so the installer never sees a # manifest pointing at a not-yet-uploaded image. Upload to the versioned path, then mirror-# to /latest/ which the installer reads by default.+# to /latest/ which the installer reads by default. Everything except manifest.json is an+# image (.img/.simg/.bin) and is content-addressed + immutable. for dest in "factory/$DEVICE/$BUILD" "factory/$DEVICE/latest"; do     echo ">> uploading images -> s3://$BUCKET/$dest/"-    for img in "$STAGE"/*.img "$STAGE"/*.simg; do+    for img in "$STAGE"/*; do         [[ -e "$img" ]] || continue+        [[ "$(basename "$img")" == "manifest.json" ]] && continue         s3 cp "$img" "s3://$BUCKET/$dest/$(basename "$img")" \             --content-type "application/octet-stream" \             --cache-control "public, max-age=31536000, immutable" --only-show-errors
installer/script_to_manifest.py
diff --git a/installer/script_to_manifest.py b/installer/script_to_manifest.pynew file mode 100644index 0000000..e7e938e--- /dev/null+++ b/installer/script_to_manifest.py@@ -0,0 +1,175 @@+#!/usr/bin/env python3+"""+script_to_manifest.py — translate a GrapheneOS install-zip `script.txt` into the ordered+flash plan the MAOS web installer consumes (manifest.json `steps`).++Why: the install zip (`<device>-install-<build>.zip`) already contains the whole `super`+pre-split into `super_1..N.img` (sized to the device max-download-size) AND `script.txt`,+GrapheneOS's *verified* flash sequence — it flashes `super` directly in bootloader mode+(no fastbootd), which is the lowest-brick-risk path. Rather than invent a plan, we translate+that script verbatim into installer steps so the browser flasher does exactly what+GrapheneOS's own tooling does, in the same order.++script.txt grammar (one command per line; blank lines and `#` comments ignored):++    check-var NAME VALUE            # or `check-var NAME:VALUE`+    flash PART FILE [other-slot]    # a 3rd token flashes to the inactive slot+    toggle-active-slot+    reboot-bootloader+    run-cmd CMD...                  # raw fastboot command (e.g. `set_active:a`, `oem uart disable`)+    erase PART+    maybe-cancel-snapshot-update+    check-requirements FILE         # android-info.txt with `require KEY=VAL[|VAL...]` lines+    reboot++Emitted manifest steps (see location_share_server/os_installer/installer.js for handlers):++    {"action":"check-var","name":NAME,"value":VALUE}+    {"action":"flash","partition":PART,"image":FILE[,"slot":"other"]}+    {"action":"toggle-active-slot"}+    {"action":"reboot-bootloader"}+    {"action":"run-cmd","command":CMD}+    {"action":"erase","partition":PART}+    {"action":"snapshot-update-cancel"}+    {"action":"check-requirements","requirements":[{"name":NAME,"values":[...]}, ...]}+    {"action":"reboot"}++Unknown commands are a hard error (fail loud rather than silently drop a step that could+matter for a safe flash).++USAGE:+    script_to_manifest.py --script script.txt --device DEVICE --build BUILD [--srcdir DIR]++Prints the full manifest JSON ({"device","build","steps":[...]}) to stdout. `check-requirements`+resolves its android-info file relative to --srcdir (defaults to the script's own directory).+"""+import argparse+import json+import os+import sys+++def parse_android_info(path):+    """Parse `require KEY=VAL[|VAL...]` lines from an android-info.txt into a list of+    {"name": KEY, "values": [VAL, ...]} requirement objects."""+    reqs = []+    with open(path, "r", encoding="utf-8", errors="replace") as f:+        for raw in f:+            line = raw.strip()+            if not line or line.startswith("#"):+                continue+            if not line.startswith("require "):+                continue+            body = line[len("require "):].strip()+            if "=" not in body:+                continue+            name, _, value = body.partition("=")+            name = name.strip()+            values = [v.strip() for v in value.split("|") if v.strip()]+            if name:+                reqs.append({"name": name, "values": values})+    return reqs+++def translate(script_path, srcdir):+    steps = []+    with open(script_path, "r", encoding="utf-8", errors="replace") as f:+        for lineno, raw in enumerate(f, 1):+            line = raw.strip()+            if not line or line.startswith("#"):+                continue+            toks = line.split()+            cmd = toks[0]++            if cmd == "check-var":+                # `check-var NAME VALUE` or `check-var NAME:VALUE`+                if len(toks) >= 3:+                    name, value = toks[1], toks[2]+                elif len(toks) == 2 and ":" in toks[1]:+                    name, value = toks[1].split(":", 1)+                else:+                    raise ValueError(f"line {lineno}: malformed check-var: {line!r}")+                steps.append({"action": "check-var", "name": name, "value": value})++            elif cmd == "flash":+                if len(toks) < 3:+                    raise ValueError(f"line {lineno}: malformed flash: {line!r}")+                step = {"action": "flash", "partition": toks[1], "image": toks[2]}+                # Any trailing token (e.g. `other-slot`) => flash to the inactive slot.+                if len(toks) >= 4:+                    step["slot"] = "other"+                steps.append(step)++            elif cmd == "toggle-active-slot":+                steps.append({"action": "toggle-active-slot"})++            elif cmd == "reboot-bootloader":+                steps.append({"action": "reboot-bootloader"})++            elif cmd == "run-cmd":+                if len(toks) < 2:+                    raise ValueError(f"line {lineno}: run-cmd needs a command: {line!r}")+                steps.append({"action": "run-cmd", "command": " ".join(toks[1:])})++            elif cmd == "erase":+                if len(toks) < 2:+                    raise ValueError(f"line {lineno}: erase needs a partition: {line!r}")+                steps.append({"action": "erase", "partition": toks[1]})++            elif cmd == "maybe-cancel-snapshot-update":+                steps.append({"action": "snapshot-update-cancel"})++            elif cmd == "check-requirements":+                if len(toks) < 2:+                    raise ValueError(f"line {lineno}: check-requirements needs a file: {line!r}")+                info = toks[1]+                if not os.path.isabs(info):+                    info = os.path.join(srcdir, info)+                if not os.path.isfile(info):+                    raise FileNotFoundError(+                        f"line {lineno}: check-requirements file not found: {info}"+                    )+                steps.append(+                    {"action": "check-requirements", "requirements": parse_android_info(info)}+                )++            elif cmd == "reboot":+                steps.append({"action": "reboot"})++            else:+                raise ValueError(+                    f"line {lineno}: unknown script.txt command {cmd!r}. Extend "+                    f"script_to_manifest.py (and installer.js) before publishing: {line!r}"+                )++    if not steps:+        raise ValueError("script.txt produced no steps")+    return steps+++def main():+    ap = argparse.ArgumentParser()+    ap.add_argument("--script", required=True, help="path to the install zip's script.txt")+    ap.add_argument("--device", required=True)+    ap.add_argument("--build", required=True)+    ap.add_argument(+        "--srcdir",+        default=None,+        help="dir to resolve check-requirements files against (default: script's dir)",+    )+    args = ap.parse_args()++    srcdir = args.srcdir or os.path.dirname(os.path.abspath(args.script))+    try:+        steps = translate(args.script, srcdir)+    except Exception as e:  # noqa: BLE001 - surface a clear message and fail+        print(f"script_to_manifest: {e}", file=sys.stderr)+        sys.exit(1)++    manifest = {"device": args.device, "build": args.build, "steps": steps}+    json.dump(manifest, sys.stdout, indent=2)+    sys.stdout.write("\n")+++if __name__ == "__main__":+    main()