Compare commits

...
1 Commits
Author SHA1 Message Date
linkong 6d310f4dbe release: bump version to 0.80.3
ci / frontend (push) Waiting to run
ci / backend (push) Waiting to run
2026-11-30 14:35:38 +08:00
19 changed files with 541 additions and 91 deletions

No files matched your search

+9 -9
View File
@@ -181,15 +181,15 @@ Push to remote:
When remote publication is requested, verify the remote tag points to the
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
using the command below. The publisher inspects changed files against the previous
stable release (`scripts/release_scope.py`), writes `release-manifest.json`, and
builds/uploads **only** the affected targets:
- `admin` / `backend` / `aiprovider`-only changes: builds/pushes only the changed
service image(s), skips desktop packaging and client hotfix updates, and deploys
only the changed container(s) on production.
- `frontend/public/earth/**`-only changes: emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`.
- `client/**` changes: builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle.
stable release (`scripts/release_scope.py`), pushes OCI `release-manifest:<tag>`,
and builds/uploads **only** the affected targets:
- `admin` / `backend` / `aiprovider`-only changes (`client.mode == "none"`): builds/pushes only the changed
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
Use `--scope auto` (default) or override explicitly with `--scope admin`,
`--scope hotfix`, `--scope backend,admin`, or `--scope full`:
+5
View File
@@ -126,6 +126,11 @@ the user's login interactive shell instead of assuming a specific dotfile.
committed files.
- Backend service code must use structured logging instead of `print()` or
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
- **Client-Only Gitea Releases**: Releases without client updates
(`client.mode == "none"`) push only changed container images plus OCI
`release-manifest:<tag>` and must **not** create a Gitea Release; only
`hotfix` or `full` client releases create a Gitea Release, and production
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
### Conflict Policy
+1 -1
View File
@@ -1 +1 @@
0.80.2
0.80.3
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.80.2",
"version": "0.80.3",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
+117 -25
View File
@@ -1,6 +1,8 @@
import { spawnSync } from 'node:child_process'
import {
chmodSync,
copyFileSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -130,33 +132,123 @@ function resolveLinuxTargets() {
return targets
}
function toWslPath(winPath) {
if (!winPath) return ''
const res = spawnSync('wslpath', ['-u', winPath], { encoding: 'utf8' })
return res.status === 0 ? (res.stdout || '').trim() : ''
}
function toWinPath(linuxPath) {
const res = spawnSync('wslpath', ['-w', linuxPath], { encoding: 'utf8' })
return res.status === 0 ? (res.stdout || '').trim() : ''
}
function resolveElectronVersion() {
try {
const pkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
const raw = String(pkg?.devDependencies?.electron || '').replace(/^[^0-9]*/, '')
return raw || ''
} catch {
return ''
}
}
function runWinViaWindowsHost() {
if (!isWsl()) return false
const winProbeScript = [
'$candidates = @(',
' (Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),',
' (Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe"),',
' (Join-Path $env:USERPROFILE "scoop\\shims\\bun.exe"),',
' (Join-Path $env:LOCALAPPDATA "bun\\bin\\bun.exe")',
') | Where-Object { $_ -and (Test-Path -LiteralPath $_) }',
'$candidates | Select-Object -First 1',
'$env:PLANET_WIN_BUN_EXE',
'(Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source)',
'(Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe")',
'(Join-Path $env:USERPROFILE "scoop\\shims\\bun.exe")',
'(Join-Path $env:LOCALAPPDATA "bun\\bin\\bun.exe")',
'@(Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\tools\\bun.exe") -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName)',
].join(', ')
const probePs = [
`$candidates = @(${winProbeScript}) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }`,
'$bunPath = $candidates | Select-Object -First 1',
'$cacheDirs = @((Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\electron-cache") -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName), (Join-Path $env:LOCALAPPDATA "electron\\Cache")) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }',
'$cacheHit = $cacheDirs | Where-Object { Get-ChildItem $_ -Filter "electron-v*-win32-x64.zip" -ErrorAction SilentlyContinue } | Select-Object -First 1',
'Write-Output ("LOCALAPPDATA=" + $env:LOCALAPPDATA)',
'Write-Output ("BUN=" + $bunPath)',
'Write-Output ("ELECTRON_CACHE=" + $cacheHit)',
].join('; ')
const winBunCheck = spawnSync('powershell.exe', ['-NoProfile', '-Command', winProbeScript], { encoding: 'utf8' })
const winBunPath = (winBunCheck.stdout || '').trim().split(/\r?\n/)[0]?.trim() || ''
const winPathRes = spawnSync('wslpath', ['-w', desktopRoot], { encoding: 'utf8' })
const winDesktopRoot = (winPathRes.stdout || '').trim()
if (winBunCheck.status !== 0 || !winBunPath || !winDesktopRoot) return false
const probe = spawnSync('powershell.exe', ['-NoProfile', '-Command', probePs], { encoding: 'utf8' })
if (probe.status !== 0) return false
console.log(`WSL2 detected; building Windows NSIS + portable installers via Windows host Bun (${winBunPath})...`)
const psScript = [
"$ErrorActionPreference = 'Stop'",
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
`Set-Location -LiteralPath '${winDesktopRoot.replace(/'/g, "''")}'`,
`& '${winBunPath.replace(/'/g, "''")}' x electron-builder --win nsis portable --publish never`,
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], { stdio: 'inherit' })
return (winRun.status ?? 1) === 0
const info = {}
for (const line of (probe.stdout || '').split(/\r?\n/)) {
const idx = line.indexOf('=')
if (idx > 0) info[line.slice(0, idx).trim()] = line.slice(idx + 1).trim()
}
const winBunPath = info.BUN || ''
const winLocalAppData = info.LOCALAPPDATA || ''
if (!winBunPath || !winLocalAppData) return false
const localAppDataWsl = toWslPath(winLocalAppData)
if (!localAppDataWsl) return false
const releaseOutDir = join(desktopRoot, 'release')
mkdirSync(releaseOutDir, { recursive: true })
const stageRoot = join(localAppDataWsl, 'PlanetReleaseBuild', `wsl-stage-${process.pid}`)
const stageClient = join(stageRoot, 'client')
const stageRelease = join(stageClient, 'release')
const stageCache = join(stageRoot, 'electron-cache')
mkdirSync(stageClient, { recursive: true })
let winElectronDist = info.ELECTRON_CACHE || ''
const electronVer = resolveElectronVersion()
const wslElectronZip = electronVer ? join(homedir(), '.cache', 'electron', `electron-v${electronVer}-win32-x64.zip`) : ''
if (!winElectronDist && wslElectronZip && existsSync(wslElectronZip)) {
mkdirSync(stageCache, { recursive: true })
copyFileSync(wslElectronZip, join(stageCache, `electron-v${electronVer}-win32-x64.zip`))
winElectronDist = toWinPath(stageCache)
}
try {
console.log(`WSL2 detected; staging Windows NSIS + zip build on NTFS via ${winBunPath}...`)
for (const rel of ['package.json', 'bun.lock', 'electron-builder.yml', 'dist-electron', '.earth-bundle', 'resources', 'scripts']) {
const src = join(desktopRoot, rel)
if (!existsSync(src)) {
throw new Error(`Missing required client build asset for Windows staging: ${src}`)
}
cpSync(src, join(stageClient, rel), { recursive: true })
}
const winStageClient = toWinPath(stageClient)
if (!winStageClient) return false
const builderArgs = ['--win', 'nsis', 'zip', '--x64', '--publish', 'never']
if (winElectronDist) {
builderArgs.push(`--config.electronDist=${winElectronDist}`)
}
const psArgs = builderArgs.map((arg) => `'${arg.replace(/'/g, "''")}'`).join(' ')
const psScript = [
"$ErrorActionPreference = 'Stop'",
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
`Set-Location -LiteralPath '${winStageClient.replace(/'/g, "''")}'`,
`& '${winBunPath.replace(/'/g, "''")}' install --frozen-lockfile --ignore-scripts`,
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
`& '${winBunPath.replace(/'/g, "''")}' ./node_modules/electron-builder/cli.js ${psArgs}`,
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], { stdio: 'inherit' })
if ((winRun.status ?? 1) !== 0 || !existsSync(stageRelease)) {
return false
}
let copied = 0
for (const entry of readdirSync(stageRelease)) {
if (entry.startsWith('__uninstaller-')) continue
if (entry.toLowerCase().endsWith('.exe') || entry.toLowerCase().endsWith('-win.zip')) {
copyFileSync(join(stageRelease, entry), join(releaseOutDir, entry))
copied += 1
}
}
return copied >= 2
} finally {
rmSync(stageRoot, { recursive: true, force: true })
}
}
function runWinViaDockerWine() {
@@ -170,7 +262,7 @@ function runWinViaDockerWine() {
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
const gid = typeof process.getgid === 'function' ? process.getgid() : 0
console.log(`Building Windows NSIS + portable installers via Docker Wine (${image})...`)
console.log(`Building Windows NSIS + zip installers via Docker Wine (${image})...`)
const dockerCmd = [
'run', '--rm',
'-v', `${desktopRoot}:/project`,
@@ -181,7 +273,7 @@ function runWinViaDockerWine() {
'-w', '/project',
image,
'bash', '-lc',
`./node_modules/.bin/electron-builder --win nsis portable --publish never; status=$?; chown -R ${uid}:${gid} /project/release 2>/dev/null || true; exit $status`,
`./node_modules/.bin/electron-builder --win nsis zip --publish never; status=$?; chown -R ${uid}:${gid} /project/release 2>/dev/null || true; exit $status`,
]
const res = spawnSync('docker', dockerCmd, { stdio: 'inherit' })
return (res.status ?? 1) === 0
@@ -189,7 +281,7 @@ function runWinViaDockerWine() {
function runWinBuild() {
if (process.platform === 'win32' || hasCommand('wine') || hasCommand('wine64')) {
runBuilder(['--win', 'nsis', 'portable'])
runBuilder(['--win', 'nsis', 'zip'])
return
}
+11
View File
@@ -8,6 +8,17 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.80.3] — 2026-11-30
Released: 2026-11-30
### Highlights
- Desktop release `0.80.3` ships full cross-platform Planet Earth installers (`Setup .exe`, `-win.zip`, macOS `.zip`, `.AppImage`, `.deb`, and Earth hotfix bundle) built directly from WSL2 via native Windows NTFS staging parity.
- Server-only releases without client updates now publish OCI `release-manifest:<tag>` metadata and changed service images without creating redundant Gitea Releases; production deployment discovers updates from Git tags + OCI manifests and sets an explicit HTTP User-Agent for health verification.
---
## [0.80.2] — 2026-11-30
Released: 2026-11-30
+6 -3
View File
@@ -330,9 +330,12 @@ No automatic hooks are installed in this phase. Manual reminders:
Use `.codex/skills/release/SKILL.md`, `scripts/release_scope.py`,
`scripts/release_publish.py`, and `.gitea/workflows/` files. Tagged releases
classify changed paths into scoped images (`admin`, `backend`, `aiprovider`)
and client modes (`none`, `hotfix`, `full`) in `release-manifest.json`, so
admin-only or backend-only releases never rebuild desktop clients or restart
unchanged services. Harness validation can smoke-check Helm and Docker locally,
and client modes (`none`, `hotfix`, `full`) recorded in OCI
`release-manifest:<tag>` (and `release-manifest.json` when a client Release is
created). Releases with `client.mode == "none"` push only changed service
images + OCI `release-manifest:<tag>` without creating a Gitea Release or
rebuilding desktop clients; only `hotfix` / `full` client releases create a
Gitea Release. Harness validation can smoke-check Helm and Docker locally,
and `scripts/harness/test_production_release.py` covers scoped release/deploy
logic without replacing the release process.
+2 -2
View File
@@ -487,9 +487,9 @@ Run the following command from the tagged commit.
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
The publisher builds Linux amd64 images for `admin`, `backend`, and `aiprovider` from the tag, then verifies their revisions and digests in Gitea. Admin uses the lightweight build target. Desktop packages are built from the same commit by default. Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The publisher classifies changed files from the tag commit (`scripts/release_scope.py`), builds Linux amd64 images only for changed services, and pushes OCI `release-manifest:<tag>` as the canonical deployment manifest. When a release contains no client or Earth hotfix update (`client.mode == "none"`), it skips desktop packaging and **does not create a Gitea Release**; Gitea Releases are created only for releases with L1 hotfixes (`hotfix`) or full desktop packages (`full`). Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The production host checks the latest stable Gitea Release approximately every two minutes using `planet-release-deploy.timer`. Once all three images and the hotfix checksum are available, it pulls the images by digest, backs up PostgreSQL, updates AI Provider, backend, and Admin in order, verifies their endpoints, publishes the Earth hotfix, and downloads it to verify its checksum. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
The production host checks the latest stable Git tags and OCI `release-manifest:<tag>` (plus Gitea Releases when client updates exist) approximately every two minutes using `planet-release-deploy.timer`. Once the manifest and digests are verified, it pulls only changed images by digest, backs up PostgreSQL, rolls out changed services, verifies endpoints, and publishes/verifies the Earth hotfix only when `client.mode != "none"`. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
+2 -2
View File
@@ -487,9 +487,9 @@ docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
发布器从标签提交构建 Linux amd64 的 `admin`、`backend`、`aiprovider` 镜像,并核验仓库中的提交标签与摘要。Admin 使用轻量构建目标。默认从同一提交打包桌面客户端。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
发布器从标签提交识别改动范围(`scripts/release_scope.py`),仅构建变更服务的 Linux amd64 镜像,并把完整部署清单写入 OCI `release-manifest:<tag>`。当版本不包含客户端或 Earth 热更变更(`client.mode == "none"`)时,不构建桌面客户端且**不创建新的 Gitea Release**;仅当包含 L1 热更或桌面客户端更新(`hotfix` / `full`)时才创建 Gitea Release 并附带 `release-manifest.json` 与对应安装包/热更包。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
生产机的 `planet-release-deploy.timer` 约每两分钟读取 Gitea 最新正式 Release。新版本的三个镜像和热更新校验文件齐全后,服务按不可变摘要拉取镜像,备份 PostgreSQL,依次更新 AI Provider、后端和 Admin,再验证接口、发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
生产机的 `planet-release-deploy.timer` 约每两分钟检查 Gitea 最新正式标签、OCI `release-manifest:<tag>`(及客户端更新版本对应的 Gitea Release)。确认清单与摘要齐全后,服务按不可变摘要仅拉取并滚动更新有变动的容器,备份 PostgreSQL,验证健康接口;仅在 `client.mode != "none"` 时发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
+2 -1
View File
@@ -16,12 +16,13 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.80.2`
- `dev` 当前开发分支历史推导到:`0.80.3`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.80.3` | improvement | `dev` | `v0.80.3` | 发布含全平台最新客户端安装包与 Earth 热更包的 0.80.3;固化仅含客户端更新才创建 Gitea Release 与 OCI release-manifest 发现规则 |
| `0.80.2` | improvement | `dev` | `v0.80.2` | 统一 Admin 控件设计参数与 Harness 校验,支持本地客户端全平台打包及按改动范围分层发版部署 |
| `0.80.1` | improvement | `dev` | `v0.80.1` | 数据源支持批量启停调度、保留筛选和就地更新,优化 Earth 卡片与 AI 对话滚动 |
| `0.80.0` | feature | `dev` | `v0.80.0` | Earth AI 工作台支持流式多轮对话和本地会话,新增单摄手势控制与公共模型目录批量刷新 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.80.2",
"version": "0.80.3",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.80.2"
version = "0.80.3"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+3 -2
View File
@@ -668,8 +668,9 @@ release-oriented change.
- Before committing a release, verify target version consistency.
- Before pushing a release, run the smallest relevant validation for the changed scope and report what was or was not validated.
- Do not include generated runtime output directories in release commits.
- **Scoped Release & Deployment Classification**: Releases resolve changed paths (`scripts/release_scope.py`) against the previous stable tag and record exact service image digests plus `client.mode` (`none` | `hotfix` | `full`) in `release-manifest.json`:
- `admin`-only, `backend`-only, or `aiprovider`-only changes build/push/roll out **only** the affected container image(s) and must **not** package desktop clients or publish client update manifests.
- **Scoped Release & Deployment Classification**: Releases resolve changed paths (`scripts/release_scope.py`) against the previous stable tag and record exact service image digests plus `client.mode` (`none` | `hotfix` | `full`) in OCI `release-manifest:<tag>` (and in `release-manifest.json` when a client Release is published):
- `admin`-only, `backend`-only, or `aiprovider`-only changes (`client.mode == "none"`) push **only** the affected container image(s) + OCI `release-manifest:<tag>`, must **not** package desktop clients or publish client update manifests, and must **not** create a Gitea Release.
- Only releases with client updates (`client.mode` = `hotfix` or `full`) create a Gitea Release. Production `planet-release-deploy` inspects Git tags + OCI `release-manifest:<tag>` directly (with fallback to Gitea Releases for legacy tags) so server-only releases still roll out to the changed containers cleanly.
- `frontend/public/earth/**` (without `client/**`) emits only the lightweight L1 Earth hotfix bundle (`--hotfix`) while preserving the prior `shell_version`.
- `client/**` triggers full multi-platform desktop installer builds (`--all`, producing `.exe`/`.zip`, `.AppImage`/`.deb`, `.zip`) plus the L1 hotfix bundle.
- Docs/harness-only changes do not trigger production rollouts.
+136 -1
View File
@@ -5,7 +5,7 @@ import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack, redirect_stdout
from contextlib import ExitStack, contextmanager, redirect_stdout
from pathlib import Path
from unittest.mock import patch
@@ -452,6 +452,10 @@ class ScopedReleaseTests(unittest.TestCase):
docker_mock.assert_not_called()
rollout_mock.assert_not_called()
self.assertEqual(hotfix_mock.call_args.kwargs["shell_version"], "1.0.0")
self.assertEqual(
hotfix_mock.call_args.kwargs["release_html_url"],
"https://gitea.rclaw.top/linkong/planet/releases/tag/v1.0.0",
)
check_hotfix_mock.assert_called_once_with("v1.1.0", bundle_sha, shell_version="1.0.0")
def test_release_publish_dry_run_hotfix_filters_assets_and_stays_read_only(self):
@@ -468,12 +472,143 @@ class ScopedReleaseTests(unittest.TestCase):
self.assertEqual(rc, 0)
stdout = out.getvalue()
self.assertIn("scope_client_mode: hotfix", stdout)
self.assertIn("gitea_release: create", stdout)
self.assertIn("assets_count: 1", stdout)
self.assertIn("planet-earth-bundle-0.80.1.tar.gz", stdout)
self.assertNotIn("Planet-0.80.1.exe", stdout)
self.assertNotIn("Planet-0.80.1.AppImage", stdout)
self.assertFalse((root / "SHA256SUMS.txt").exists())
def test_release_publish_server_only_skips_gitea_release(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
manifest = {
"schema_version": 1,
"tag": "v0.80.2",
"commit": "a" * 40,
"previous_tag": "v0.80.1",
"components": ["admin"],
"changed_services": ["admin"],
"services": {k: f"gitea.rclaw.top/linkong/planet/{k}:v0.80.2@sha256:{'1' * 64}" for k in registry.SERVICES},
"client": {"mode": "none", "shell_version": "0.80.1", "min_shell_version": "0.80.1"},
}
(root / registry.MANIFEST_NAME).write_text(json.dumps(manifest))
changelog = root / "CHANGELOG.md"
changelog.write_text("# Changelog\n")
@contextmanager
def fake_prepare(*_args, **_kwargs):
yield root, changelog
out = io.StringIO()
with (
patch.object(publish, "run_git_origin_url", return_value="https://gitea.rclaw.top/linkong/planet.git"),
patch.object(publish, "git_credential_authorization", return_value="token test"),
patch.object(publish, "api_request", return_value=(404, None)),
patch.object(publisher, "prepare", side_effect=fake_prepare),
patch.object(publish, "publish_release") as pub_mock,
redirect_stdout(out),
):
rc = publish.main(["--tag", "v0.80.2", "--scope", "admin", "--use-git-credential"])
self.assertEqual(rc, 0)
pub_mock.assert_not_called()
self.assertIn("skipped Gitea Release: no client update", out.getvalue())
def test_deploy_discovers_server_only_release_from_tags_and_oci_without_gitea_release(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
host = deploy.Host(base / "host", base / "settings", base / "state")
host.state.mkdir()
(host.directory("v1.0.0")).mkdir(parents=True)
for name in deploy.HOST_FILES:
(host.directory("v1.0.0") / name).write_text("host-managed")
deploy.point_current(host, "v1.0.0")
old_refs = {
"aiprovider": f"gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:{'1' * 64}",
"backend": f"gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:{'2' * 64}",
"admin": f"gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:{'3' * 64}",
}
new_admin = f"gitea.rclaw.top/linkong/planet/admin:v1.1.0@sha256:{'4' * 64}"
new_refs = {**old_refs, "admin": new_admin}
manifest = {
"schema_version": 1,
"tag": "v1.1.0",
"commit": "f" * 40,
"previous_tag": "v1.0.0",
"components": ["admin"],
"changed_services": ["admin"],
"services": new_refs,
"client": {"mode": "none", "shell_version": "1.0.0", "min_shell_version": "1.0.0"},
}
host.env.write_text(
"\n".join([f"{registry.SERVICES[k]}={v}" for k, v in old_refs.items()]) + "\n"
)
live_manifest = base / "manifest.json"
original_live = b'{"bundle":{"version":"1.0.0","sha256":"keep"}}'
live_manifest.write_bytes(original_live)
running = old_refs.copy()
rolled = []
tags_payload = json.dumps([
{"name": "v1.2.0", "commit": {"sha": "e" * 40}}, # unpublished tag skipped cleanly
{"name": "v1.1.0", "commit": {"sha": "f" * 40}},
{"name": "v1.0.0", "commit": {"sha": "a" * 40}},
]).encode()
def fake_oci(tag, commit):
if tag == "v1.1.0" and commit == "f" * 40:
return manifest
return None
with (
patch.object(deploy, "read_url", return_value=tags_payload),
patch.object(deploy, "resolve_release_manifest_oci", side_effect=fake_oci),
patch.object(deploy, "release_by_tag", return_value=None) as release_by_tag_mock,
patch.object(deploy, "resolved_images", return_value=new_refs),
patch.object(deploy, "inspect", side_effect=lambda name: {"Config": {"Image": running[name]}}),
patch.object(deploy, "data_containers", return_value={"postgres": "same", "redis": "same"}),
patch.object(deploy, "live_manifest_path", return_value=live_manifest),
patch.object(deploy, "docker"),
patch.object(deploy, "backup_database", side_effect=lambda p: p.write_bytes(b"ok")),
patch.object(deploy, "rollout_services", side_effect=lambda _h, _t, imgs, services=None: (rolled.append(tuple(services or ())), running.update({s: imgs[s] for s in (services or ())}))) as rollout_mock,
patch.object(deploy, "check_routes"),
patch.object(deploy, "publish_hotfix_bundle") as hotfix_mock,
patch.object(deploy, "check_hotfix") as check_hotfix_mock,
):
deploy.reconcile(host)
self.assertEqual(host.current(), "v1.1.0")
self.assertEqual(rolled, [("admin",)])
rollout_mock.assert_called_once()
hotfix_mock.assert_not_called()
check_hotfix_mock.assert_not_called()
self.assertEqual(live_manifest.read_bytes(), original_live)
release_by_tag_mock.assert_called_once_with("v1.2.0")
def test_read_url_sets_default_user_agent(self):
captured = {}
class DummyResp:
def __enter__(self):
return self
def __exit__(self, *args):
return False
def read(self, _n):
return b"ok"
class DummyOpener:
def open(self, request, timeout=30):
captured["ua"] = request.get_header("User-agent")
return DummyResp()
with patch.object(registry.urllib.request, "build_opener", return_value=DummyOpener()):
data = registry.read_url("https://rclaw.top/health/ready")
self.assertEqual(data, b"ok")
self.assertEqual(captured["ua"], registry.DEFAULT_USER_AGENT)
if __name__ == "__main__":
unittest.main()
+66 -14
View File
@@ -9,6 +9,7 @@ import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
@@ -26,8 +27,10 @@ if __package__:
SERVICES,
read_url,
release_bundle,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
@@ -41,8 +44,10 @@ else:
SERVICES,
read_url,
release_bundle,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
@@ -433,8 +438,8 @@ def deploy(host, release, previous, tag, images, commit, *, manifest=None):
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
notes=(release or {}).get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/v{shell_version}",
assets=[(archive, sha)],
min_shell_version=minimum,
shell_version=shell_version,
@@ -452,27 +457,75 @@ def deploy(host, release, previous, tag, images, commit, *, manifest=None):
)
def discover_latest_release(previous, *, check=False):
"""Discover the highest deliverable stable release from Gitea tags and OCI/Release metadata."""
payload = json.loads(read_url(API + "/tags?limit=30"))
if isinstance(payload, dict) and "tag_name" in payload:
tag = payload["tag_name"]
if payload.get("draft") or payload.get("prerelease"):
return None
try:
candidate_version = version(tag)
except ValueError:
print(f"Ignoring release with a non-production tag: {tag!r}")
return None
if candidate_version < version(previous):
return None
if tag == previous and not check:
return tag, None, None, payload
commit = tag_commit(tag)
manifest = release_manifest(payload, tag)
return tag, commit, manifest, payload
if not isinstance(payload, list):
raise ValueError("Gitea returned unexpected tag listing payload")
min_ver = version(previous)
candidates = []
for entry in payload:
if not isinstance(entry, dict):
continue
name = entry.get("name")
if not isinstance(name, str):
continue
try:
ver = version(name)
except ValueError:
continue
if ver >= min_ver:
sha = (entry.get("commit") or {}).get("sha")
candidates.append((ver, name, sha))
candidates.sort(reverse=True)
for _, tag, sha in candidates:
commit = sha if (isinstance(sha, str) and re.fullmatch("[0-9a-f]{40,64}", sha)) else tag_commit(tag)
manifest = resolve_release_manifest_oci(tag, commit)
if manifest is not None:
if manifest["client"]["mode"] == "none":
return tag, commit, manifest, None
release = release_by_tag(tag)
if release is not None:
return tag, commit, manifest, release
continue
release = release_by_tag(tag)
if release is not None:
return tag, commit, release_manifest(release, tag), release
return None
def reconcile(host, *, check=False, retry=False):
if (host.state / "pending").exists():
if check:
raise RuntimeError("A previous rollout is pending recovery")
rollback(host)
previous = host.current()
release = json.loads(read_url(API + "/releases/latest"))
tag = release["tag_name"]
if release.get("draft") or release.get("prerelease"):
return
try:
candidate_version = version(tag)
except ValueError:
print(f"Ignoring release with a non-production tag: {tag!r}")
return
if candidate_version < version(previous):
discovered = discover_latest_release(previous, check=check)
if discovered is None:
return
tag, commit, manifest, release = discovered
if tag == previous and not check:
print(f"{tag} is already active")
return
commit = tag_commit(tag)
failed = host.state / "last-failed/release.json"
if (
tag != previous
@@ -482,7 +535,6 @@ def reconcile(host, *, check=False, retry=False):
):
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
return
manifest = release_manifest(release, tag)
images = resolved_images(tag, commit, manifest=manifest)
if check:
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
+77 -19
View File
@@ -15,6 +15,8 @@ REPO = "linkong/planet"
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
MANIFEST_NAME = "release-manifest.json"
MANIFEST_IMAGE = "release-manifest"
DEFAULT_USER_AGENT = "Planet-Release-Deploy/1.0"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
"backend": "BACKEND_IMAGE_NAME",
@@ -37,7 +39,10 @@ class NoRedirect(urllib.request.HTTPRedirectHandler):
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
request = urllib.request.Request(url, headers=headers or {})
merged_headers = dict(headers or {})
if not any(key.lower() == "user-agent" for key in merged_headers):
merged_headers["User-Agent"] = DEFAULT_USER_AGENT
request = urllib.request.Request(url, headers=merged_headers)
for attempt in range(3):
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
@@ -97,18 +102,8 @@ def release_bundle(release, tag):
return _verified_release_asset(release, tag, name, limit=32 * 1024 * 1024, label="Earth bundle")
def release_manifest(release, tag):
"""Read and validate optional release-manifest.json; returns None for legacy releases."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
if not any(entry.get("name") == MANIFEST_NAME for entry in assets):
return None
_, data, _ = _verified_release_asset(
release, tag, MANIFEST_NAME, limit=512 * 1024, label="Release manifest"
)
manifest = json.loads(data.decode("utf-8"))
def _validate_release_manifest(manifest, tag):
"""Validate common schema and pin structure for a release manifest."""
if not isinstance(manifest, dict) or manifest.get("schema_version") != 1:
raise ValueError("Unsupported release manifest schema version")
if manifest.get("tag") != tag:
@@ -122,6 +117,42 @@ def release_manifest(release, tag):
return manifest
def release_manifest(release, tag):
"""Read and validate optional release-manifest.json; returns None for legacy releases."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
if not any(entry.get("name") == MANIFEST_NAME for entry in assets):
return None
_, data, _ = _verified_release_asset(
release, tag, MANIFEST_NAME, limit=512 * 1024, label="Release manifest"
)
return _validate_release_manifest(json.loads(data.decode("utf-8")), tag)
def latest_stable_tags(limit=30):
"""Return recent repository tags from Gitea."""
data = json.loads(read_url(f"{API}/tags?limit={int(limit)}"))
if not isinstance(data, list):
raise ValueError("Gitea returned invalid repository tag metadata")
return data
def release_by_tag(tag):
"""Return a published non-draft/non-prerelease Gitea Release dict, or None when absent."""
version(tag)
try:
release = json.loads(read_url(f"{API}/releases/tags/{tag}"))
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise
if not isinstance(release, dict) or release.get("draft") or release.get("prerelease"):
return None
return release
def resolve_service_ref(service, ref):
"""Verify an explicit ``image:tag@sha256:...`` pin against Gitea registry."""
prefix = image_name(service) + ":"
@@ -143,6 +174,10 @@ def image_name(service):
return f"{REGISTRY}/{REPO}/{service}"
def manifest_image_name():
return f"{REGISTRY}/{REPO}/{MANIFEST_IMAGE}"
def digest(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
@@ -154,11 +189,8 @@ def descriptor_digest(desc):
return value
def resolve_image(service, tag, commit):
"""Return the immutable platform image; only an absent tag returns None."""
version(tag)
name = image_name(service)
repository = f"{REPO}/{service}"
def _fetch_oci_config(repository, name, tag, commit):
"""Fetch and verify the linux/amd64 OCI manifest digest and revision label."""
query = urllib.parse.urlencode(
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
)
@@ -196,6 +228,32 @@ def resolve_image(service, tag, commit):
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
if labels.get("org.opencontainers.image.revision") != commit:
raise ValueError(f"{name}:{tag} belongs to a different commit")
return digest(raw), labels
def resolve_image(service, tag, commit):
"""Return the immutable platform image; only an absent tag returns None."""
version(tag)
name = image_name(service)
fetched = _fetch_oci_config(f"{REPO}/{service}", name, tag, commit)
if fetched is None:
return None
manifest_digest, labels = fetched
if service == "admin" and labels.get("planet.frontend.target") != "admin":
raise ValueError("The production Admin image must be built with the admin-only target")
return f"{name}:{tag}@{digest(raw)}"
return f"{name}:{tag}@{manifest_digest}"
def resolve_release_manifest_oci(tag, commit):
"""Read and validate the OCI release-manifest:<tag> metadata artifact, or None on 404."""
version(tag)
name = manifest_image_name()
fetched = _fetch_oci_config(f"{REPO}/{MANIFEST_IMAGE}", name, tag, commit)
if fetched is None:
return None
_, labels = fetched
raw_manifest = labels.get("planet.release.manifest")
if not isinstance(raw_manifest, str) or not raw_manifest.strip():
raise ValueError(f"{name}:{tag} is missing planet.release.manifest label")
manifest = json.loads(raw_manifest)
return _validate_release_manifest(manifest, tag)
+80 -4
View File
@@ -22,9 +22,12 @@ if __package__:
SERVER,
SERVICES,
image_name,
manifest_image_name,
read_url,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
@@ -38,9 +41,12 @@ else:
SERVER,
SERVICES,
image_name,
manifest_image_name,
read_url,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
@@ -219,8 +225,12 @@ def resolve_previous_release_state(previous_tag):
"""Fetch verified service image refs and active desktop shell version from ``previous_tag``."""
if not previous_tag:
return {}, None, None
release = json.loads(read_url(f"{API}/releases/tags/{previous_tag}"))
manifest = release_manifest(release, previous_tag)
prev_commit = tag_commit(previous_tag)
manifest = resolve_release_manifest_oci(previous_tag, prev_commit)
if manifest is None:
release = release_by_tag(previous_tag)
if release is not None:
manifest = release_manifest(release, previous_tag)
if manifest is not None:
pins = {
service: resolve_service_ref(service, ref)
@@ -229,7 +239,6 @@ def resolve_previous_release_state(previous_tag):
client = manifest.get("client") or {}
return pins, client.get("shell_version"), client.get("min_shell_version")
prev_commit = tag_commit(previous_tag)
pins = {}
for service in SERVICES:
pin = resolve_image(service, previous_tag, prev_commit)
@@ -239,6 +248,56 @@ def resolve_previous_release_state(previous_tag):
return pins, previous_tag[1:], previous_tag[1:]
def ensure_release_manifest_image(tag, commit, manifest):
"""Push and verify the minimal OCI release-manifest:<tag> metadata artifact."""
existing = resolve_release_manifest_oci(tag, commit)
if existing is not None:
if existing != manifest:
raise RuntimeError(f"Published OCI release manifest for {tag} differs from expected manifest")
print(f"Verified OCI {manifest_image_name()}:{tag}", flush=True)
return existing
with tempfile.TemporaryDirectory(prefix="planet-manifest-") as tmp:
ctx = Path(tmp)
(ctx / "release-manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
)
(ctx / "Dockerfile").write_text(
"FROM scratch\nCOPY release-manifest.json /release-manifest.json\n",
encoding="utf-8",
)
cmd = [
"docker",
"--config",
str(docker_config()),
"buildx",
"build",
"--platform",
"linux/amd64",
"--provenance=false",
"--file",
str(ctx / "Dockerfile"),
"--label",
f"org.opencontainers.image.revision={commit}",
"--label",
f"org.opencontainers.image.version={tag[1:]}",
"--label",
f"org.opencontainers.image.source={SERVER}/{REPO}",
"--label",
f"planet.release.manifest={json.dumps(manifest, separators=(',', ':'))}",
"--output",
f"type=image,name={manifest_image_name()}:{tag},push=true,compression=gzip,force-compression=true",
str(ctx),
]
subprocess.run(cmd, check=True)
verified = resolve_release_manifest_oci(tag, commit)
if verified != manifest:
raise RuntimeError(f"Pushed OCI release manifest is missing or mismatched for {tag}")
print(f"Verified OCI {manifest_image_name()}:{tag}", flush=True)
return verified
def build_release_manifest(tag, commit, scope, service_refs, packages, *, shell_version=None, min_shell_version=None):
ver = tag[1:]
bundle_name = f"planet-earth-bundle-{ver}.tar.gz"
@@ -331,7 +390,24 @@ def prepare(tag, assets_dir, suffixes, *, already_published=False, scope_overrid
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
(stage / MANIFEST_NAME).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
else:
manifest = resolve_release_manifest_oci(tag, commit)
if manifest is None:
pub_release = release_by_tag(tag)
if pub_release is not None:
manifest = release_manifest(pub_release, tag)
if manifest is None:
manifest = build_release_manifest(
tag,
commit,
scope,
service_refs,
[],
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
ensure_release_manifest_image(tag, commit, manifest)
(stage / MANIFEST_NAME).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
if cache.exists():
+20 -4
View File
@@ -575,6 +575,9 @@ def main(argv: list[str] | None = None) -> int:
print(f"scope_components: {','.join(scope.components)}")
print(f"scope_services: {','.join(scope.services) or 'none'}")
print(f"scope_client_mode: {scope.client_mode}")
print(
f"gitea_release: {'skip (no client update)' if scope.client_mode == 'none' else 'create'}"
)
print(f"scope_previous_tag: {scope.previous_tag or 'none'}")
print(f"notes_length: {len(notes)}")
print(f"assets_count: {len(assets)}")
@@ -585,10 +588,10 @@ def main(argv: list[str] | None = None) -> int:
try:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle, release_manifest
from .production_registry import API, MANIFEST_NAME, REPO, SERVER, release_bundle, release_manifest
from .production_release import prepare
else:
from production_registry import API, REPO, SERVER, release_bundle, release_manifest
from production_registry import API, MANIFEST_NAME, REPO, SERVER, release_bundle, release_manifest
from production_release import prepare
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
@@ -614,9 +617,22 @@ def main(argv: list[str] | None = None) -> int:
already_published=published,
scope_override=args.scope,
) as (stage, changelog):
manifest = json.loads((stage / MANIFEST_NAME).read_text(encoding="utf-8"))
client_mode = manifest["client"]["mode"]
if client_mode == "none":
if published:
raise RuntimeError(
f"Server-only release {args.tag} must not have a published Gitea Release"
)
print(
f"Published server-only release {args.tag} via OCI manifest "
"(skipped Gitea Release: no client update)",
flush=True,
)
return 0
if published:
manifest = release_manifest(public, args.tag)
if manifest is None or manifest["client"]["mode"] != "none":
pub_manifest = release_manifest(public, args.tag)
if pub_manifest is None or pub_manifest["client"]["mode"] != "none":
release_bundle(public, args.tag)
print(f"Verified published release {args.tag}; production follows stable releases")
else:
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.80.2"
version = "0.80.3"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },