diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml
index 30518bde0b..22234d2f76 100644
--- a/.github/workflows/docs.yaml
+++ b/.github/workflows/docs.yaml
@@ -7,6 +7,9 @@ on:
- Domathon
- Dom
- StarPilot
+ - stable
+ - testing
+ - dev
pull_request:
workflow_call:
inputs:
diff --git a/.github/workflows/flm-offroad.yaml b/.github/workflows/flm-offroad.yaml
index 1ce8035dd3..545238707d 100644
--- a/.github/workflows/flm-offroad.yaml
+++ b/.github/workflows/flm-offroad.yaml
@@ -2,7 +2,7 @@ name: FLM offroad contracts
on:
push:
- branches: [Dom, StarPilot]
+ branches: [Dom, StarPilot, stable, testing, dev]
paths:
- 'openpilot/starpilot/flm/**'
- 'openpilot/starpilot/lateral/**'
diff --git a/.github/workflows/galaxy-phone-bridge.yaml b/.github/workflows/galaxy-phone-bridge.yaml
index 843c5034c3..cfbbcaa4d8 100644
--- a/.github/workflows/galaxy-phone-bridge.yaml
+++ b/.github/workflows/galaxy-phone-bridge.yaml
@@ -2,7 +2,7 @@ name: Galaxy phone bridge
on:
push:
- branches: [Dom, StarPilot, secretgood-ios-integration]
+ branches: [Dom, StarPilot, stable, testing, dev, secretgood-ios-integration]
paths:
- 'openpilot/starpilot/galaxy_bluetooth/**'
- '.github/workflows/galaxy-phone-bridge.yaml'
diff --git a/.github/workflows/safety.yaml b/.github/workflows/safety.yaml
index f048fd39c0..f6988c1222 100644
--- a/.github/workflows/safety.yaml
+++ b/.github/workflows/safety.yaml
@@ -2,7 +2,7 @@ name: safety qualification
on:
push:
- branches: [master, Domathon, Dom, StarPilot]
+ branches: [master, Domathon, Dom, StarPilot, stable, testing, dev]
pull_request:
workflow_dispatch:
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml
index e5d22b94da..b06330189e 100644
--- a/.github/workflows/tests.yaml
+++ b/.github/workflows/tests.yaml
@@ -7,6 +7,9 @@ on:
- Domathon
- Dom
- StarPilot
+ - stable
+ - testing
+ - dev
pull_request:
workflow_dispatch:
workflow_call:
@@ -36,12 +39,14 @@ jobs:
steps:
- uses: actions/checkout@v7
- name: Validate published device build receipt
- if: github.event_name == 'push' && (github.ref == 'refs/heads/Dom' || github.ref == 'refs/heads/StarPilot')
+ if: github.event_name == 'push' && (github.ref == 'refs/heads/Dom' || github.ref == 'refs/heads/StarPilot' || github.ref == 'refs/heads/stable' || github.ref == 'refs/heads/testing' || github.ref == 'refs/heads/dev')
run: python3 tools/ci/check_prebuilt_receipt.py --revision HEAD
- name: Check shipped device runtime dependencies
run: |
python3 -m unittest tools.laptop_device_build.tests.test_runtime_dependencies -v
python3 -c 'from pathlib import Path; assert b"starting pandad (comma hardware)" in Path("openpilot/selfdrive/pandad/pandad").read_bytes(), "Shipped pandad must use the comma hardware build profile"'
+ - name: Test one-shot branch migration
+ run: python3 -m unittest discover -s scripts/tests -v
- name: Validate tracked dependencies
run: python3 tools/vendor/check.py --revision HEAD
- run: ./tools/op.sh setup
diff --git a/README.md b/README.md
index 2fe1cfa739..0fa5cb2654 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
[](https://deepwiki.com/StarPilotHQ/StarPilot)
[](https://firestar.link/discord)
-[](https://github.com/StarPilotHQ/StarPilot)
+[](https://github.com/StarPilotHQ/StarPilot)
[](https://wiki.firestar.link)
[](https://firestar.link/ios)
[](https://firestar.link/android)
@@ -11,7 +11,7 @@
**StarPilot** is a custom fork of [comma.ai's openpilot](https://comma.ai/openpilot),
an open source driver assistance system.
-**This is the StarPilot 7.0 development branch (`Dom`). Feature migration,
+**This is the StarPilot 7.0 testing channel (`testing`, formerly `Dom`). Feature migration,
vehicle qualification, and Auto Learn validation are still in progress.**
Openpilot provides
diff --git a/launch_chffrplus.sh b/launch_chffrplus.sh
index c6606c2ebe..f4c32c65b9 100755
--- a/launch_chffrplus.sh
+++ b/launch_chffrplus.sh
@@ -73,11 +73,16 @@ function update_is_ready {
# every boot before swapping trees, including manual reboots.
# Keep this in sync with TRUSTED_LEGACY_RELEASES in updated.py.
TRUSTED_LEGACY_STARPILOT_COMMIT="c2e5e469ee8fefc3cffb514dc2e1a1fb82a421d6"
+TRUSTED_LEGACY_STABLE_MIGRATION="0758072c767719dd63d133f78c6738b90505cb4e"
+
+function trusted_legacy_commit {
+ [ "$1" = "$TRUSTED_LEGACY_STARPILOT_COMMIT" ] || [ "$1" = "$TRUSTED_LEGACY_STABLE_MIGRATION" ]
+}
function staged_os_is_compatible {
local staged="$1" marker="$1/.git/starpilot-retain-agnos" commit
commit="$(git -C "$staged" rev-parse --verify 'HEAD^{commit}')" || return 1
- if [ "$commit" = "$TRUSTED_LEGACY_STARPILOT_COMMIT" ]; then
+ if trusted_legacy_commit "$commit"; then
[ -f "$marker" ] && [ -s "$marker" ] && [ ! -L "$marker" ] && [ -r /VERSION ] && [ "$(cat "$marker")" = "$(< /VERSION)" ]
else
[ ! -e "$marker" ] && [ ! -L "$marker" ]
@@ -91,7 +96,7 @@ function reset_update_os_environment {
function maybe_activate_legacy_agnos {
local repo="$1" verifier="$2" manifest="$3" commit
commit="$(git -C "$repo" rev-parse --verify 'HEAD^{commit}')" || return 1
- if [ "$commit" != "$TRUSTED_LEGACY_STARPILOT_COMMIT" ] && [ ! -L "$manifest" ]; then
+ if ! trusted_legacy_commit "$commit" && [ ! -L "$manifest" ]; then
"$verifier" --verify "$manifest" && sudo reboot
fi
}
diff --git a/openpilot/starpilot/galaxy/tests/test_software_status.mjs b/openpilot/starpilot/galaxy/tests/test_software_status.mjs
index f9a73ee2a0..b20951564a 100644
--- a/openpilot/starpilot/galaxy/tests/test_software_status.mjs
+++ b/openpilot/starpilot/galaxy/tests/test_software_status.mjs
@@ -332,8 +332,10 @@ const switchPage = {...staged, operations: {...staged.operations, canFastUpdate:
SoftwarePage.methods.askUpdate.call(switchPage)
assert.equal(switchPage.dialog.action, 'update')
assert.equal(switchPage.dialog.branch, 'beta')
-assert.equal(SoftwarePage.methods.branchLabel('StarPilot'), 'Stable — StarPilot')
-assert.equal(SoftwarePage.methods.branchLabel('Dom'), 'Development — Dom')
+assert.equal(SoftwarePage.methods.branchLabel('StarPilot'), 'Stable — StarPilot (legacy name)')
+assert.equal(SoftwarePage.methods.branchLabel('Dom'), 'Testing — Dom (legacy name)')
+assert.equal(SoftwarePage.methods.branchLabel('stable'), 'Stable')
+assert.equal(SoftwarePage.methods.branchLabel('testing'), 'Testing')
assert.deepEqual(page('Dom', ['Dom', 'other:']).branchOptions.map(branch=>branch.name), ['Dom'])
assert.match(SoftwarePage.template, /aria-label="Version branch"/)
assert.match(SoftwarePage.template, /@change="changeBranch"/)
@@ -737,22 +739,26 @@ updateView.data.updater.targetChangeFound = false
assert.equal(updateView.updateBanner.message, 'No Update Available')
assert.equal(SoftwarePage.methods.requestMessage(request('versions', 'complete')), '')
-const branchLayout = page()
+const branchLayout = page('testing', ['testing', 'stable', 'beta'], 'testing')
branchLayout.changeBranch = SoftwarePage.methods.changeBranch.bind(branchLayout)
-SoftwarePage.methods.syncDraftBranch.call(branchLayout, 'Dom')
-assert.equal(branchLayout.primaryChoice, 'Dom')
+SoftwarePage.methods.syncDraftBranch.call(branchLayout, 'testing')
+assert.equal(branchLayout.primaryChoice, 'testing')
branchLayout.primaryChoice = 'other:'
await SoftwarePage.methods.onPrimaryBranchChange.call(branchLayout)
assert.equal(branchLayout.draftBranch, '')
assert.deepEqual(branchLayout.calls, [], 'opening Other does not refresh metadata without a branch')
assert.deepEqual(branchLayout.otherBranches.map(branch => branch.name), ['beta'])
+const legacyChannels = page('Dom', ['Dom', 'StarPilot', 'dev', 'testing', 'stable'])
+SoftwarePage.methods.syncDraftBranch.call(legacyChannels, 'Dom')
+assert.equal(legacyChannels.primaryChoice, 'other:')
+assert.deepEqual(legacyChannels.otherBranches.map(branch => branch.name), ['Dom', 'StarPilot', 'dev'])
branchLayout.draftBranch = 'beta'
await branchLayout.changeBranch()
assert.deepEqual(branchLayout.calls, ['beta'])
-branchLayout.primaryChoice = 'StarPilot'
+branchLayout.primaryChoice = 'stable'
await SoftwarePage.methods.onPrimaryBranchChange.call(branchLayout)
-assert.equal(branchLayout.draftBranch, 'StarPilot')
-assert.deepEqual(branchLayout.calls, ['beta', 'StarPilot'])
+assert.equal(branchLayout.draftBranch, 'stable')
+assert.deepEqual(branchLayout.calls, ['beta', 'stable'])
assert.equal(previousSelection.primaryChoice, 'other:', 'previous selection synchronizes both selectors without refreshing')
assert.doesNotMatch(SoftwarePage.template, /Refresh versions/)
diff --git a/openpilot/starpilot/galaxy/web/js/models.js b/openpilot/starpilot/galaxy/web/js/models.js
index 3544c57793..a2e89d0f56 100644
--- a/openpilot/starpilot/galaxy/web/js/models.js
+++ b/openpilot/starpilot/galaxy/web/js/models.js
@@ -1008,7 +1008,7 @@ export const ModelsPage = {
Set up parked with a USB 3 data cable and separate power. Keep the computer awake; keep the iPhone app open and unlocked.
-
+
diff --git a/openpilot/starpilot/galaxy/web/js/software-status.js b/openpilot/starpilot/galaxy/web/js/software-status.js
index 894255871b..426b348b74 100644
--- a/openpilot/starpilot/galaxy/web/js/software-status.js
+++ b/openpilot/starpilot/galaxy/web/js/software-status.js
@@ -10,8 +10,10 @@ import { RouteCleanup } from "./route-cleanup.js"
const ACTIONS = new Set(["check", "download", "select", "install", "preferences", "install-preferences", "update", "fast", "rollback", "versions", "version", "download-version"])
const REQUEST_STATES = new Set(["pending", "complete", "failed"])
const UPDATER_ACTIVE = new Set(["checking...", "downloading...", "finalizing update...", "updating..."])
-const PRIMARY_BRANCH_LABELS = { StarPilot: "Stable — StarPilot", Dom: "Development — Dom" }
+const PRIMARY_BRANCH_LABELS = { stable: "Stable", testing: "Testing", StarPilot: "Stable — StarPilot (legacy name)", Dom: "Testing — Dom (legacy name)" }
const PRIMARY_BRANCH_HELP = {
+ stable: "Stable releases. Recommended for most users.",
+ testing: "Latest features and fixes for testing. May introduce bugs.",
StarPilot: "Stable releases. Recommended for most users.",
Dom: "Latest features and fixes under development. Updates regularly and may introduce bugs.",
}
@@ -459,7 +461,7 @@ export const SoftwarePage = {
return [...new Set([this.operations?.selectedTarget, this.data?.installed.branch, this.previousVersion?.branch, ...available].filter(branch => branch && branch !== "other:"))]
.map(name => ({ name, available: available.includes(name) || name === this.data?.installed.branch }))
},
- otherBranches() { return this.branchOptions.filter(branch => !['StarPilot', 'Dom'].includes(branch.name)) },
+ otherBranches() { return this.branchOptions.filter(branch => !['stable', 'testing'].includes(branch.name)) },
hasInstalledVersion() {
const recent = this.operations?.history?.recent
return this.draftBranch === this.data?.installed.branch ||
@@ -571,19 +573,19 @@ export const SoftwarePage = {
},
syncDraftBranch(branch) {
this.draftBranch = branch || this.data?.installed.branch || ""
- this.primaryChoice = ['StarPilot', 'Dom'].includes(this.draftBranch) ? this.draftBranch : this.draftBranch ? 'other:' : ''
+ this.primaryChoice = ['stable', 'testing'].includes(this.draftBranch) ? this.draftBranch : this.draftBranch ? 'other:' : ''
},
onPrimaryBranchChange() {
this.draftTouched = true
if (this.primaryChoice === 'other:') {
- if (['StarPilot', 'Dom'].includes(this.draftBranch)) this.draftBranch = ''
+ if (['stable', 'testing'].includes(this.draftBranch)) this.draftBranch = ''
return
}
this.draftBranch = this.primaryChoice
return this.changeBranch()
},
async changeBranch() {
- this.primaryChoice = ['StarPilot', 'Dom'].includes(this.draftBranch) ? this.draftBranch : 'other:'
+ this.primaryChoice = ['stable', 'testing'].includes(this.draftBranch) ? this.draftBranch : 'other:'
this.draftTouched = true
this.version = ""
this.newerVersionLimit = 2; this.olderVersionLimit = 1; this.collapsedOlderLimit = 0
@@ -726,8 +728,8 @@ export const SoftwarePage = {
diff --git a/openpilot/starpilot/software/fast_update.py b/openpilot/starpilot/software/fast_update.py
index 56cc2f8d51..f3ff675950 100644
--- a/openpilot/starpilot/software/fast_update.py
+++ b/openpilot/starpilot/software/fast_update.py
@@ -40,8 +40,8 @@ def legacy_os_compatible(launch, current_os):
def validate_legacy_return(git, revision, branch):
- if branch not in ('Dom', 'StarPilot'):
- raise FastUpdateIncompatible('Legacy return is only available for Dom and StarPilot 6.x releases')
+ if branch not in ('Dom', 'StarPilot', 'stable', 'testing'):
+ raise FastUpdateIncompatible('Legacy return is only available for supported StarPilot 6.x channels')
entries = {}
for row in git('ls-tree', '-rz', '--full-tree', revision).split('\0'):
if row:
@@ -241,7 +241,7 @@ def fast_update(repo, branch, *, params, parked, expected_commit, current_os=Non
notify('complete', 'Recent versions are ready to review.')
return 'versions-listed'
notify('validating', 'Checking downloaded operating system and native artifacts...')
- legacy_return = branch in ('Dom', 'StarPilot') and not git('ls-tree', target, '--', 'upstream-sync.json').strip()
+ legacy_return = branch in ('Dom', 'StarPilot', 'stable', 'testing') and not git('ls-tree', target, '--', 'upstream-sync.json').strip()
if legacy_return:
version = validate_legacy_return(git, target, branch)
notify('validating', f'Returning to {branch} {version}; checking the legacy prebuilt release...')
diff --git a/openpilot/starpilot/software/tests/test_fast_update.py b/openpilot/starpilot/software/tests/test_fast_update.py
index d1b27b28ba..0d60f53925 100644
--- a/openpilot/starpilot/software/tests/test_fast_update.py
+++ b/openpilot/starpilot/software/tests/test_fast_update.py
@@ -98,12 +98,13 @@ class TestFastUpdate(unittest.TestCase):
self.git(self.remote, 'branch', branch)
return self.target
- def test_legacy_dom_and_starpilot_return_without_manifest_or_build_receipt(self):
- for branch in ('Dom', 'StarPilot'):
+ def test_legacy_channels_return_without_manifest_or_build_receipt(self):
+ for branch in ('Dom', 'StarPilot', 'stable', 'testing'):
with self.subTest(branch=branch):
if branch == 'Dom':
self.legacy_release()
- self.git(self.remote, 'branch', 'StarPilot')
+ for alias in ('StarPilot', 'stable', 'testing'):
+ self.git(self.remote, 'branch', alias)
else:
self.git(self.repo, 'checkout', '-B', 'SecretGoodStarPilot', self.previous)
model = self.repo / 'downloaded-model'
diff --git a/openpilot/starpilot/ui/home.py b/openpilot/starpilot/ui/home.py
index e3b2f5450f..e9091419d7 100644
--- a/openpilot/starpilot/ui/home.py
+++ b/openpilot/starpilot/ui/home.py
@@ -115,9 +115,9 @@ class HomeView:
self._sidebar(state)
header = rl.Rectangle(340, 40, 1780, 80)
description = state.description
- if state.branch == "StarPilot":
+ if state.branch in ("StarPilot", "stable"):
parts = description.split(" / ")
- if len(parts) > 1 and parts[1] == "StarPilot":
+ if len(parts) > 1 and parts[1] in ("StarPilot", "stable"):
parts[1] = "Stable"
description = " / ".join(parts)
detail = (" " + description if description else "") + (" - " + state.model_label if state.model_label else "")
@@ -231,7 +231,7 @@ class HomeView:
def _compact(self, state: HomeState):
white = rl.Color(255, 255, 255, 229)
self._text("StarPilot", FontRole.BRAND, 64, 6, 8, white)
- branch_label = "Stable" if state.branch == "StarPilot" else state.branch
+ branch_label = "Stable" if state.branch in ("StarPilot", "stable") else state.branch
version_branch = f"{state.version} {branch_label}".strip()
date_width = self._measure(state.commit_date, FontRole.ROMAN, 30).width if state.commit_date else 0
version_width = 520 - date_width - 16 if state.commit_date else 520
diff --git a/openpilot/system/updated/tests/test_retained_agnos.py b/openpilot/system/updated/tests/test_retained_agnos.py
index d99d51f05f..a203dd54a5 100644
--- a/openpilot/system/updated/tests/test_retained_agnos.py
+++ b/openpilot/system/updated/tests/test_retained_agnos.py
@@ -143,8 +143,10 @@ class TestRetainedAgnos(unittest.TestCase):
marker = repo / '.git/starpilot-retain-agnos'
launcher = ROOT / 'launch_chffrplus.sh'
text = launcher.read_text()
- audited = next(iter(load_updater().TRUSTED_LEGACY_RELEASES['StarPilot']))
- self.assertIn(f'TRUSTED_LEGACY_STARPILOT_COMMIT="{audited}"', text)
+ audited = load_updater().TRUSTED_LEGACY_RELEASES
+ declared = set(re.findall(r'TRUSTED_LEGACY_(?:STARPILOT_COMMIT|STABLE_MIGRATION)="([0-9a-f]{40})"', text))
+ self.assertEqual(declared, set().union(*audited.values()))
+ trusted = shell_function(launcher, 'trusted_legacy_commit')
check = shell_function(launcher, 'staged_os_is_compatible').replace('/VERSION', str(version))
activate = shell_function(launcher, 'maybe_activate_legacy_agnos')
verifier = self.root / 'verifier'
@@ -153,7 +155,7 @@ class TestRetainedAgnos(unittest.TestCase):
verifier.chmod(0o755)
manifest = self.root / 'agnos.json'
manifest.write_text('[]')
- common = f'TRUSTED_LEGACY_STARPILOT_COMMIT={commit}\n{check}\n{activate}\n'
+ common = f'TRUSTED_LEGACY_STARPILOT_COMMIT={commit}\nTRUSTED_LEGACY_STABLE_MIGRATION=other-migration\n{trusted}\n{check}\n{activate}\n'
def admission():
return subprocess.run(['bash', '-c', common + f'staged_os_is_compatible {shlex.quote(str(repo))}'], check=False).returncode
self.assertNotEqual(admission(), 0) # Missing marker is not a modern update.
@@ -165,6 +167,12 @@ class TestRetainedAgnos(unittest.TestCase):
marker.unlink()
marker.write_text('20.2.1\n')
self.assertEqual(admission(), 0)
+ migration_common = common.replace(f'TRUSTED_LEGACY_STARPILOT_COMMIT={commit}', 'TRUSTED_LEGACY_STARPILOT_COMMIT=other')
+ migration_common = migration_common.replace('TRUSTED_LEGACY_STABLE_MIGRATION=other-migration', f'TRUSTED_LEGACY_STABLE_MIGRATION={commit}')
+ self.assertEqual(subprocess.run(['bash', '-c', migration_common + f'staged_os_is_compatible {shlex.quote(str(repo))}']).returncode, 0)
+ marker.write_text('wrong\n')
+ self.assertNotEqual(subprocess.run(['bash', '-c', migration_common + f'staged_os_is_compatible {shlex.quote(str(repo))}']).returncode, 0)
+ marker.write_text('20.2.1\n')
version.write_text('changed\n')
self.assertNotEqual(admission(), 0) # Manual reboot must recheck the OS.
shell = common + f'sudo() {{ echo reboot >> {shlex.quote(str(log))}; }}\n' + \
diff --git a/openpilot/system/updated/tests/test_vendored_update.py b/openpilot/system/updated/tests/test_vendored_update.py
index 64a82d4e61..787dc79e07 100644
--- a/openpilot/system/updated/tests/test_vendored_update.py
+++ b/openpilot/system/updated/tests/test_vendored_update.py
@@ -301,7 +301,10 @@ class TestVendoredUpdate(unittest.TestCase):
with self.assertRaises(ValueError):
self.updated.validate_update_revision(str(self.source), target, 'StarPilot')
audited = load_updater().TRUSTED_LEGACY_RELEASES
- self.assertEqual(audited, {'StarPilot': frozenset({'c2e5e469ee8fefc3cffb514dc2e1a1fb82a421d6'})})
+ self.assertEqual(audited, {
+ 'StarPilot': frozenset({'c2e5e469ee8fefc3cffb514dc2e1a1fb82a421d6', '0758072c767719dd63d133f78c6738b90505cb4e'}),
+ 'stable': frozenset({'0758072c767719dd63d133f78c6738b90505cb4e'}),
+ })
def test_reserved_readiness_marker_rejected_in_modern_and_legacy_trees(self):
for kind in ('modern-file', 'modern-symlink', 'legacy-file', 'legacy-symlink'):
diff --git a/openpilot/system/updated/updated.py b/openpilot/system/updated/updated.py
index 602cd33f56..a6956575a9 100755
--- a/openpilot/system/updated/updated.py
+++ b/openpilot/system/updated/updated.py
@@ -265,7 +265,10 @@ def init_overlay() -> None:
# Audited legacy release, pinned by Git commit identity. Other releases must
# satisfy the modern source manifest contract.
-TRUSTED_LEGACY_RELEASES = {'StarPilot': frozenset({'c2e5e469ee8fefc3cffb514dc2e1a1fb82a421d6'})}
+TRUSTED_LEGACY_RELEASES = {
+ 'StarPilot': frozenset({'c2e5e469ee8fefc3cffb514dc2e1a1fb82a421d6', '0758072c767719dd63d133f78c6738b90505cb4e'}),
+ 'stable': frozenset({'0758072c767719dd63d133f78c6738b90505cb4e'}),
+}
LEGACY_OS_MARKER = '.git/starpilot-retain-agnos'
diff --git a/prebuilt.json b/prebuilt.json
index e109796b00..e34063e07d 100644
--- a/prebuilt.json
+++ b/prebuilt.json
@@ -1 +1 @@
-{"protected_inventory_sha256": "9aa41f1769606afd13d7124044e67d244b9385c856923732cddea45d5752efe5", "schema_version": 1}
+{"protected_inventory_sha256": "2e37282639b9825fd60b64af4dd82ab5eea9290ba7f0706bb64e1988543c6c51", "schema_version": 1}
diff --git a/scripts/branch_migration.py b/scripts/branch_migration.py
new file mode 100644
index 0000000000..bb75a14af2
--- /dev/null
+++ b/scripts/branch_migration.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""Offline, commit-bound channel migration; never checks out or downloads code."""
+import argparse
+import fcntl
+import json
+import os
+from pathlib import Path
+import re
+import stat
+import subprocess
+import tempfile
+
+
+PLAN = 'scripts/branch-migration.json'
+
+
+def git(repo, *args):
+ return subprocess.check_output(['git', '--no-optional-locks', '-c', 'gc.auto=0', '-c',
+ 'maintenance.auto=false', '-C', str(repo), *args],
+ text=True, timeout=15).strip()
+
+
+def atomic_json(path, value):
+ atomic_write(path, json.dumps(value, sort_keys=True).encode() + b'\n')
+
+
+def atomic_write(path, value):
+ fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
+ try:
+ os.fchmod(fd, stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644)
+ with os.fdopen(fd, 'wb') as stream:
+ stream.write(value)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ directory = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def migrate(repo, params, checkpoint=lambda step: None):
+ repo, params = Path(repo).resolve(), Path(params)
+ plan_path = repo / PLAN
+ if not plan_path.is_file() or plan_path.is_symlink():
+ return 'no plan'
+ plan = json.loads(plan_path.read_text())
+ if (type(plan) is not dict or set(plan) != {'source', 'destination', 'parent', 'token'} or
+ any(type(value) is not str for value in plan.values()) or
+ (plan['source'], plan['destination']) not in (('Dom', 'testing'), ('StarPilot', 'stable')) or
+ not re.fullmatch('[0-9a-f]{40}', plan['parent']) or not re.fullmatch('[0-9a-f]{32}', plan['token'])):
+ raise ValueError('Invalid channel migration plan')
+ head = git(repo, 'rev-parse', '--verify', 'HEAD')
+ raw = git(repo, 'cat-file', 'commit', head)
+ headers, message = raw.split('\n\n', 1)
+ parents = [line[7:] for line in headers.splitlines() if line.startswith('parent ')]
+ title = f"Branch-Migration: {plan['source']} -> {plan['destination']} ({plan['token']})"
+ if parents != [plan['parent']] or message != title:
+ return 'not migration release'
+ gitdir = Path(git(repo, 'rev-parse', '--absolute-git-dir'))
+ with (gitdir / 'starpilot-branch-migration.lock').open('a') as lease:
+ try:
+ fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ return 'migration busy'
+ completed = gitdir / ('starpilot-branch-migration-' + plan['token'] + '.done')
+ pending = gitdir / 'starpilot-branch-migration.pending'
+ record = {**plan, 'commit': head}
+ if completed.exists():
+ if completed.is_symlink() or json.loads(completed.read_text()) != record:
+ raise ValueError('Migration completion does not match release')
+ if pending.exists() and not pending.is_symlink() and json.loads(pending.read_text()) == record:
+ pending.unlink()
+ return 'already migrated'
+ if pending.exists() and (pending.is_symlink() or json.loads(pending.read_text()) != record):
+ raise ValueError('Another migration is pending')
+ branch = git(repo, 'symbolic-ref', '--short', 'HEAD')
+ if branch != plan['source'] and not (pending.exists() and branch == plan['destination']):
+ return 'manual branch selection'
+ target = params / 'UpdaterTargetBranch'
+ saved = target.read_bytes() if target.exists() else b''
+ if saved not in (b'', plan['source'].encode(), plan['destination'].encode()):
+ return 'manual updater selection'
+ if not params.is_dir() or target.is_symlink():
+ raise ValueError('Updater Params directory is unavailable or unsafe')
+ destination = 'refs/heads/' + plan['destination']
+ existing = subprocess.run(['git', '-C', str(repo), 'rev-parse', '--verify', '--quiet', destination],
+ text=True, capture_output=True, timeout=15)
+ if existing.returncode not in (0, 1):
+ raise ValueError('Cannot inspect destination ref')
+ if existing.returncode == 0 and existing.stdout.strip() != head:
+ raise ValueError('Destination local branch already contains different work')
+ atomic_json(pending, record)
+ checkpoint('pending')
+ if existing.returncode == 1:
+ git(repo, 'update-ref', destination, head, '0' * 40)
+ checkpoint('destination')
+ git(repo, 'symbolic-ref', 'HEAD', destination)
+ checkpoint('head')
+ git(repo, 'config', 'branch.' + plan['destination'] + '.remote', 'origin')
+ checkpoint('remote')
+ git(repo, 'config', 'branch.' + plan['destination'] + '.merge', destination)
+ checkpoint('upstream')
+ fetch = subprocess.run(['git', '-C', str(repo), 'config', '--get-all', 'remote.origin.fetch'],
+ text=True, capture_output=True, timeout=15)
+ if fetch.returncode not in (0, 1):
+ raise ValueError('Cannot inspect origin fetch configuration')
+ refspec = '+' + destination + ':refs/remotes/origin/' + plan['destination']
+ if refspec not in fetch.stdout.splitlines() and '+refs/heads/*:refs/remotes/origin/*' not in fetch.stdout.splitlines():
+ git(repo, 'config', '--add', 'remote.origin.fetch', refspec)
+ checkpoint('fetch')
+ if (target.read_bytes() if target.exists() else b'') != saved:
+ raise ValueError('Updater selection changed during migration')
+ atomic_write(target, plan['destination'].encode())
+ checkpoint('params')
+ atomic_json(completed, record)
+ checkpoint('completed')
+ pending.unlink()
+ return 'migrated to ' + plan['destination']
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--repo', type=Path, default=Path(__file__).resolve().parents[1])
+ parser.add_argument('--params', type=Path, default=Path('/data/params/d'))
+ args = parser.parse_args()
+ try:
+ print(migrate(args.repo, args.params))
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ parser.exit(1, f'Channel migration deferred: {error}\n')
diff --git a/scripts/create_branch_migration.py b/scripts/create_branch_migration.py
new file mode 100644
index 0000000000..194995bd1d
--- /dev/null
+++ b/scripts/create_branch_migration.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Prepare a pinned, title-only migration commit in a local review ref; never push."""
+import argparse
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import uuid
+
+
+HOOK = '''
+if [ -f "$DIR/scripts/branch-migration.json" ]; then
+ python3 "$DIR/scripts/branch_migration.py" --repo "$DIR" || echo "Branch migration deferred; keeping installed software."
+fi
+'''
+
+
+def prepare(repo, source, destination, base, review_ref, token=None):
+ repo = Path(repo).resolve()
+ if (source, destination) not in (('Dom', 'testing'), ('StarPilot', 'stable')):
+ raise ValueError('Only Dom -> testing and StarPilot -> stable are supported')
+ token = token or uuid.uuid4().hex
+ with tempfile.TemporaryDirectory(prefix='branch-migration-index-') as temporary:
+ env = dict(os.environ, GIT_INDEX_FILE=str(Path(temporary) / 'index'))
+
+ def git(*args, data=None):
+ return subprocess.check_output(['git', '--no-optional-locks', '-c', 'gc.auto=0', '-c',
+ 'maintenance.auto=false', '-C', str(repo), *args],
+ input=data, env=env, timeout=30).decode().strip()
+
+ git('check-ref-format', review_ref)
+ if not review_ref.startswith('refs/heads/review/'):
+ raise ValueError('Use a new local refs/heads/review/ ref')
+ parent = git('rev-parse', '--verify', base + '^{commit}')
+ if source == 'StarPilot':
+ version = git('show', parent + ':selfdrive/ui/lib/starpilot_version.py')
+ if not re.search(r'^STARPILOT_DISPLAY_VERSION = [\"\']6\.\d+\.\d+[\"\']$', version, re.MULTILINE):
+ raise ValueError('The stable bridge must preserve a reviewed StarPilot 6.x release')
+ elif not git('ls-tree', parent, '--', 'prebuilt.json'):
+ raise ValueError('The testing bridge requires the reviewed rebase build receipt')
+ if git('ls-tree', parent, '--', 'prebuilt').split()[:1] != ['100644']:
+ raise ValueError('The source must be a precompiled release')
+ git('read-tree', parent)
+ launch = git('show', parent + ':launch_chffrplus.sh') + '\n'
+ anchor = 'source "$DIR/launch_env.sh"\n'
+ if launch.count(anchor) != 1 or 'scripts/branch-migration.json' in launch:
+ raise ValueError('Review the source launcher before creating its migration')
+ files = {
+ 'launch_chffrplus.sh': ('100755', launch.replace(anchor, anchor + HOOK)),
+ 'scripts/branch_migration.py': ('100644', Path(__file__).with_name('branch_migration.py').read_text()),
+ 'scripts/branch-migration.json': ('100644', json.dumps({
+ 'source': source, 'destination': destination, 'parent': parent, 'token': token,
+ }, sort_keys=True) + '\n'),
+ }
+ for name, (mode, content) in files.items():
+ blob = git('hash-object', '-w', '--stdin', data=content.encode())
+ git('update-index', '--add', '--cacheinfo', mode + ',' + blob + ',' + name)
+ tree = git('write-tree', '--missing-ok')
+ if git('ls-tree', parent, '--', 'prebuilt.json'):
+ # Use the canonical inventory rules, including modes and exact Git blobs.
+ spec = importlib.util.spec_from_file_location('canonical_receipt', Path(__file__).parents[1] / 'openpilot/common/prebuilt_manifest.py')
+ canonical = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(canonical)
+ if not canonical.valid_receipt(git, parent):
+ raise ValueError('Source release has no valid canonical receipt')
+ receipt = {'schema_version': 1, 'protected_inventory_sha256': canonical.revision_digest(git, tree)}
+ blob = git('hash-object', '-w', '--stdin', data=(json.dumps(receipt, sort_keys=True) + '\n').encode())
+ git('update-index', '--add', '--cacheinfo', '100644,' + blob + ',prebuilt.json')
+ tree = git('write-tree', '--missing-ok')
+ title = f'Branch-Migration: {source} -> {destination} ({token})'
+ commit = git('commit-tree', tree, '-p', parent, data=(title + '\n').encode())
+ git('update-ref', review_ref, commit, '0' * 40)
+ return {'source': source, 'destination': destination, 'parent': parent,
+ 'commit': commit, 'review_ref': review_ref, 'token': token}
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--repo', type=Path, default=Path.cwd())
+ parser.add_argument('--source', choices=['Dom', 'StarPilot'], required=True)
+ parser.add_argument('--destination', choices=['testing', 'stable'], required=True)
+ parser.add_argument('--base', required=True, help='Exact reviewed source commit')
+ parser.add_argument('--review-ref', required=True)
+ args = parser.parse_args()
+ print(json.dumps(prepare(args.repo, args.source, args.destination, args.base, args.review_ref), indent=2))
diff --git a/scripts/tests/test_branch_migration.py b/scripts/tests/test_branch_migration.py
new file mode 100644
index 0000000000..b0e3157020
--- /dev/null
+++ b/scripts/tests/test_branch_migration.py
@@ -0,0 +1,248 @@
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+
+SCRIPTS = Path(__file__).resolve().parents[1]
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, SCRIPTS / (name + '.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+runtime = load('branch_migration')
+creator = load('create_branch_migration')
+
+
+class BranchMigrationTest(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+
+ def git(self, repo, *args):
+ return subprocess.check_output(['git', '-c', 'core.hooksPath=/dev/null', '-C', str(repo), *args],
+ stderr=subprocess.STDOUT, text=True).strip()
+
+ def fixture(self, source='Dom', destination='testing', modern=None):
+ modern = source == 'Dom' if modern is None else modern
+ remote = self.root / ('remote-' + source)
+ remote.mkdir()
+ self.git(remote, 'init', '-b', source)
+ self.git(remote, 'config', 'user.name', 'Migration test')
+ self.git(remote, 'config', 'user.email', 'test@example.invalid')
+ (remote / 'launch_chffrplus.sh').write_text('#!/bin/bash\nDIR="."\nsource "$DIR/launch_env.sh"\n')
+ (remote / 'launch_chffrplus.sh').chmod(0o755)
+ (remote / 'payload').write_text('existing software and data')
+ (remote / 'prebuilt').write_text('')
+ if source == 'StarPilot':
+ version = remote / 'selfdrive/ui/lib/starpilot_version.py'
+ version.parent.mkdir(parents=True)
+ version.write_text('STARPILOT_DISPLAY_VERSION = "6.7.9"\n')
+ self.git(remote, 'add', '.')
+ if modern:
+ spec = importlib.util.spec_from_file_location('receipt', SCRIPTS.parent / 'openpilot/common/prebuilt_manifest.py')
+ receipt = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(receipt)
+ tree = self.git(remote, 'write-tree')
+ (remote / 'prebuilt.json').write_text(json.dumps({'schema_version': 1,
+ 'protected_inventory_sha256': receipt.revision_digest(lambda *args: self.git(remote, *args), tree)}))
+ self.git(remote, 'add', 'prebuilt.json')
+ self.git(remote, 'commit', '-m', 'Existing release')
+ parent = self.git(remote, 'rev-parse', 'HEAD')
+ migration = creator.prepare(remote, source, destination, parent, 'refs/heads/review/' + destination)
+ self.git(remote, 'update-ref', 'refs/heads/' + source, migration['commit'], parent)
+ self.git(remote, 'update-ref', 'refs/heads/' + destination, migration['commit'])
+ self.git(remote, 'reset', '--hard', migration['commit'])
+ repo = self.root / ('device-' + source)
+ self.git(self.root, 'clone', '--depth=1', '--single-branch', '--branch', source, remote.as_uri(), str(repo))
+ params = self.root / ('params-' + source)
+ params.mkdir()
+ (params / 'UpdaterTargetBranch').write_text(source)
+ (params / 'preserved-settings-models-recordings').write_bytes(b'unchanged')
+ return remote, repo, params, migration
+
+ def assert_migrated(self, repo, params, migration):
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), migration['destination'])
+ self.assertEqual(self.git(repo, 'rev-parse', 'HEAD'), migration['commit'])
+ self.assertEqual(self.git(repo, 'rev-parse', 'refs/heads/' + migration['source']), migration['commit'])
+ self.assertEqual(self.git(repo, 'config', 'branch.' + migration['destination'] + '.remote'), 'origin')
+ self.assertEqual(self.git(repo, 'config', 'branch.' + migration['destination'] + '.merge'), 'refs/heads/' + migration['destination'])
+ self.assertIn('+refs/heads/' + migration['destination'] + ':refs/remotes/origin/' + migration['destination'],
+ self.git(repo, 'config', '--get-all', 'remote.origin.fetch'))
+ self.assertEqual((params / 'UpdaterTargetBranch').read_text(), migration['destination'])
+ self.assertEqual((params / 'preserved-settings-models-recordings').read_bytes(), b'unchanged')
+ self.assertEqual(self.git(repo, 'status', '--porcelain'), '')
+
+ def test_both_channels_depth_one_without_parent_and_offline(self):
+ for source, destination in (('Dom', 'testing'), ('StarPilot', 'stable')):
+ with self.subTest(source=source):
+ remote, repo, params, migration = self.fixture(source, destination)
+ parent = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', migration['parent']], capture_output=True)
+ self.assertNotEqual(parent.returncode, 0)
+ self.git(repo, 'remote', 'set-url', 'origin', str(self.root / 'offline'))
+ self.assertEqual(runtime.migrate(repo, params), 'migrated to ' + destination)
+ self.assert_migrated(repo, params, migration)
+ self.assertEqual(runtime.migrate(repo, params), 'already migrated')
+ self.assertFalse((repo / '.git/starpilot-branch-migration.pending').exists())
+
+ def test_every_interrupted_step_retries_without_data_loss(self):
+ for step in ('pending', 'destination', 'head', 'remote', 'upstream', 'fetch', 'params', 'completed'):
+ with self.subTest(step=step):
+ case = self.root / step
+ case.mkdir()
+ original = self.root
+ self.root = case
+ try:
+ _, repo, params, migration = self.fixture()
+ def interrupt(current, interrupted_step=step):
+ if current == interrupted_step:
+ raise RuntimeError('simulated interruption')
+ with self.assertRaisesRegex(RuntimeError, 'simulated interruption'):
+ runtime.migrate(repo, params, interrupt)
+ runtime.migrate(repo, params)
+ self.assert_migrated(repo, params, migration)
+ self.assertFalse((repo / '.git/starpilot-branch-migration.pending').exists())
+ finally:
+ self.root = original
+
+ def test_destination_advance_is_fetched_without_resetting_installed_code(self):
+ remote, repo, params, migration = self.fixture()
+ self.git(remote, 'checkout', 'testing')
+ (remote / 'payload').write_text('new testing release')
+ self.git(remote, 'commit', '-am', 'Later destination release')
+ latest = self.git(remote, 'rev-parse', 'HEAD')
+ runtime.migrate(repo, params)
+ self.assert_migrated(repo, params, migration)
+ self.git(repo, 'fetch', 'origin')
+ self.assertEqual(self.git(repo, 'rev-parse', '@{upstream}'), latest)
+ self.assertEqual(self.git(repo, 'rev-parse', 'HEAD'), migration['commit'])
+
+ def test_rollback_or_manual_switch_never_chains(self):
+ _, repo, params, migration = self.fixture()
+ runtime.migrate(repo, params)
+ self.git(repo, 'checkout', 'Dom')
+ (params / 'UpdaterTargetBranch').write_text('Dom')
+ self.assertEqual(runtime.migrate(repo, params), 'already migrated')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
+ self.git(repo, 'checkout', '-b', 'StarPilot')
+ (params / 'UpdaterTargetBranch').write_text('StarPilot')
+ self.assertEqual(runtime.migrate(repo, params), 'already migrated')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'StarPilot')
+ self.assertFalse((repo / '.git/refs/heads/stable').exists())
+
+ def test_inherited_plan_is_inert_even_after_future_force_push(self):
+ _, repo, params, _ = self.fixture()
+ self.git(repo, 'config', 'user.name', 'Test')
+ self.git(repo, 'config', 'user.email', 'test@example.invalid')
+ (repo / 'payload').write_text('future rebase')
+ self.git(repo, 'commit', '-am', 'Future rebase release')
+ self.git(repo, 'branch', '-m', 'StarPilot')
+ (params / 'UpdaterTargetBranch').write_text('StarPilot')
+ self.assertEqual(runtime.migrate(repo, params), 'not migration release')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'StarPilot')
+
+ def test_manual_updater_target_is_preserved(self):
+ _, repo, params, _ = self.fixture()
+ (params / 'UpdaterTargetBranch').write_text('dev')
+ self.assertEqual(runtime.migrate(repo, params), 'manual updater selection')
+ self.assertEqual((params / 'UpdaterTargetBranch').read_text(), 'dev')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
+
+ def test_existing_different_destination_is_not_overwritten(self):
+ _, repo, params, migration = self.fixture()
+ tree = self.git(repo, 'rev-parse', 'HEAD^{tree}')
+ other = subprocess.check_output(['git', '-C', str(repo), '-c', 'user.name=Test', '-c',
+ 'user.email=test@example.invalid', 'commit-tree', tree], input=b'Other work\n').decode().strip()
+ self.git(repo, 'update-ref', 'refs/heads/testing', other)
+ with self.assertRaisesRegex(ValueError, 'different work'):
+ runtime.migrate(repo, params)
+ self.assertEqual(self.git(repo, 'rev-parse', 'refs/heads/testing'), other)
+
+ def test_missing_plan_is_inert(self):
+ repo = self.root / 'no-plan'
+ repo.mkdir()
+ self.assertEqual(runtime.migrate(repo, self.root / 'no-params'), 'no plan')
+
+ def test_changed_target_during_migration_is_not_overwritten(self):
+ _, repo, params, _ = self.fixture()
+ def change(step):
+ if step == 'fetch':
+ (params / 'UpdaterTargetBranch').write_text('dev')
+ with self.assertRaisesRegex(ValueError, 'selection changed'):
+ runtime.migrate(repo, params, change)
+ self.assertEqual((params / 'UpdaterTargetBranch').read_text(), 'dev')
+ self.assertEqual(runtime.migrate(repo, params), 'manual updater selection')
+
+ def test_generator_refreshes_canonical_modern_receipt(self):
+ _, repo, params, migration = self.fixture(modern=True)
+ spec = importlib.util.spec_from_file_location('receipt', SCRIPTS.parent / 'openpilot/common/prebuilt_manifest.py')
+ receipt = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(receipt)
+ self.assertTrue(receipt.valid_receipt(lambda *args: self.git(repo, *args), 'HEAD'))
+ self.assertEqual(self.git(repo, 'log', '-1', '--format=%B').splitlines(),
+ [f"Branch-Migration: Dom -> testing ({migration['token']})"])
+ runtime.migrate(repo, params)
+ self.assert_migrated(repo, params, migration)
+
+ def test_local_source_edits_and_param_mode_survive(self):
+ _, repo, params, _ = self.fixture()
+ (repo / 'payload').write_text('local work')
+ (params / 'UpdaterTargetBranch').chmod(0o640)
+ runtime.migrate(repo, params)
+ self.assertEqual((repo / 'payload').read_text(), 'local work')
+ self.assertEqual((params / 'UpdaterTargetBranch').stat().st_mode & 0o777, 0o640)
+
+ def test_wrong_parent_or_title_cannot_trigger_migration(self):
+ _, repo, params, _ = self.fixture()
+ plan = json.loads((repo / runtime.PLAN).read_text())
+ plan['parent'] = '0' * 40
+ (repo / runtime.PLAN).write_text(json.dumps(plan))
+ self.assertEqual(runtime.migrate(repo, params), 'not migration release')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
+
+ def test_pending_does_not_follow_manual_branch_switch(self):
+ _, repo, params, _ = self.fixture()
+ def stop(step):
+ if step == 'pending':
+ raise RuntimeError('interrupted')
+ with self.assertRaises(RuntimeError):
+ runtime.migrate(repo, params, stop)
+ self.git(repo, 'checkout', '-b', 'dev')
+ self.assertEqual(runtime.migrate(repo, params), 'manual branch selection')
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'dev')
+
+ def test_conflicting_pending_marker_is_not_overwritten(self):
+ _, repo, params, _ = self.fixture()
+ marker = repo / '.git/starpilot-branch-migration.pending'
+ marker.write_text('{"different": true}')
+ with self.assertRaisesRegex(ValueError, 'Another migration'):
+ runtime.migrate(repo, params)
+ self.assertEqual(marker.read_text(), '{"different": true}')
+
+ def test_old_installs_without_updater_preference_are_supported(self):
+ _, repo, params, migration = self.fixture('StarPilot', 'stable')
+ (params / 'UpdaterTargetBranch').unlink()
+ runtime.migrate(repo, params)
+ self.assert_migrated(repo, params, migration)
+
+ def test_generator_refuses_cross_channel_plan(self):
+ with self.assertRaisesRegex(ValueError, 'Only Dom'):
+ creator.prepare(self.root, 'testing', 'stable', 'HEAD', 'refs/heads/review/bad')
+
+ def test_malformed_plan_is_refused_without_moving_branch(self):
+ _, repo, params, _ = self.fixture()
+ (repo / runtime.PLAN).write_text('[]')
+ with self.assertRaisesRegex(ValueError, 'Invalid channel'):
+ runtime.migrate(repo, params)
+ self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/tests/test_channel_configuration.py b/scripts/tests/test_channel_configuration.py
new file mode 100644
index 0000000000..ed947633ac
--- /dev/null
+++ b/scripts/tests/test_channel_configuration.py
@@ -0,0 +1,49 @@
+import ast
+from pathlib import Path
+import re
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+class ChannelConfigurationTest(unittest.TestCase):
+ def test_old_and_new_channels_keep_ci_and_published_receipt_gate(self):
+ for name in ('tests.yaml', 'safety.yaml', 'docs.yaml', 'flm-offroad.yaml', 'galaxy-phone-bridge.yaml'):
+ source = (ROOT / '.github/workflows' / name).read_text().split('pull_request:', 1)[0]
+ for branch in ('StarPilot', 'Dom', 'stable', 'testing', 'dev'):
+ with self.subTest(workflow=name, branch=branch):
+ self.assertRegex(source, rf'\b{branch}\b')
+ tests = (ROOT / '.github/workflows/tests.yaml').read_text()
+ guard = next(line for line in tests.splitlines() if "github.event_name == 'push' && (github.ref" in line)
+ for branch in ('StarPilot', 'Dom', 'stable', 'testing', 'dev'):
+ self.assertIn(f"refs/heads/{branch}'", guard)
+ self.assertIn('tools/ci/check_prebuilt_receipt.py --revision HEAD', tests)
+
+ def test_pretty_channel_names_do_not_change_release_or_tested_policy(self):
+ source = ast.parse((ROOT / 'openpilot/common/version.py').read_text())
+ assignments = [node for node in source.body if isinstance(node, ast.Assign) and
+ any(isinstance(target, ast.Name) and target.id in ('RELEASE_BRANCHES', 'TESTED_BRANCHES')
+ for target in node.targets)]
+ values = {}
+ exec(compile(ast.Module(body=assignments, type_ignores=[]), '', 'exec'), {}, values)
+ for name in ('RELEASE_BRANCHES', 'TESTED_BRANCHES'):
+ self.assertTrue(set(values[name]).isdisjoint({'stable', 'testing', 'dev', 'Dom', 'StarPilot'}))
+
+ def test_launcher_and_updater_share_exact_legacy_pins(self):
+ source = ast.parse((ROOT / 'openpilot/system/updated/updated.py').read_text())
+ assignment = next(node for node in source.body if isinstance(node, ast.Assign) and
+ any(isinstance(target, ast.Name) and target.id == 'TRUSTED_LEGACY_RELEASES' for target in node.targets))
+ values = {}
+ exec(compile(ast.Module(body=[assignment], type_ignores=[]), '', 'exec'), {}, values)
+ pins = values['TRUSTED_LEGACY_RELEASES']
+ launcher = (ROOT / 'launch_chffrplus.sh').read_text()
+ declared = set(re.findall(r'TRUSTED_LEGACY_(?:STARPILOT_COMMIT|STABLE_MIGRATION)="([0-9a-f]{40})"', launcher))
+ self.assertEqual(declared, set().union(*pins.values()))
+ self.assertEqual(set(pins), {'StarPilot', 'stable'})
+ self.assertEqual(len(pins['stable']), 1)
+ self.assertLessEqual(pins['stable'], pins['StarPilot'])
+
+
+if __name__ == '__main__':
+ unittest.main()