Compare commits

..
2 Commits
Author SHA1 Message Date
linkong 6d310f4dbe release: bump version to 0.80.3
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-30 14:35:38 +08:00
linkong 2c439b7235 release: bump version to 0.80.2
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-30 11:06:33 +08:00
28 changed files with 1802 additions and 195 deletions

No files matched your search

+14 -5
View File
@@ -180,13 +180,22 @@ 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 builds the three production images and
the desktop packages from the tag. A published stable release triggers the
server's two-minute Compose deployment check. The workstation can go offline
after publication. Check the live update manifest and the running image digests
before reporting production deployment complete.
using the command below. The publisher inspects changed files against the previous
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`:
```bash
python3 scripts/release_publish.py --tag vx.x.x --dry-run
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
```
+11
View File
@@ -98,6 +98,12 @@ the user's login interactive shell instead of assuming a specific dotfile.
one-screen (`一屏` / `首屏`) height chain: route roots use `height: 100%`,
intermediate wrappers keep `min-height: 0`, and only the intended child owns
scrolling.
- **Admin Control Design Contract**: Inline controls in the same row must share
a `rules.md` density tier (`--an-control-xs/sm/md/lg`, e.g., `32px` filter bar
with `0px` height jump on filter reset), centered table selection/switch
columns, rounded-square shadowless `.tui-switch`, labeled `操作` columns, and
`.an-detail-link` navigation cues; enforced by
`scripts/harness/frontend-rules-check.sh` and `scripts/harness/frontend-smoke.mjs`.
- **Existing-UI Context Inspection Before Editing**: Whenever changing or
extending an existing interface (any non-new screen, such as `/earth/` HUD
overlays or existing Admin/Docs pages), inspect surrounding sibling controls,
@@ -120,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.1
0.80.3
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.80.1",
"version": "0.80.3",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
@@ -37,6 +37,7 @@
"start": "bun run build && bun ./scripts/launch-electron.mjs",
"dev": "bun run build && bun ./scripts/launch-electron.mjs --devtools",
"dist:dir": "bun run build && bun ./scripts/dist-target.mjs --dir",
"dist:hotfix": "bun run build:earth",
"dist:win": "bun run build && bun ./scripts/dist-target.mjs --win",
"dist:linux": "bun run build && bun ./scripts/dist-target.mjs --linux",
"dist:mac": "bun run build && bun ./scripts/dist-target.mjs --mac",
+175 -31
View File
@@ -1,7 +1,10 @@
import { spawnSync } from 'node:child_process'
import {
chmodSync,
copyFileSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
@@ -129,43 +132,177 @@ 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 = [
'$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 probe = spawnSync('powershell.exe', ['-NoProfile', '-Command', probePs], { encoding: 'utf8' })
if (probe.status !== 0) return false
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() {
if (!hasCommand('docker')) return false
const image = process.env.PLANET_ELECTRON_BUILDER_IMAGE || 'electronuserland/builder:wine'
const home = homedir()
const electronCache = join(home, '.cache', 'electron')
const builderCache = join(home, '.cache', 'electron-builder')
mkdirSync(electronCache, { recursive: true })
mkdirSync(builderCache, { recursive: true })
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
const gid = typeof process.getgid === 'function' ? process.getgid() : 0
console.log(`Building Windows NSIS + zip installers via Docker Wine (${image})...`)
const dockerCmd = [
'run', '--rm',
'-v', `${desktopRoot}:/project`,
'-v', `${electronCache}:/root/.cache/electron`,
'-v', `${builderCache}:/root/.cache/electron-builder`,
'-e', `ELECTRON_MIRROR=${env.ELECTRON_MIRROR}`,
'-e', `ELECTRON_BUILDER_BINARIES_MIRROR=${env.ELECTRON_BUILDER_BINARIES_MIRROR}`,
'-w', '/project',
image,
'bash', '-lc',
`./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
}
function runWinBuild() {
if (process.platform === 'win32' || hasCommand('wine') || hasCommand('wine64')) {
runBuilder(['--win', 'nsis', 'portable'])
runBuilder(['--win', 'nsis', 'zip'])
return
}
if (isWsl()) {
const winBunCheck = spawnSync(
'powershell.exe',
['-NoProfile', '-Command', 'Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source'],
{ encoding: 'utf8' },
)
const winBunPath = (winBunCheck.stdout || '').trim()
const winPathRes = spawnSync('wslpath', ['-w', desktopRoot], { encoding: 'utf8' })
const winDesktopRoot = (winPathRes.stdout || '').trim()
if (winBunCheck.status === 0 && winBunPath && winDesktopRoot) {
console.log('WSL2 detected without Wine; building Windows installers via Windows host toolchain...')
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, "''")}'`,
'bun x electron-builder --win nsis portable --publish never',
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], {
stdio: 'inherit',
})
if ((winRun.status ?? 1) === 0) {
return
}
console.warn('Windows host build fell back to unpacked/zip cross-build without Wine.')
}
} else {
console.warn('Wine not available on Linux host: building standalone Windows zip bundle (win-unpacked + zip).')
if (runWinViaWindowsHost()) {
return
}
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
if (runWinViaDockerWine()) {
return
}
if (process.env.PLANET_ALLOW_WIN_ZIP_FALLBACK === '1') {
console.warn('PLANET_ALLOW_WIN_ZIP_FALLBACK=1 set without Wine/Docker/Windows Bun: building win zip without NSIS .exe.')
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
return
}
console.error(
'Unable to build Windows NSIS (.exe) installer: install Wine (wine64), enable Docker (electronuserland/builder:wine), or install Windows bun.exe (or set PLANET_ALLOW_WIN_ZIP_FALLBACK=1 for zip-only).',
)
process.exit(1)
}
function runMacBuild() {
@@ -177,7 +314,14 @@ function runMacBuild() {
}
}
if (mode === '--dir') {
if (mode === '--hotfix') {
const result = spawnSync(process.execPath, [join(__dirname, 'build-earth-bundle.mjs')], {
cwd: desktopRoot,
env,
stdio: 'inherit',
})
process.exit(result.status ?? 1)
} else if (mode === '--dir') {
runBuilder(['--dir'])
} else if (mode === '--linux') {
runBuilder(['--linux', ...resolveLinuxTargets()])
+22
View File
@@ -8,6 +8,28 @@ 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
### Highlights
- Admin standardizes control density/radius CSS tokens (`--an-control-*`), aligns datasource filter bars (`32px` with `0px` reset jump), selection checkboxes, and shadowless rounded-square switches, and enforces the layout contract in static + Playwright harness checks.
- Desktop client local packaging aligns cross-platform Windows `.exe` builds (`dist-target.mjs` 3-tier detection + `--hotfix` bundle), while release publishing and production deployment classify changes by scope (`release_scope.py` + `release-manifest.json`) so Admin/Backend/AIProvider rollouts never trigger unnecessary client rebuilds.
---
## [0.80.1] — 2026-11-26
Released: 2026-11-26
+12 -4
View File
@@ -94,7 +94,7 @@ elevated restart; report that separately when it has not been exercised.
| Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. |
| Security | `scripts/harness/security-check.sh` | Checks that environment/private-key files are not tracked and scans for high-confidence committed secret tokens. |
| Backend Rules | `scripts/harness/backend-rules-check.sh` | Checks backend app Python for direct `print()`, `breakpoint()`, and `pdb.set_trace()` debug calls so service code uses structured logging. |
| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, viewport-scaled font sizes, zero letter spacing, Earth HUD baseline shell/glow/translucency/focus-stack alignment, and high-signal UI rule warnings. |
| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, Admin control design contract (`--an-control-*`, checkbox centering, switch `box-shadow: none`, segmented transparent borders, `DataTable` `data-column-id`), viewport-scaled font sizes, zero letter spacing, Earth HUD baseline shell/glow/translucency/focus-stack alignment, and high-signal UI rule warnings. |
| Docs Consistency | `scripts/harness/docs-consistency-check.sh` | Checks frontend Docs metadata against backend Gatekeeper metadata, public Docs registration, full technical-doc bilingual file pairs, public doc links, readable link titles, language-scoped technical links, README/project-context admin stack drift, supported credential collector contracts, manual console route coverage against the actual admin manifest, documented UI route drift, and documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs. |
| Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, isolated Docker bootstrap/proxy and startup tests, error-catalog consistency tests, security scan, backend/frontend/doc consistency checks, and CI backend smoke tests. |
| Full | `scripts/harness/validate.sh` | Runs quick check, frontend Bun install/build, Playwright route smoke, optional Helm checks, and opt-in Docker image smoke builds. |
@@ -327,9 +327,17 @@ No automatic hooks are installed in this phase. Manual reminders:
### Release Or Delivery Change
Use the existing release skill/workflow and `.gitea/workflows/` files. Harness
validation can smoke-check Helm and Docker locally, but it must not replace the
release process.
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`) 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.
## Implementation Notes
+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/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
+3 -1
View File
@@ -16,12 +16,14 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.80.1`
- `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 工作台支持流式多轮对话和本地会话,新增单摄手势控制与公共模型目录批量刷新 |
| `0.79.2` | improvement | `dev` | `v0.79.2` | 卫星目录支持紧凑传输、本地缓存和后台校验,改进桌面客户端启动时的窗口尺寸恢复 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.80.1",
"version": "0.80.3",
"private": true,
"packageManager": "bun@1",
"dependencies": {
@@ -90,7 +90,7 @@ export function DataTable<TData>({
const sorted = header.column.getIsSorted()
const stickyEnd = header.column.id === 'actions' || header.column.id === 'action'
return (
<th key={header.id} style={{ width: header.getSize() }} data-sticky-end={stickyEnd || undefined}>
<th key={header.id} style={{ width: header.getSize() }} data-column-id={header.column.id} data-sticky-end={stickyEnd || undefined}>
{header.isPlaceholder ? null : (
<button
type="button"
@@ -142,7 +142,7 @@ export function DataTable<TData>({
</td>
) : null}
{row.getVisibleCells().map((cell) => (
<td key={cell.id} data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}>
<td key={cell.id} data-column-id={cell.column.id} data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
@@ -7130,7 +7130,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const counts = objectAt(activeState?.raw, 'counts')
const countOf = (key: string) => (typeof counts[key] === 'number' ? counts[key] as number : null)
const scheduleOptions = [
{ value: '', label: '全部状态', count: countOf('all') },
{ value: '', label: '全部调度', count: countOf('all') },
{ value: 'true', label: '已启用', count: countOf('active') },
{ value: 'false', label: '已停用', count: countOf('inactive') },
]
+134 -29
View File
@@ -6,6 +6,12 @@
--an-page-padding: 16px;
--an-section-gap: 16px;
--an-panel-gap: 12px;
--an-control-xs: 28px;
--an-control-sm: 32px;
--an-control-md: 34px;
--an-control-lg: 38px;
--an-control-radius: 6px;
--an-control-radius-md: 7px;
--an-bg: #f6f8fb;
--an-surface: #ffffff;
--an-surface-alt: #f9fbfd;
@@ -1073,15 +1079,15 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
.an-toolbar > .tui-button {
align-self: stretch;
height: 34px;
height: var(--an-control-md);
}
.an-toolbar .an-status-pill {
align-self: stretch;
height: 34px;
height: var(--an-control-md);
min-width: 0;
padding: 0 12px;
border-radius: 7px;
border-radius: var(--an-control-radius-md);
line-height: 1;
}
@@ -2874,10 +2880,10 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
.an-input,
.an-select {
width: 100%;
height: 32px;
height: var(--an-control-sm);
min-width: 0;
border: 1px solid var(--an-border);
border-radius: 6px;
border-radius: var(--an-control-radius);
background: var(--an-surface);
color: var(--an-text);
padding: 0 10px;
@@ -3253,20 +3259,74 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
white-space: nowrap;
}
.an-data-table__selection-cell {
width: 42px;
min-width: 42px;
max-width: 42px;
.an-data-table th.an-data-table__selection-cell,
.an-data-table td.an-data-table__selection-cell {
width: 40px;
min-width: 40px;
max-width: 40px;
padding: 0;
text-align: center;
vertical-align: middle;
}
.an-data-table__selection-cell input {
width: 15px;
height: 15px;
margin: 0;
accent-color: var(--an-accent);
.an-data-table__selection-cell input[type='checkbox'] {
position: relative;
box-sizing: border-box;
appearance: none;
-webkit-appearance: none;
display: block;
width: 16px;
height: 16px;
margin: 0 auto;
border: 1.5px solid color-mix(in srgb, var(--an-muted) 56%, var(--an-border));
border-radius: 4px;
background: var(--an-surface);
cursor: pointer;
transition: border-color 0.14s ease, background 0.14s ease;
}
.an-data-table__selection-cell input[type='checkbox']:hover:not(:disabled) {
border-color: var(--an-accent);
}
.an-data-table__selection-cell input[type='checkbox']:checked,
.an-data-table__selection-cell input[type='checkbox']:indeterminate {
border-color: var(--an-accent);
background: var(--an-accent);
}
.an-data-table__selection-cell input[type='checkbox']:checked::after {
content: '';
position: absolute;
box-sizing: border-box;
left: 4px;
top: 1px;
width: 5px;
height: 9px;
border: solid #ffffff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.an-data-table__selection-cell input[type='checkbox']:indeterminate::after {
content: '';
position: absolute;
left: 3px;
top: 5.5px;
width: 7px;
height: 2px;
border-radius: 1px;
background: #ffffff;
}
.an-data-table__selection-cell input[type='checkbox']:focus-visible {
outline: 2px solid color-mix(in srgb, var(--an-accent) 78%, white);
outline-offset: 0;
}
.an-data-table__selection-cell input[type='checkbox']:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.an-data-table th {
@@ -3955,7 +4015,7 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
.an-filter-grid--datasources > .an-segmented--counted {
flex: 0 0 auto;
max-width: 100%;
height: 32px;
height: var(--an-control-sm);
}
.an-filter-grid--datasources > .an-field--inline-filter {
@@ -3963,25 +4023,32 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
min-width: 116px;
}
.an-filter-grid--datasources > .tui-button {
.an-filter-grid--datasources > .tui-button,
.an-filter-grid--datasources > .tui-button.tui-button--tactile {
flex: 0 0 auto;
width: var(--an-control-sm);
height: var(--an-control-sm);
border-radius: var(--an-control-radius);
box-shadow: none;
}
.an-segmented--counted button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
gap: 5px;
}
.an-segmented__count {
font-variant-numeric: tabular-nums;
font-size: 11px;
color: var(--an-muted);
font-size: 12px;
font-weight: 500;
color: color-mix(in srgb, var(--an-text) 56%, var(--an-muted));
}
.an-segmented--counted button.is-active .an-segmented__count {
color: var(--an-accent);
font-weight: 650;
}
.an-batch-bar {
@@ -4021,15 +4088,19 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
align-items: center;
}
.an-table-switch {
justify-content: center;
}
.an-table-actions {
gap: 2px;
justify-content: center;
}
.an-table-actions .tui-button--icon {
width: 28px;
height: 28px;
border-radius: 6px;
width: var(--an-control-xs);
height: var(--an-control-xs);
border-radius: var(--an-control-radius);
color: var(--an-muted);
}
@@ -4068,11 +4139,23 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
padding: 0 10px;
}
.an-data-table--datasources .an-data-table__selection-cell {
.an-data-table--datasources th.an-data-table__selection-cell,
.an-data-table--datasources td.an-data-table__selection-cell {
width: 40px;
min-width: 40px;
max-width: 40px;
padding: 0;
text-align: center;
}
.an-data-table--datasources th[data-column-id='schedule'],
.an-data-table--datasources td[data-column-id='schedule'] {
text-align: center;
}
.an-data-table--datasources th[data-column-id='schedule'] .an-data-table__sort {
justify-content: center;
cursor: default;
}
.an-data-table--datasources th[data-sticky-end='true'],
@@ -4573,29 +4656,51 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
.an-segmented {
height: 30px;
display: inline-flex;
align-items: stretch;
gap: 2px;
border: 1px solid var(--an-border);
border-radius: 6px;
border-radius: var(--an-control-radius);
padding: 2px;
background: var(--an-surface-alt);
background: color-mix(in srgb, var(--an-border) 34%, var(--an-surface-alt));
}
.admin-theme-root[data-theme='dark'] .an-segmented {
background: color-mix(in srgb, #000 28%, var(--an-surface-alt));
}
.an-segmented button {
min-width: 0;
border: 0;
border: 1px solid transparent;
background: transparent;
color: var(--an-muted);
color: color-mix(in srgb, var(--an-text) 68%, var(--an-muted));
border-radius: 4px;
padding: 0 10px;
font: inherit;
font-size: 13px;
font-weight: 500;
line-height: 1;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition: background 0.14s ease, color 0.14s ease, border-color 0.14s ease, box-shadow 0.14s ease;
}
.an-segmented button:hover:not(:disabled):not(.is-active) {
color: var(--an-text);
}
.an-segmented button.is-active {
background: var(--an-surface);
color: var(--an-text);
border: 1px solid var(--an-border);
font-weight: 600;
border-color: color-mix(in srgb, var(--an-border) 88%, transparent);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
}
.admin-theme-root[data-theme='dark'] .an-segmented button.is-active {
background: color-mix(in srgb, var(--an-surface) 92%, #ffffff);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
}
.an-segmented button:focus-visible {
@@ -4948,7 +5053,7 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
}
.an-filter-grid--datasources > .an-field--inline-filter {
flex: 1 1 calc(50% - 6px);
flex: 1 1 calc(42% - 6px);
min-width: 0;
}
@@ -169,7 +169,7 @@ body[data-admin-theme='dark'] .tui-tooltip {
.tui-switch {
width: var(--tui-control-width, 38px);
height: var(--tui-control-height, 20px);
border: 1px solid var(--tui-border-soft);
border: 1px solid var(--tui-border);
border-radius: var(--tui-control-radius, 8px);
margin: var(--tui-control-margin, 0);
padding: 2px;
@@ -178,9 +178,9 @@ body[data-admin-theme='dark'] .tui-tooltip {
justify-content: flex-start;
flex: 0 0 auto;
background: var(--tui-control-bg, linear-gradient(180deg, var(--tui-surface), var(--tui-surface-soft)));
box-shadow: var(--tui-control-shadow, 0 2px 5px rgba(15, 23, 42, 0.13), 0 8px 18px rgba(15, 23, 42, 0.07));
box-shadow: none;
cursor: pointer;
transition: border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease;
transition: border-color 0.16s ease, background 0.16s ease;
}
.tui-switch span {
@@ -188,7 +188,7 @@ body[data-admin-theme='dark'] .tui-tooltip {
height: 14px;
border-radius: 6px;
background: linear-gradient(180deg, #ffffff, #dbeafe);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.2);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.18);
transition: transform 0.18s ease, background 0.16s ease;
}
+1
View File
@@ -919,4 +919,5 @@ export const legacyUiTextEnUS: Record<string, string> = {
'重置筛选': 'Reset filters',
'操作': 'Actions',
'详情与统计': 'Details & stats',
'全部调度': 'All schedules',
}
+4 -4
View File
@@ -5372,7 +5372,7 @@ bundle_command() {
case "$target" in
-h|--help|help)
log_note "用法: ./planet.sh bundle [--win|--linux|--mac|--dir|--all]"
log_note "用法: ./planet.sh bundle [--win|--linux|--mac|--dir|--hotfix|--all]"
return 0
;;
"" )
@@ -5384,11 +5384,11 @@ bundle_command() {
target="--linux"
fi
;;
--win|--linux|--mac|--dir|--all)
--win|--linux|--mac|--dir|--hotfix|--all)
;;
*)
log_error "未知打包目标: ${target}"
printf "${DIM} %s${NC}\n" "支持: --win, --linux, --mac, --dir, --all" >&2
printf "${DIM} %s${NC}\n" "支持: --win, --linux, --mac, --dir, --hotfix, --all" >&2
exit 1
;;
esac
@@ -5418,7 +5418,7 @@ start / restart 可加 --no-build:仅使用本地已有镜像,缺少镜像
start 启动服务;默认启动 Web 全量前端;加 --admin 用轻量 Admin 容器替代 Vite,--admin-only 仅启动后端+Admin 容器,--no-frontend 不启动 Web
admin 单独管理 Admin 轻量容器: ./planet.sh admin {start|stop|restart|health|log}
earth 启动 Electron Earth 桌面端 (WSL2 优先拉起原生 Windows 客户端,加 --linux 强制 Linux)
bundle 打包跨平台独立客户端: ./planet.sh bundle {--win|--linux|--mac|--dir|--all}
bundle 打包跨平台独立客户端: ./planet.sh bundle {--win|--linux|--mac|--dir|--hotfix|--all}
deploy 生产编排管理: ./planet.sh deploy {up|down|restart|status|logs|init-env} [--split] [--no-build] [--env-file <path>]
backup 执行 PostgreSQL 滚动压缩备份: ./planet.sh backup [--mode full|core] [--retention-days 14]
migrate 数据库版本迁移: ./planet.sh migrate {status|upgrade|stamp <version>} [--container [name]]
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.80.1"
version = "0.80.3"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+23
View File
@@ -368,6 +368,23 @@ Backend/admin pages are compact single-screen workspaces (`一屏` / `首屏`):
- Do not scale font size with viewport width.
- Letter spacing should usually be `0`.
### Admin Control Design Contract (Mandatory Baseline)
- **Control Density Tiers**: `.admin-theme-root` defines and components reuse 4 explicit height/radius tiers so controls sharing a horizontal row stay optically flush and never cause row-height jumps when dynamic buttons mount or unmount (`heightDelta === 0`):
- `--an-control-xs` (`28px`, radius `6px`, `12px`/`500`, `14px` icon): table row `操作` icon buttons (`.an-table-actions .tui-button--icon`) and compact inline micro-actions.
- `--an-control-sm` (`32px`, radius `6px`, `13px`/`500` and `600` active, `14–15px` icon): filter-bar controls (segmented bars, `<select>`, `.an-input`, search box, filter-reset button), form fields, contextual batch bar, and table pagination. Any dynamic icon button inside a `32px` filter row must override `.tui-button--tactile`'s `34px` preset down to `--an-control-sm` (`box-shadow: none`).
- `--an-control-md` (`34px`, radius `7px`, `13px`/`650`, `15px` icon): page-header `.an-toolbar` buttons and status pills.
- `--an-control-lg` (`38px`, radius `7px`, `14px`/`650`, `16px` icon): auth / standalone emphasis primary buttons.
- **Button Hierarchy & Semantic Links**:
- At most one `primary` button per toolbar/panel; use `subtle` for secondary actions, `ghost` for table-row actions (resting muted tint, hover/focus `--an-danger` + `12%` red tint for destructive icons), and `danger` only for confirmation modals or emergency stop of active tasks.
- Drill-down sub-views and cross-page navigation inside detail inspectors must use semantic link controls (`.an-detail-link` with `>` / upper-right arrow cues), never crowded button strips.
- **Filter Bars, Segmented Controls, Switches, Checkboxes & Tables**:
- Filter toolbars use wrap-safe Flexbox (`flex-wrap: wrap; align-items: center`) with `min-width`-bounded inputs/selects rather than rigid grid tracks that crush controls on mobile/zoom.
- `.an-segmented button` reserves a `1px solid transparent` idle border (preventing `1px` active-state jitter), maintains distinct trough contrast in light and dark themes, and renders counts in `12px` `tabular-nums`.
- Binary scheduling/setting switches keep the rounded-square `.tui-switch` geometry (`38×20px`, `8px`/`6px` radius, `1px solid var(--tui-border)` rim, `box-shadow: none`), centered under matching `data-column-id` table headers.
- Table selection checkboxes declare high-specificity `.an-data-table th/td.an-data-table__selection-cell` centering inside `40px` cells; table action columns carry an explicit centered header (`操作` / `Actions`) and unpin sticky-end on `<=760px` mobile; detail panels show at most one status pill per entity.
- Enforced statically by `scripts/harness/frontend-rules-check.sh` (`check_admin_control_design_contract`) and visually/geometrically by `scripts/harness/frontend-smoke.mjs`.
### Earth HUD Baseline & Creative Space (Shell Unified, Interior Expressive)
Earth HUD cards and floating panels follow **“壳层统一、内景自由”**: align outer shell, liquid-glass material, shared controls, and focus/pin mechanics so new features feel native to the HUD, while keeping interior visualizations and domain layouts open to creative design.
@@ -651,6 +668,12 @@ 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 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.
### Verify
+71
View File
@@ -692,6 +692,76 @@ def check_connection_test_input_pattern() -> None:
fail("WebSearch Base URL field must expose a disabled-aware connection test through inputAction")
def check_admin_control_design_contract() -> None:
admin_css = read_text("frontend/src/admin/styles.css")
tactile_css = read_text("frontend/src/components/tactile-ui/styles.css")
data_table_tsx = read_text("frontend/src/admin/components/data-table/DataTable.tsx")
theme_root = css_block_for_selector(admin_css, ".admin-theme-root")
for token in ("--an-control-xs", "--an-control-sm", "--an-control-md", "--an-control-radius"):
if theme_root is None or not css_has_declaration(theme_root[1], token, r"[^;]+"):
fail(f"frontend/src/admin/styles.css: .admin-theme-root must define Admin control token {token}")
selection_block = css_block_for_selector(
admin_css,
".an-data-table th.an-data-table__selection-cell",
)
if selection_block is None:
fail(
"frontend/src/admin/styles.css: table selection cells must declare "
".an-data-table th.an-data-table__selection-cell / td.an-data-table__selection-cell "
"so centering beats generic td rules"
)
else:
line_no, body = selection_block
if not css_has_declaration(body, "text-align", r"center"):
fail(
f"frontend/src/admin/styles.css:{line_no}: selection cell rule must declare text-align: center"
)
filter_reset_block = css_block_for_selector(
admin_css,
".an-filter-grid--datasources > .tui-button.tui-button--tactile",
)
if filter_reset_block is None or not css_has_declaration(
filter_reset_block[1],
"height",
r"(?:var\(--an-control-sm\)|32px)",
):
fail(
"frontend/src/admin/styles.css: .an-filter-grid--datasources > .tui-button.tui-button--tactile "
"must lock height to var(--an-control-sm) so filter reset never shifts row height"
)
segmented_btn = css_block_for_selector(admin_css, ".an-segmented button")
if segmented_btn is None or not css_has_declaration(
segmented_btn[1],
"border",
r"1px\s+solid\s+transparent",
):
fail(
"frontend/src/admin/styles.css: .an-segmented button must reserve 1px solid transparent "
"border to prevent active-state jitter"
)
switch_blocks = [
body
for _line_no, selector, body in iter_css_blocks(tactile_css)
if ".tui-switch" in [item.strip() for item in selector.split(",")]
]
if not switch_blocks or not any(css_has_declaration(body, "box-shadow", r"none") for body in switch_blocks):
fail(
"frontend/src/components/tactile-ui/styles.css: .tui-switch must declare box-shadow: none "
"for shadowless table/form clarity"
)
if "data-column-id={header.column.id}" not in data_table_tsx or "data-column-id={cell.column.id}" not in data_table_tsx:
fail(
"frontend/src/admin/components/data-table/DataTable.tsx: th and td must expose data-column-id "
"for column-level alignment rules"
)
def check_uiux_static_warnings() -> None:
viewport_font_pattern = re.compile(r"\b(?:font-size|fontSize)\s*[:=]\s*[^;\n}]*(?:vw|vmin|vmax|cqw|cqi)")
letter_spacing_pattern = re.compile(r"\b(?:letter-spacing|letterSpacing)\s*[:=]\s*([^;\n}]+)")
@@ -976,6 +1046,7 @@ def main() -> None:
check_connection_test_input_pattern()
check_admin_shell_height_chain()
check_admin_header_and_focus_safety()
check_admin_control_design_contract()
check_earth_hud_baseline()
check_earth_icon_consistency()
check_uiux_static_warnings()
+40 -4
View File
@@ -1744,6 +1744,38 @@ async function runDatasourceSchedulingChecks(browser, failures, consoleErrors) {
await enableSwitch.first().waitFor({ state: 'visible' })
assert.equal(await page.getByRole('button', { name: '触发全部' }).count(), 0, 'idle datasources toolbar must not show redundant trigger-all button')
assert.equal(await page.locator('thead th', { hasText: '操作' }).count(), 1, 'datasources table must label its actions column')
const filterHeightBefore = await page.evaluate(() => Math.round(document.querySelector('.an-filter-grid--datasources')?.getBoundingClientRect().height || 0))
await page.locator('.an-segmented--counted button', { hasText: '已启用' }).click()
await page.getByRole('button', { name: '重置筛选' }).waitFor({ state: 'visible' })
const filterMetricsDirty = await page.evaluate(() => {
const grid = document.querySelector('.an-filter-grid--datasources')?.getBoundingClientRect()
const seg = document.querySelector('.an-filter-grid--datasources > .an-segmented--counted')?.getBoundingClientRect()
const sel = document.querySelector('.an-filter-grid--datasources select')?.getBoundingClientRect()
const resetBtn = document.querySelector('.an-filter-grid--datasources > button')?.getBoundingClientRect()
return {
gridH: grid ? Math.round(grid.height) : 0,
segH: seg ? Math.round(seg.height) : 0,
selH: sel ? Math.round(sel.height) : 0,
resetH: resetBtn ? Math.round(resetBtn.height) : 0,
}
})
assert.equal(filterMetricsDirty.gridH, filterHeightBefore, 'mounting filter reset button must not change filter row height')
assert.equal(filterMetricsDirty.segH, 32, 'segmented filter control must stay 32px tall')
assert.equal(filterMetricsDirty.selH, 32, 'filter select control must stay 32px tall')
assert.equal(filterMetricsDirty.resetH, 32, 'filter reset button must stay 32px tall')
await page.getByRole('button', { name: '重置筛选' }).click()
const alignment = await page.evaluate(() => {
const cb = document.querySelector('thead th.an-data-table__selection-cell input')?.getBoundingClientRect()
const cell = document.querySelector('thead th.an-data-table__selection-cell')?.getBoundingClientRect()
const schedTh = document.querySelector('thead th[data-column-id="schedule"]')?.getBoundingClientRect()
const schedSwitch = document.querySelector('tbody td[data-column-id="schedule"] [role="switch"]')?.getBoundingClientRect()
return {
checkboxDelta: cb && cell ? Math.abs((cb.left - cell.left) - (cell.right - cb.right)) : null,
scheduleDelta: schedTh && schedSwitch ? Math.abs(((schedTh.left + schedTh.right) / 2) - ((schedSwitch.left + schedSwitch.right) / 2)) : null,
}
})
assert.ok(alignment.checkboxDelta !== null && alignment.checkboxDelta <= 1.5, `selection checkbox must be centered, got delta=${alignment.checkboxDelta}`)
assert.ok(alignment.scheduleDelta !== null && alignment.scheduleDelta <= 1.5, `schedule switch must align with header center, got delta=${alignment.scheduleDelta}`)
const listRequestsBeforeToggle = listRequests
await enableSwitch.first().click()
await page.locator('.an-toast--success').first().waitFor({ state: 'visible' })
@@ -2008,11 +2040,13 @@ async function runEarthNewsRefreshChecks(browser, failures) {
await frame.waitForFunction(() => !document.getElementById('news-refresh')?.disabled, null, { timeout: 5000 })
assert.equal(await buttonsAreReady(), true, 'retry did not restore refresh buttons')
await checkNoFrameworkOverlay(page, 'earth manual news refresh lifecycle')
await page.close()
smokeProgress('earth mobile news refresh')
await page.setViewportSize(mobileViewport)
await page.goto(urlFor('/earth'), { waitUntil: 'domcontentloaded' })
const mobileFrame = await getEarthFrame(page, 'earth mobile news refresh')
const mobilePage = await context.newPage()
await mobilePage.setViewportSize(mobileViewport)
await mobilePage.goto(urlFor('/earth'), { waitUntil: 'domcontentloaded' })
const mobileFrame = await getEarthFrame(mobilePage, 'earth mobile news refresh')
await mobileFrame.waitForFunction(() => (
document.getElementById('mobile-news-board-list')?.children.length > 0
), null, { timeout: SMOKE_RENDER_TIMEOUT_MS })
@@ -2035,7 +2069,7 @@ async function runEarthNewsRefreshChecks(browser, failures) {
const mobileStatus = await mobileFrame.evaluate(() => document.getElementById('mobile-news-board-status')?.innerText || '')
assert.ok(mobileStatus.includes('态势新闻已刷新'), 'mobile refresh did not show completed status')
assert.deepEqual(runtimeErrors, [], 'news refresh emitted uncaught page errors')
await checkNoFrameworkOverlay(page, 'earth mobile news refresh')
await checkNoFrameworkOverlay(mobilePage, 'earth mobile news refresh')
} catch (error) {
failures.push(formatSmokeError(error))
} finally {
@@ -2666,6 +2700,8 @@ async function main() {
failures.push(formatSmokeError(error))
}
await context.close()
await runAuthenticatedAdminChecks(browser, failures, consoleErrors, {
label: 'desktop',
viewport: desktopViewport,
+376 -1
View File
@@ -5,7 +5,7 @@ import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack
from contextlib import ExitStack, contextmanager, redirect_stdout
from pathlib import Path
from unittest.mock import patch
@@ -13,6 +13,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import production_deploy as deploy
import production_registry as registry
import production_release as publisher
import release_publish as publish
import release_scope as scope
def hotfix(tag):
@@ -235,5 +237,378 @@ class ImageTests(unittest.TestCase):
registry.release_bundle(release, tag)
class ScopedReleaseTests(unittest.TestCase):
def test_classify_changed_paths_scopes_independently(self):
admin_only = scope.classify_changed_paths(
["frontend/src/admin/styles.css", "docs/CHANGELOG.md", "rules.md"]
)
self.assertEqual(admin_only.services, ("admin",))
self.assertEqual(admin_only.client_mode, "none")
self.assertEqual(admin_only.components, ("admin",))
backend_only = scope.classify_changed_paths(["backend/app/api/v1/datasources.py"])
self.assertEqual(backend_only.services, ("backend",))
self.assertEqual(backend_only.client_mode, "none")
provider_only = scope.classify_changed_paths(["aiprovider/main.py"])
self.assertEqual(provider_only.services, ("aiprovider",))
self.assertEqual(provider_only.client_mode, "none")
hotfix_only = scope.classify_changed_paths(["frontend/public/earth/js/main.js"])
self.assertEqual(hotfix_only.services, ())
self.assertEqual(hotfix_only.client_mode, "hotfix")
self.assertEqual(hotfix_only.components, ("earth-hotfix",))
cards_manifest = scope.classify_changed_paths(
["frontend/public/earth/assets/cards/manifest.json"]
)
self.assertEqual(cards_manifest.services, ("backend",))
self.assertEqual(cards_manifest.client_mode, "hotfix")
shell_release = scope.classify_changed_paths(["client/src/main/index.ts", "frontend/src/admin/styles.css"])
self.assertEqual(shell_release.services, ("admin",))
self.assertEqual(shell_release.client_mode, "full")
docs_only = scope.classify_changed_paths(["docs/HARNESS.md", "scripts/harness/doctor.sh"])
self.assertEqual(docs_only.services, ())
self.assertEqual(docs_only.client_mode, "none")
self.assertEqual(docs_only.components, ("metadata",))
tooling_only = scope.classify_changed_paths(
["planet.sh", "client/scripts/dist-target.mjs", "client/tests/update.test.ts"]
)
self.assertEqual(tooling_only.services, ())
self.assertEqual(tooling_only.client_mode, "none")
self.assertEqual(tooling_only.components, ("metadata",))
after_pack = scope.classify_changed_paths(["client/scripts/after-pack.cjs"])
self.assertEqual(after_pack.client_mode, "full")
def test_scope_override_and_previous_stable_tag(self):
self.assertEqual(
scope.previous_stable_tag("v0.80.2", ["v0.79.9", "v0.80.0", "v0.80.1", "v0.80.2", "v1.0.0-rc1"]),
"v0.80.1",
)
parsed = scope.parse_scope_override("backend,admin")
self.assertEqual(parsed.services, ("backend", "admin"))
self.assertEqual(parsed.client_mode, "none")
hotfix_override = scope.parse_scope_override("hotfix")
self.assertEqual(hotfix_override.services, ())
self.assertEqual(hotfix_override.client_mode, "hotfix")
def test_ensure_images_scoped_reuses_unchanged_pins_and_select_packages_modes(self):
prev_pins = {
"aiprovider": "gitea.rclaw.top/linkong/planet/aiprovider:v1.0.0@sha256:" + "1" * 64,
"backend": "gitea.rclaw.top/linkong/planet/backend:v1.0.0@sha256:" + "2" * 64,
"admin": "gitea.rclaw.top/linkong/planet/admin:v1.0.0@sha256:" + "3" * 64,
}
new_admin = "gitea.rclaw.top/linkong/planet/admin:v1.1.0@sha256:" + "4" * 64
with (
tempfile.TemporaryDirectory() as temp,
patch.object(publisher, "resolve_image", side_effect=[None, new_admin]),
patch.object(publisher.subprocess, "run") as run,
):
pins = publisher.ensure_images(
Path(temp),
"v1.1.0",
"a" * 40,
services=("admin",),
previous_services=prev_pins,
)
run.assert_called_once()
self.assertEqual(pins["aiprovider"], prev_pins["aiprovider"])
self.assertEqual(pins["backend"], prev_pins["backend"])
self.assertEqual(pins["admin"], new_admin)
root = Path(temp)
self.assertEqual(publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="none"), [])
bundle = root / "planet-earth-bundle-1.1.0.tar.gz"
bundle.write_bytes(hotfix("v1.1.0"))
self.assertEqual(
publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="hotfix"),
[bundle],
)
self.assertEqual(
publisher.select_packages(root, "v1.1.0", (".zip", ".tar.gz"), client_mode="full"),
[],
)
def test_admin_only_deploy_restarts_only_admin_and_skips_hotfix(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()] + ["LIMIT=500m"]) + "\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 = []
with (
patch.object(deploy, "read_url", return_value=json.dumps({"tag_name": "v1.1.0", "draft": False, "prerelease": False}).encode()),
patch.object(deploy, "tag_commit", return_value="f" * 40),
patch.object(deploy, "release_manifest", return_value=manifest),
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") as docker_mock,
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") as routes_mock,
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",)])
self.assertEqual(docker_mock.call_count, 1)
self.assertIn(new_admin, docker_mock.call_args.args)
routes_mock.assert_called_once()
rollout_mock.assert_called_once()
hotfix_mock.assert_not_called()
check_hotfix_mock.assert_not_called()
self.assertEqual(live_manifest.read_bytes(), original_live)
def test_earth_hotfix_only_deploy_preserves_shell_version_and_skips_containers(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}",
}
bundle_data = hotfix("v1.1.0")
bundle_sha = hashlib.sha256(bundle_data).hexdigest()
manifest = {
"schema_version": 1,
"tag": "v1.1.0",
"commit": "f" * 40,
"previous_tag": "v1.0.0",
"components": ["earth-hotfix"],
"changed_services": [],
"services": old_refs,
"client": {"mode": "hotfix", "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()] + ["CLIENT_UPDATE_PUBLISH_TOKEN=tok"]
) + "\n"
)
live_manifest = base / "manifest.json"
live_manifest.write_bytes(b"{}")
with (
patch.object(deploy, "read_url", return_value=json.dumps({"tag_name": "v1.1.0", "draft": False, "prerelease": False}).encode()),
patch.object(deploy, "tag_commit", return_value="f" * 40),
patch.object(deploy, "release_manifest", return_value=manifest),
patch.object(deploy, "resolved_images", return_value=old_refs),
patch.object(deploy, "release_bundle", return_value=("planet-earth-bundle-1.1.0.tar.gz", bundle_data, bundle_sha)),
patch.object(deploy, "inspect", side_effect=lambda name: {"Config": {"Image": old_refs[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") as docker_mock,
patch.object(deploy, "backup_database", side_effect=lambda p: p.write_bytes(b"ok")),
patch.object(deploy, "rollout_services") 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)
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):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / "Planet-0.80.1.exe").write_bytes(b"exe")
(root / "Planet-0.80.1.AppImage").write_bytes(b"appimage")
(root / "planet-earth-bundle-0.80.1.tar.gz").write_bytes(hotfix("v0.80.1"))
out = io.StringIO()
with redirect_stdout(out):
rc = publish.main(
["--tag", "v0.80.1", "--scope", "hotfix", "--assets-dir", str(root), "--dry-run"]
)
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()
+172 -56
View File
@@ -9,6 +9,7 @@ import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
@@ -26,7 +27,11 @@ if __package__:
SERVICES,
read_url,
release_bundle,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
)
@@ -39,7 +44,11 @@ else:
SERVICES,
read_url,
release_bundle,
release_by_tag,
release_manifest,
resolve_image,
resolve_release_manifest_oci,
resolve_service_ref,
tag_commit,
version,
)
@@ -167,9 +176,10 @@ def stage_config(host, previous, tag):
return target
def rollout_services(host, tag, images):
def rollout_services(host, tag, images, services=None):
directory = host.directory(tag)
for name in SERVICES:
targets = tuple(SERVICES) if services is None else tuple(services)
for name in targets:
print(f"Starting {name} from {images[name]}", flush=True)
docker(
"compose",
@@ -293,12 +303,17 @@ def rollback(host):
pending = host.state / "pending"
journal = json.loads((pending / "release.json").read_text())
previous = journal["previous"]
client_mode = journal.get("client_mode", "full")
print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True)
manifest = Path(journal["manifest"])
old = pending / "previous-manifest.json"
before = old.read_bytes() if old.exists() else None
current = manifest.read_bytes() if manifest.exists() else None
if current != before:
if client_mode == "none":
raise RuntimeError(
"Hotfix manifest changed independently; preserved the transaction for review"
)
bundle = json.loads(current or b"{}").get("bundle") or {}
if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]:
raise RuntimeError(
@@ -309,11 +324,18 @@ def rollback(host):
sync_directory(manifest.parent)
else:
atomic_file(manifest, before, 0o644)
set_images(host, journal["old_images"])
rollout_services(host, previous, journal["old_images"])
old_images = journal["old_images"]
rolled_services = [
name for name in SERVICES if inspect(name)["Config"]["Image"] != old_images[name]
]
set_images(host, old_images)
if not rolled_services or set(rolled_services) == set(SERVICES):
rollout_services(host, previous, old_images)
else:
rollout_services(host, previous, old_images, services=rolled_services)
point_current(host, previous)
check_routes()
if before:
if before and client_mode != "none":
old_manifest = json.loads(before)
bundle = old_manifest.get("bundle")
if bundle:
@@ -326,33 +348,64 @@ def rollback(host):
print(f"Rollback to {previous} verified", flush=True)
def resolved_images(tag, commit):
def resolved_images(tag, commit, manifest=None):
images = {}
if manifest is None:
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
return images
changed_services = set(manifest.get("changed_services") or [])
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
pinned = manifest["services"][service]
if service in changed_services:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
if ref != pinned:
raise ValueError(f"{service}:{tag} digest does not match release manifest")
images[service] = ref
else:
images[service] = resolve_service_ref(service, pinned)
return images
def deploy(host, release, previous, tag, images, commit):
name, data, sha = release_bundle(release, tag)
minimum = minimum_shell(data, tag)
def deploy(host, release, previous, tag, images, commit, *, manifest=None):
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
client_info = (manifest or {}).get("client") or {}
if client_mode == "none":
name, data, sha = None, None, None
minimum = None
shell_version = client_info.get("shell_version")
else:
name, data, sha = release_bundle(release, tag)
minimum = client_info.get("min_shell_version") or minimum_shell(data, tag)
shell_version = client_info.get("shell_version") or tag[1:]
settings = env_settings(host)
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if not token:
raise RuntimeError("Production hotfix publisher credential is missing")
old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()}
for service, ref in images.items():
docker("pull", "--platform", "linux/amd64", ref)
changed_services = [service for service in SERVICES if images[service] != old_images[service]]
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if client_mode != "none" and not token:
raise RuntimeError("Production hotfix publisher credential is missing")
for service in changed_services:
docker("pull", "--platform", "linux/amd64", images[service])
for service in SERVICES:
if inspect(service)["Config"]["Image"] != old_images[service]:
raise RuntimeError("Running image differs from the host configuration: " + service)
stage_config(host, previous, tag)
manifest = live_manifest_path()
bundle_path = manifest.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
manifest_file = live_manifest_path()
if client_mode != "none":
bundle_path = manifest_file.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
original_stores = data_containers()
save_journal(
host,
@@ -360,38 +413,104 @@ def deploy(host, release, previous, tag, images, commit):
tag=tag,
previous=previous,
old_images=old_images,
manifest=str(manifest),
manifest=str(manifest_file),
sha=sha,
client_mode=client_mode,
commit=commit,
),
manifest,
manifest_file,
)
try:
set_images(host, images)
rollout_services(host, tag, images)
if changed_services:
set_images(host, images)
if set(changed_services) == set(SERVICES):
rollout_services(host, tag, images)
else:
rollout_services(host, tag, images, services=changed_services)
check_routes()
if data_containers() != original_stores:
raise RuntimeError("PostgreSQL or Redis container identity changed")
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
assets=[(archive, sha)],
min_shell_version=minimum,
)
check_hotfix(tag, sha)
if client_mode != "none":
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
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,
)
check_hotfix(tag, sha, shell_version=shell_version)
point_current(host, tag)
finish_journal(host, "last-success")
except Exception as exc:
print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True)
rollback(host)
raise
print(f"Deployed {tag} at {commit}", flush=True)
print(
f"Deployed {tag} at {commit} (services={','.join(changed_services) or 'none'}, client={client_mode})",
flush=True,
)
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):
@@ -400,21 +519,13 @@ def reconcile(host, *, check=False, retry=False):
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
@@ -424,10 +535,14 @@ def reconcile(host, *, check=False, retry=False):
):
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
return
images = resolved_images(tag, commit)
images = resolved_images(tag, commit, manifest=manifest)
if check:
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
client_mode = (manifest.get("client") or {}).get("mode", "full") if manifest else "full"
sha = None
shell_version = (manifest or {}).get("client", {}).get("shell_version") if manifest else tag[1:]
if client_mode != "none":
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
if tag == previous:
for name, ref in images.items():
container = inspect(name)
@@ -437,10 +552,11 @@ def reconcile(host, *, check=False, retry=False):
):
raise RuntimeError("Active service differs from the release: " + name)
check_routes()
check_hotfix(tag, sha)
if client_mode != "none":
check_hotfix(tag, sha, shell_version=shell_version)
print(f"Verified {tag} at {commit}; active release {previous}", flush=True)
return
deploy(host, release, previous, tag, images, commit)
deploy(host, release, previous, tag, images, commit, manifest=manifest)
def main():
+117 -13
View File
@@ -14,6 +14,9 @@ SERVER = "https://gitea.rclaw.top"
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",
@@ -36,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:
@@ -69,8 +75,8 @@ def tag_commit(tag):
return commit
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
def _verified_release_asset(release, tag, name, *, limit, label):
"""Download and verify a release asset against SHA256SUMS.txt."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
@@ -78,25 +84,100 @@ def release_bundle(release, tag):
sizes = {entry["name"]: entry["size"] for entry in assets}
if len(assets) != len(sizes):
raise ValueError("Duplicate release attachment names")
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
base = f"{SERVER}/{REPO}/releases/download/{tag}"
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
raise ValueError("Release has no complete Earth bundle and checksum list")
if not 0 < sizes.get(name, 0) <= limit or "SHA256SUMS.txt" not in sizes:
raise ValueError(f"Release has no complete {label} and checksum list")
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
data = read_url(f"{base}/{name}", limit=sizes[name])
sha = hashlib.sha256(data).hexdigest()
if hashes != [sha] or len(data) != sizes[name]:
raise ValueError("Earth bundle failed release SHA-256 or size verification")
raise ValueError(f"{label} failed release SHA-256 or size verification")
return name, data, sha
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
return _verified_release_asset(release, tag, name, limit=32 * 1024 * 1024, label="Earth bundle")
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:
raise ValueError("Release manifest tag differs from the published release")
services = manifest.get("services")
if not isinstance(services, dict) or set(services.keys()) != set(SERVICES.keys()):
raise ValueError("Release manifest must pin all production service images")
client = manifest.get("client")
if not isinstance(client, dict) or client.get("mode") not in ("none", "hotfix", "full"):
raise ValueError("Release manifest has an invalid client mode")
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) + ":"
if not isinstance(ref, str) or not ref.startswith(prefix) or "@" not in ref:
raise ValueError(f"Invalid image reference for {service}: {ref!r}")
ref_tag, ref_digest = ref[len(prefix) :].split("@", 1)
version(ref_tag)
if not re.fullmatch(r"sha256:[a-f0-9]{64}", ref_digest):
raise ValueError(f"Invalid image digest for {service}: {ref!r}")
resolved = resolve_image(service, ref_tag, tag_commit(ref_tag))
if resolved != ref:
raise ValueError(f"{service} image reference differs from registry ({resolved!r} != {ref!r})")
return resolved
def image_name(service):
if service not in SERVICES:
raise ValueError(f"Unexpected production service: {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()
@@ -108,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"}
)
@@ -150,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)
+224 -20
View File
@@ -16,24 +16,42 @@ from pathlib import Path
if __package__:
from .production_registry import (
API,
MANIFEST_NAME,
REPO,
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,
)
from .release_scope import resolve_release_scope
else:
from production_registry import (
API,
MANIFEST_NAME,
REPO,
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,
)
from release_scope import resolve_release_scope
def git(*args, cwd=None):
@@ -58,8 +76,19 @@ def docker_config():
)
def ensure_images(source, tag, commit):
def ensure_images(source, tag, commit, *, services=None, previous_services=None):
target_services = set(SERVICES if services is None else services)
resolved_pins = {}
for service in SERVICES:
if service not in target_services:
prev_ref = (previous_services or {}).get(service)
if not prev_ref:
raise RuntimeError(
f"Cannot reuse unchanged {service} image without a verified previous release pin"
)
resolved_pins[service] = prev_ref
print(f"Reused {prev_ref}", flush=True)
continue
pin = resolve_image(service, tag, commit)
if not pin:
context = source / "frontend" if service == "admin" else source
@@ -103,10 +132,14 @@ def ensure_images(source, tag, commit):
pin = resolve_image(service, tag, commit)
if not pin:
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
resolved_pins[service] = pin
print(f"Verified {pin}", flush=True)
return resolved_pins
def select_packages(directory, tag, suffixes):
def select_packages(directory, tag, suffixes, *, client_mode="full"):
if client_mode == "none":
return []
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
paths = (
[
@@ -117,15 +150,22 @@ def select_packages(directory, tag, suffixes):
if directory.is_dir()
else []
)
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
):
return []
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
if not bundle.is_file():
return []
if client_mode == "full":
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
):
return []
elif client_mode == "hotfix":
paths = [bundle]
else:
raise ValueError(f"Unsupported client_mode: {client_mode!r}")
with tarfile.open(bundle, "r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
@@ -155,12 +195,15 @@ def package_hash(path):
return hashlib.file_digest(stream, "sha256").hexdigest()
def cached_packages(source, supplied, cache, tag, suffixes):
def cached_packages(source, supplied, cache, tag, suffixes, *, client_mode="full"):
if client_mode == "none":
return []
if not cache.exists():
if supplied is None:
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
bundle_flag = "--hotfix" if client_mode == "hotfix" else "--all"
subprocess.run(["./planet.sh", "bundle", bundle_flag], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes)
packages = select_packages(supplied, tag, suffixes, client_mode=client_mode)
if not packages:
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
@@ -171,21 +214,139 @@ def cached_packages(source, supplied, cache, tag, suffixes):
sums = {p.name: package_hash(p) for p in stage.iterdir()}
(stage / "checksums.json").write_text(json.dumps(sums))
os.rename(stage, cache)
packages = select_packages(cache, tag, suffixes)
packages = select_packages(cache, tag, suffixes, client_mode=client_mode)
expected = json.loads((cache / "checksums.json").read_text())
if not packages or {p.name: package_hash(p) for p in packages} != expected:
raise ValueError("The saved release artifacts differ from the original build")
return packages
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
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)
for service, ref in manifest["services"].items()
}
client = manifest.get("client") or {}
return pins, client.get("shell_version"), client.get("min_shell_version")
pins = {}
for service in SERVICES:
pin = resolve_image(service, previous_tag, prev_commit)
if not pin:
raise RuntimeError(f"Missing {service}:{previous_tag} image in previous release")
pins[service] = pin
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"
bundle_path = next((p for p in packages if p.name == bundle_name), None)
if scope.client_mode == "full":
resolved_shell = ver
resolved_min_shell = ver
else:
resolved_shell = shell_version or ver
resolved_min_shell = min_shell_version or resolved_shell
return {
"schema_version": 1,
"tag": tag,
"commit": commit,
"previous_tag": scope.previous_tag,
"components": list(scope.components),
"changed_services": list(scope.services),
"services": dict(service_refs),
"client": {
"mode": scope.client_mode,
"shell_version": resolved_shell,
"min_shell_version": resolved_min_shell,
"bundle": bundle_path.name if bundle_path else None,
"bundle_sha256": package_hash(bundle_path) if bundle_path else None,
},
}
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False):
def prepare(tag, assets_dir, suffixes, *, already_published=False, scope_override=None):
version(tag)
commit = verified_tag(tag)
scope = resolve_release_scope(tag, commit, override=scope_override)
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
state = state / "planet-releases" / tag / "publisher"
state.mkdir(mode=0o700, parents=True, exist_ok=True)
cache = state / commit
cache_key = f"{commit}-{scope.client_mode}"
cache = state / cache_key
prev_services = {}
prev_shell_version = None
prev_min_shell_version = None
if len(scope.services) < len(SERVICES) or scope.client_mode != "full":
if scope.previous_tag:
prev_services, prev_shell_version, prev_min_shell_version = resolve_previous_release_state(
scope.previous_tag
)
elif len(scope.services) < len(SERVICES):
raise RuntimeError("No previous stable release found to reuse unchanged services")
with (
local_release_lock(state / "lock"),
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
@@ -195,15 +356,58 @@ def prepare(tag, assets_dir, suffixes, *, already_published=False):
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
)
try:
ensure_images(worktree, tag, commit)
service_refs = ensure_images(
worktree,
tag,
commit,
services=scope.services,
previous_services=prev_services,
)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
staged_packages = []
for package in cached_packages(
worktree,
assets_dir,
cache,
tag,
suffixes,
client_mode=scope.client_mode,
):
dest = stage / package.name
try:
os.link(package, stage / package.name)
os.link(package, dest)
except OSError:
shutil.copy2(package, stage / package.name)
shutil.copy2(package, dest)
staged_packages.append(dest)
manifest = build_release_manifest(
tag,
commit,
scope,
service_refs,
staged_packages,
shell_version=prev_shell_version,
min_shell_version=prev_min_shell_version,
)
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():
+83 -11
View File
@@ -148,7 +148,8 @@ def collect_release_assets(assets_dir: Path) -> list[tuple[Path, str]]:
(
entry
for entry in assets_dir.iterdir()
if entry.is_file() and entry.name.lower().endswith(ASSET_SUFFIXES)
if entry.is_file()
and (entry.name.lower().endswith(ASSET_SUFFIXES) or entry.name == "release-manifest.json")
),
key=lambda p: p.name,
)
@@ -297,6 +298,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
default="",
help="Optional X-Client-Update-Token matching CLIENT_UPDATE_PUBLISH_TOKEN on backend",
)
parser.add_argument(
"--scope",
default="auto",
help="Release scope: auto, full, none, or comma-separated components (aiprovider,backend,admin,hotfix,client-shell)",
)
return parser.parse_args(argv)
@@ -438,6 +444,7 @@ def publish_hotfix_bundle(
release_html_url: str,
assets: list[tuple[Path, str]],
min_shell_version: str | None = None,
shell_version: str | None = None,
) -> None:
hotfix_tar = next(
(
@@ -452,6 +459,8 @@ def publish_hotfix_bundle(
return
version = tag.lstrip("vV")
resolved_shell = shell_version or version
resolved_min_shell = min_shell_version or resolved_shell
endpoint = f"{publish_url.rstrip('/')}/api/v1/client/updates/bundle"
proc = subprocess.run(
[
@@ -473,9 +482,9 @@ def publish_hotfix_bundle(
"--form-string",
f"version={version}",
"--form-string",
f"min_shell_version={min_shell_version or version}",
f"min_shell_version={resolved_min_shell}",
"--form-string",
f"shell_version={version}",
f"shell_version={resolved_shell}",
"--form-string",
f"shell_download_url={release_html_url}",
"--form-string",
@@ -520,14 +529,56 @@ def main(argv: list[str] | None = None) -> int:
assets_dir = Path(args.assets_dir or "client/release")
if args.dry_run:
if __package__:
from .production_release import select_packages
from .release_scope import resolve_release_scope
else:
from production_release import select_packages
from release_scope import resolve_release_scope
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
commit_ref = args.tag
try:
commit_ref = subprocess.check_output(
["git", "rev-parse", "--verify", f"{args.tag}^{{commit}}"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
try:
commit_ref = subprocess.check_output(
["git", "rev-parse", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
commit_ref = "HEAD"
scope = resolve_release_scope(args.tag, commit_ref, override=args.scope)
if scope.client_mode == "none":
assets = []
else:
selected = (
select_packages(assets_dir, args.tag, ASSET_SUFFIXES, client_mode=scope.client_mode)
if assets_dir.is_dir()
else []
)
assets = [(path, compute_sha256(path)) for path in sorted(selected, key=lambda p: p.name)]
if not assets:
print(
f"error: no distributable assets matching client_mode={scope.client_mode} found in {assets_dir}",
file=sys.stderr,
)
return 1
print(f"server: {server}")
print(f"repo: {repo}")
print(f"tag: {args.tag}")
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)}")
for path, sha in assets:
@@ -537,10 +588,10 @@ def main(argv: list[str] | None = None) -> int:
try:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle
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
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)
@@ -559,9 +610,30 @@ def main(argv: list[str] | None = None) -> int:
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
supplied = assets_dir if args.assets_dir else None
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
with prepare(
args.tag,
supplied,
ASSET_SUFFIXES,
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:
release_bundle(public, args.tag)
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:
notes = extract_release_notes(changelog, args.tag)
+303
View File
@@ -0,0 +1,303 @@
"""Classify repository changes into scoped Planet release targets."""
from __future__ import annotations
import json
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
VALID_SERVICES = ("aiprovider", "backend", "admin")
VALID_CLIENT_MODES = ("none", "hotfix", "full")
CLIENT_MODE_RANK = {"none": 0, "hotfix": 1, "full": 2}
METADATA_EXACT = frozenset(
{
"AGENTS.md",
"CODEMAP.md",
"README.md",
"VERSION",
".editorconfig",
".gitattributes",
".gitignore",
"project_context.md",
"rules.md",
}
)
METADATA_PREFIXES = (
".codex/",
".gitea/",
".github/",
"client/tests/",
"docs/",
"scripts/harness/",
)
RELEASE_TOOLING_FILES = frozenset(
{
"client/scripts/dist-target.mjs",
"planet.sh",
"scripts/production_deploy.py",
"scripts/production_registry.py",
"scripts/production_release.py",
"scripts/release_publish.py",
"scripts/release_scope.py",
}
)
BACKEND_RUNTIME_FILES = frozenset(
{
"pyproject.toml",
"uv.lock",
"config/earth-boundary-pov-policy.china-v1.json",
"resources/earth/boundary-pov-geometry.china-v1.json",
"scripts/build_earth_boundary_china_pov_geojson.py",
"scripts/build_earth_boundary_pmtiles.py",
"scripts/db_migrate.py",
"scripts/earth_boundary_policy.py",
}
)
VERSION_ONLY_FILES = frozenset(
{
"client/package.json",
"frontend/package.json",
"pyproject.toml",
"uv.lock",
}
)
EARTH_CARDS_MANIFEST = "frontend/public/earth/assets/cards/manifest.json"
@dataclass(frozen=True)
class ReleaseScope:
"""Resolved container build targets and desktop client delivery mode."""
services: tuple[str, ...]
client_mode: str
components: tuple[str, ...]
previous_tag: str | None = None
changed_paths: tuple[str, ...] = ()
def to_dict(self) -> dict[str, object]:
return {
"services": list(self.services),
"client_mode": self.client_mode,
"components": list(self.components),
"previous_tag": self.previous_tag,
"changed_paths": list(self.changed_paths),
}
def _git(args: list[str], cwd: Path | None = None) -> str:
return subprocess.check_output(["git", *args], cwd=cwd, text=True)
def _git_show(revision: str, path: str, cwd: Path | None = None) -> str | None:
try:
return _git(["show", f"{revision}:{path}"], cwd=cwd)
except subprocess.CalledProcessError:
return None
def _parse_stable_version(tag: str) -> tuple[int, int, int] | None:
match = re.fullmatch(r"v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", tag.strip())
if not match:
return None
return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
def previous_stable_tag(tag: str, tags: Iterable[str]) -> str | None:
"""Return the highest stable release tag strictly lower than ``tag``."""
target = _parse_stable_version(tag)
if target is None:
return None
candidates: list[tuple[tuple[int, int, int], str]] = []
for raw in tags:
ver = _parse_stable_version(raw)
if ver is not None and ver < target:
candidates.append((ver, raw.strip()))
if not candidates:
return None
candidates.sort()
return candidates[-1][1]
def _normalize_package_json(raw: str) -> object | None:
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
if not isinstance(data, dict):
return None
return {k: v for k, v in data.items() if k != "version"}
def _normalize_pyproject(raw: str) -> str:
return re.sub(r'(?m)^version\s*=\s*["\'][^"\']*["\']\s*$', "version = <NORMALIZED>", raw)
def _normalize_uv_lock(raw: str) -> str:
return re.sub(
r'(\[\[package\]\]\s*\nname\s*=\s*"planet"\s*\nversion\s*=\s*)"[^"]+"',
r'\1"<NORMALIZED>"',
raw,
count=1,
)
def is_version_only_change(prev_ref: str, commit: str, path: str, cwd: Path | None = None) -> bool:
"""Return True when a version-bearing manifest only bumped the root Planet version."""
if path not in VERSION_ONLY_FILES:
return False
before = _git_show(prev_ref, path, cwd=cwd)
after = _git_show(commit, path, cwd=cwd)
if before is None or after is None:
return False
if path in ("client/package.json", "frontend/package.json"):
norm_before = _normalize_package_json(before)
norm_after = _normalize_package_json(after)
return norm_before is not None and norm_before == norm_after
if path == "pyproject.toml":
return _normalize_pyproject(before) == _normalize_pyproject(after)
if path == "uv.lock":
return _normalize_uv_lock(before) == _normalize_uv_lock(after)
return False
def _is_metadata_or_tooling(path: str) -> bool:
return (
path in METADATA_EXACT
or path in RELEASE_TOOLING_FILES
or any(path.startswith(prefix) for prefix in METADATA_PREFIXES)
)
def _derive_components(services: set[str], client_mode: str) -> tuple[str, ...]:
ordered: list[str] = [svc for svc in VALID_SERVICES if svc in services]
if client_mode == "hotfix":
ordered.append("earth-hotfix")
elif client_mode == "full":
ordered.append("client-shell")
if not ordered:
ordered.append("metadata")
return tuple(ordered)
def classify_changed_paths(
paths: Iterable[str],
*,
previous_tag: str | None = None,
) -> ReleaseScope:
"""Classify changed repository paths into service image builds and client mode."""
normalized_paths = tuple(
sorted({p.strip().lstrip("./").replace("\\", "/") for p in paths if p and p.strip()})
)
services: set[str] = set()
client_mode = "none"
for path in normalized_paths:
if _is_metadata_or_tooling(path):
continue
if path.startswith("aiprovider/"):
services.add("aiprovider")
continue
if path.startswith(("backend/", "alembic/")) or path in BACKEND_RUNTIME_FILES:
services.add("backend")
continue
if path.startswith("frontend/public/earth/"):
if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]:
client_mode = "hotfix"
if path == EARTH_CARDS_MANIFEST:
services.add("backend")
continue
if path.startswith("frontend/"):
services.add("admin")
continue
if path.startswith("client/"):
client_mode = "full"
continue
# Infra/compose/root or unknown paths fall back to rebuilding all services safely.
services.update(VALID_SERVICES)
ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services)
return ReleaseScope(
services=ordered_services,
client_mode=client_mode,
components=_derive_components(services, client_mode),
previous_tag=previous_tag,
changed_paths=normalized_paths,
)
def parse_scope_override(raw: str | None, *, previous_tag: str | None = None) -> ReleaseScope | None:
"""Parse an explicit ``--scope`` value, or return None for auto-detection."""
if raw is None:
return None
text = raw.strip().lower()
if not text or text == "auto":
return None
if text == "full":
return ReleaseScope(
services=VALID_SERVICES,
client_mode="full",
components=_derive_components(set(VALID_SERVICES), "full"),
previous_tag=previous_tag,
)
services: set[str] = set()
client_mode = "none"
for token in (part.strip() for part in text.split(",") if part.strip()):
if token in VALID_SERVICES:
services.add(token)
elif token in ("hotfix", "earth", "earth-hotfix"):
if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]:
client_mode = "hotfix"
elif token in ("client", "client-shell", "desktop"):
client_mode = "full"
elif token in ("none", "metadata", "docs"):
continue
else:
raise ValueError(
f"Unsupported release scope token {token!r}; expected auto, full, none, "
"aiprovider, backend, admin, hotfix, or client-shell"
)
ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services)
return ReleaseScope(
services=ordered_services,
client_mode=client_mode,
components=_derive_components(services, client_mode),
previous_tag=previous_tag,
)
def resolve_release_scope(
tag: str,
commit: str,
*,
override: str | None = None,
cwd: Path | None = None,
) -> ReleaseScope:
"""Determine scoped release targets from git history unless explicitly overridden."""
all_tags = _git(["tag", "--list", "v*"], cwd=cwd).splitlines()
prev_tag = previous_stable_tag(tag, all_tags)
explicit = parse_scope_override(override, previous_tag=prev_tag)
if explicit is not None:
return explicit
if prev_tag is None:
return ReleaseScope(
services=VALID_SERVICES,
client_mode="full",
components=_derive_components(set(VALID_SERVICES), "full"),
previous_tag=None,
)
raw_paths = _git(["diff", "--name-only", f"{prev_tag}..{commit}"], cwd=cwd).splitlines()
effective_paths = [
path
for path in raw_paths
if path.strip() and not is_version_only_change(prev_tag, commit, path.strip(), cwd=cwd)
]
return classify_changed_paths(effective_paths, previous_tag=prev_tag)
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.80.1"
version = "0.80.3"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },