forked from longtao.wu/droboticflow
Merge pull request '🧭 会话开始时只读检查分支是否落后 dev、是否包含线上版本' (#61) from codex/branch-freshness-check-20261027 into dev
This commit is contained in:
commit
6282fe4de9
8
.scratch/branch-freshness-check/work.md
Normal file
8
.scratch/branch-freshness-check/work.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Read-only branch freshness check at session start
|
||||
|
||||
Goal: warn before work starts when the checkout is behind origin/dev or lacks the commit a live Fanyu deployment runs
|
||||
Agent: Claude Code (desktop session, 2026-10-27)
|
||||
Base: claude/reviewer-dashboard-20261027 @ 27156708 (PR #60, the live release line; user asked to stack on it so the PR lands after #60)
|
||||
Scope: scripts/local/branch-freshness.sh, tests/release/test_branch_freshness.py, one AGENTS.md line
|
||||
Out of scope: release.py, agent_status.py, any cluster write, deleting branches
|
||||
Risk: tooling only; reads git and `kubectl get deploy` with a short timeout, never writes
|
||||
@ -4,6 +4,7 @@
|
||||
|
||||
- This repository directory is the single working root; the sibling `~/Desktop/fanyu` folder is legacy and will be retired.
|
||||
- Cluster kubeconfig (`fanyu.conf`), BOS credential CSV, downloaded captures, and the local workspace mount are being migrated under this repo's untracked local data path (see `docs/HANDOFF.md` § 0 for the live layout).
|
||||
- Before reading code to explain production behavior or starting changes, run `bash scripts/local/branch-freshness.sh` (read-only). If it reports the checkout is behind `origin/dev` or missing a live build commit, tell the user and work in a separate worktree based on the live commit instead of the stale checkout.
|
||||
|
||||
## Engineering Principles
|
||||
|
||||
|
||||
109
scripts/local/branch-freshness.sh
Executable file
109
scripts/local/branch-freshness.sh
Executable file
@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env bash
|
||||
# 分支新鲜度检查(只读,会话开始时运行:bash scripts/local/branch-freshness.sh)
|
||||
#
|
||||
# 对比当前检出与 origin/dev、Fanyu 线上 API/切片处理器/Worker 的 build commit,
|
||||
# 落后或不包含线上版本时提示。只更新远端跟踪引用,不改分支、文件或集群;
|
||||
# 任何失败都只降级为提示,始终以 0 退出,不阻断会话。
|
||||
#
|
||||
# 可选环境变量:
|
||||
# FRESHNESS_BASE_REF 对比基线(默认 origin/dev)
|
||||
# FRESHNESS_SKIP_FETCH=1 不拉取远端引用
|
||||
# FRESHNESS_SKIP_CLUSTER=1 不查询线上版本
|
||||
# FRESHNESS_CACHE_TTL 线上版本号缓存秒数(默认 1800)
|
||||
# FRESHNESS_CACHE_FILE / FRESHNESS_KUBECONFIG / FRESHNESS_KUBECTL 测试或本机覆盖
|
||||
|
||||
set -u
|
||||
|
||||
# macOS 没有 timeout 命令;用 perl alarm 给网络调用设上限。
|
||||
with_timeout() {
|
||||
local seconds=$1
|
||||
shift
|
||||
perl -e 'alarm shift; exec @ARGV' "$seconds" "$@"
|
||||
}
|
||||
|
||||
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "分支新鲜度检查:当前目录不是 git 仓库,跳过。"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
common_dir=$(git rev-parse --path-format=absolute --git-common-dir)
|
||||
main_root=$(dirname "$common_dir")
|
||||
base_ref=${FRESHNESS_BASE_REF:-origin/dev}
|
||||
cache_file=${FRESHNESS_CACHE_FILE:-$main_root/local-data/.cache/live-build-commits.txt}
|
||||
cache_ttl=${FRESHNESS_CACHE_TTL:-1800}
|
||||
kubeconfig=${FRESHNESS_KUBECONFIG:-$main_root/local-data/fanyu.conf}
|
||||
kubectl_bin=${FRESHNESS_KUBECTL:-kubectl}
|
||||
namespace=droboticflow-fanyu
|
||||
deployments="droboticflow-api droboticflow-annotation-processor droboticflow-worker"
|
||||
|
||||
branch=$(git branch --show-current)
|
||||
[ -n "${branch}" ] || branch="(detached $(git rev-parse --short HEAD))"
|
||||
warnings=()
|
||||
notes=()
|
||||
|
||||
# 1. 与基线分支对比
|
||||
if [ "${FRESHNESS_SKIP_FETCH:-}" != "1" ] && [ "${base_ref}" = "origin/dev" ]; then
|
||||
if ! with_timeout 8 git fetch --quiet origin dev >/dev/null 2>&1; then
|
||||
notes+=("未能联网拉取 origin/dev,以下按本地已有引用对比。")
|
||||
fi
|
||||
fi
|
||||
if git rev-parse --verify --quiet "${base_ref}^{commit}" >/dev/null; then
|
||||
behind=$(git rev-list --count "HEAD..${base_ref}")
|
||||
ahead=$(git rev-list --count "${base_ref}..HEAD")
|
||||
if [ "${behind}" -gt 0 ]; then
|
||||
warnings+=("当前分支 ${branch} 落后 ${base_ref} ${behind} 个提交(领先 ${ahead} 个)。")
|
||||
fi
|
||||
else
|
||||
notes+=("本地没有 ${base_ref},未对比基线分支。")
|
||||
fi
|
||||
|
||||
# 2. 与线上 build commit 对比(缓存,避免每次会话都访问集群)
|
||||
live=""
|
||||
if [ "${FRESHNESS_SKIP_CLUSTER:-}" = "1" ]; then
|
||||
notes+=("未查询线上版本(FRESHNESS_SKIP_CLUSTER=1)。")
|
||||
else
|
||||
if [ -s "$cache_file" ]; then
|
||||
age=$(perl -e 'print time - (stat shift)[9]' "$cache_file")
|
||||
[ "$age" -lt "$cache_ttl" ] && live=$(cat "$cache_file")
|
||||
fi
|
||||
if [ -z "$live" ] && [ -f "$kubeconfig" ] && command -v "$kubectl_bin" >/dev/null 2>&1; then
|
||||
fetched=""
|
||||
for deployment in $deployments; do
|
||||
commit=$(with_timeout 6 "$kubectl_bin" --kubeconfig "$kubeconfig" -n "$namespace" get deploy "${deployment}" \
|
||||
-o 'jsonpath={.spec.template.spec.containers[0].env[?(@.name=="DROBOTICFLOW_BUILD_COMMIT")].value}' 2>/dev/null) || commit=""
|
||||
if [ -z "$commit" ]; then
|
||||
fetched=""
|
||||
break
|
||||
fi
|
||||
fetched+="${deployment} $commit"$'\n'
|
||||
done
|
||||
if [ -n "$fetched" ]; then
|
||||
live=$fetched
|
||||
mkdir -p "$(dirname "$cache_file")" && printf '%s' "$live" >"$cache_file"
|
||||
fi
|
||||
fi
|
||||
if [ -z "$live" ]; then
|
||||
notes+=("线上版本未知(集群不可达或无本机凭据)。")
|
||||
else
|
||||
while read -r deployment commit; do
|
||||
[ -n "${deployment}" ] || continue
|
||||
short=${commit:0:8}
|
||||
if ! git cat-file -e "$commit^{commit}" 2>/dev/null; then
|
||||
warnings+=("本地没有线上提交 ${short}(${deployment}),请先拉取对应分支再判断。")
|
||||
elif ! git merge-base --is-ancestor "$commit" HEAD; then
|
||||
warnings+=("当前分支不包含线上 ${deployment} 的版本 ${short}。")
|
||||
fi
|
||||
done <<<"$live"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. 输出
|
||||
if [ ${#warnings[@]} -gt 0 ]; then
|
||||
echo "⚠ 分支新鲜度检查(${branch}):"
|
||||
for line in "${warnings[@]}"; do echo " - ${line}"; done
|
||||
echo " 读代码、诊断线上问题或改动前,请在包含线上版本的独立工作区进行,并告知用户。"
|
||||
else
|
||||
echo "分支新鲜度检查:${branch} 已是最新(包含 ${base_ref} 与线上版本)。"
|
||||
fi
|
||||
for line in ${notes[@]+"${notes[@]}"}; do echo " · ${line}"; done
|
||||
exit 0
|
||||
124
tests/release/test_branch_freshness.py
Normal file
124
tests/release/test_branch_freshness.py
Normal file
@ -0,0 +1,124 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[2] / 'scripts/local/branch-freshness.sh'
|
||||
|
||||
|
||||
class BranchFreshness(unittest.TestCase):
|
||||
"""The session-start check is read-only, never blocks, and flags stale checkouts."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
self.repo = self.root / 'repo'
|
||||
self.repo.mkdir()
|
||||
self.git('init', '-q', '-b', 'work')
|
||||
self.git('config', 'user.name', 'Local test')
|
||||
self.git('config', 'user.email', 'test@example.invalid')
|
||||
self.commit('baseline')
|
||||
self.git('branch', 'dev-sim')
|
||||
self.calls = self.root / 'kubectl-calls'
|
||||
self.kubectl = self.root / 'kubectl'
|
||||
self.write_kubectl(exit_code=0)
|
||||
(self.root / 'kubeconfig').write_text('fake')
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def git(self, *args, cwd=None):
|
||||
return subprocess.check_output(['git', *args], cwd=cwd or self.repo, text=True, stderr=subprocess.DEVNULL).strip()
|
||||
|
||||
def commit(self, message):
|
||||
(self.repo / 'file').write_text(message)
|
||||
self.git('add', '.')
|
||||
self.git('commit', '-qm', message)
|
||||
return self.git('rev-parse', 'HEAD')
|
||||
|
||||
def write_kubectl(self, exit_code, commit=''):
|
||||
# Prints the build commit for any deployment and counts invocations.
|
||||
self.kubectl.write_text(f'#!/bin/bash\necho x >> "{self.calls}"\n'
|
||||
f'[ {exit_code} -eq 0 ] || exit {exit_code}\n'
|
||||
f'echo -n "${{FAKE_LIVE_COMMIT:-{commit}}}"\n')
|
||||
self.kubectl.chmod(self.kubectl.stat().st_mode | stat.S_IEXEC)
|
||||
|
||||
def run_check(self, live='', cwd=None, **extra):
|
||||
env = {**os.environ,
|
||||
'FRESHNESS_BASE_REF': 'dev-sim',
|
||||
'FRESHNESS_SKIP_FETCH': '1',
|
||||
'FRESHNESS_KUBECTL': str(self.kubectl),
|
||||
'FRESHNESS_KUBECONFIG': str(self.root / 'kubeconfig'),
|
||||
'FRESHNESS_CACHE_FILE': str(self.root / 'cache.txt'),
|
||||
'FAKE_LIVE_COMMIT': live,
|
||||
**extra}
|
||||
result = subprocess.run(['bash', str(SCRIPT)], cwd=cwd or self.repo, env=env, text=True, capture_output=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def kubectl_calls(self):
|
||||
return len(self.calls.read_text().splitlines()) if self.calls.exists() else 0
|
||||
|
||||
def test_current_checkout_reports_up_to_date(self):
|
||||
live = self.git('rev-parse', 'HEAD')
|
||||
out = self.run_check(live=live)
|
||||
self.assertIn('已是最新', out)
|
||||
self.assertNotIn('⚠', out)
|
||||
|
||||
def test_behind_base_branch_is_flagged_with_count(self):
|
||||
live = self.git('rev-parse', 'HEAD')
|
||||
self.git('checkout', '-q', 'dev-sim')
|
||||
self.commit('dev one')
|
||||
self.commit('dev two')
|
||||
self.git('checkout', '-q', 'work')
|
||||
out = self.run_check(live=live)
|
||||
self.assertIn('⚠', out)
|
||||
self.assertIn('落后 dev-sim 2 个提交', out)
|
||||
|
||||
def test_missing_live_commit_is_flagged_per_deployment(self):
|
||||
self.git('checkout', '-q', '-b', 'release')
|
||||
live = self.commit('live fix')
|
||||
self.git('checkout', '-q', 'work')
|
||||
out = self.run_check(live=live)
|
||||
self.assertIn('⚠', out)
|
||||
self.assertIn('不包含线上', out)
|
||||
self.assertIn('droboticflow-api', out)
|
||||
self.assertIn(live[:8], out)
|
||||
|
||||
def test_live_commit_not_fetched_locally_is_reported(self):
|
||||
out = self.run_check(live='0123456789abcdef0123456789abcdef01234567')
|
||||
self.assertIn('本地没有线上提交', out)
|
||||
|
||||
def test_unreachable_cluster_never_blocks(self):
|
||||
self.write_kubectl(exit_code=1)
|
||||
out = self.run_check()
|
||||
self.assertIn('线上版本未知', out)
|
||||
|
||||
def test_live_commits_are_cached_within_ttl(self):
|
||||
live = self.git('rev-parse', 'HEAD')
|
||||
self.run_check(live=live)
|
||||
first = self.kubectl_calls()
|
||||
self.assertEqual(first, 3)
|
||||
self.write_kubectl(exit_code=1)
|
||||
out = self.run_check(live=live)
|
||||
self.assertEqual(self.kubectl_calls(), first, 'cached result must not query the cluster again')
|
||||
self.assertIn('已是最新', out)
|
||||
self.run_check(live=live, FRESHNESS_CACHE_TTL='0')
|
||||
self.assertGreater(self.kubectl_calls(), first, 'expired cache must refresh')
|
||||
|
||||
def test_cluster_query_can_be_disabled(self):
|
||||
out = self.run_check(FRESHNESS_SKIP_CLUSTER='1')
|
||||
self.assertEqual(self.kubectl_calls(), 0)
|
||||
self.assertIn('未查询线上版本', out)
|
||||
|
||||
def test_outside_git_checkout_exits_quietly(self):
|
||||
outside = self.root / 'plain'
|
||||
outside.mkdir()
|
||||
out = self.run_check(cwd=outside)
|
||||
self.assertIn('不是 git 仓库', out)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
x
Reference in New Issue
Block a user