🧭 Enforce dev mainline and release identity
Some checks are pending
web-ci / checks (push) Waiting to run
web-ci / pool-search-mongo (push) Waiting to run

This commit is contained in:
Codex 2026-11-10 01:35:25 -08:00
parent 7a1231c7c6
commit 0040988fe9
7 changed files with 162 additions and 69 deletions

View File

@ -2,7 +2,7 @@
## Working Root
- The repository root is `/Users/d-robotics/Desktop/fanyu/droboticflow`. Until the main checkout's 19 local-only commits and untracked work are reconciled, the default unified development worktree is `local-data/worktrees/recent-integration`; never reset or switch branches in the main checkout without a dedicated recovery plan.
- The repository root is `/Users/d-robotics/Desktop/fanyu/droboticflow`. The unified development checkout is `local-data/worktrees/recent-integration` on `dev`. The main checkout and existing unmerged worktrees retain protected work; do not reset, switch or discard them as part of routine development.
- Cluster kubeconfig (`fanyu.conf`), BOS credential CSV, downloaded captures, and the local workspace mount live under this repo's untracked `local-data/` directory; `~/Desktop/fanyu` still holds legacy copies (`fanyu.conf`, `泛宇-aksk.csv`) and is being retired (see `docs/HANDOFF.md` § 0).
- 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`, missing a live build commit, or only locally compared without remote/live confirmation, tell the user and work in a worktree that contains the live commit instead of a stale checkout.
@ -32,17 +32,15 @@ These principles guide implementation choices. Specific business contracts and t
- Before assuming a remote target, inspect the remote URL with credentials redacted (`git remote -v | sed -E 's#//[^@/[[:space:]]+@#//<redacted>@#g'`). Never print raw credential-bearing `.git/config` URLs into logs or reports; prefer migrating Git credentials to the system Keychain.
- After making code or documentation changes for the user, stage only the files changed for that task. Do not stage or commit unrelated user changes already present in the working tree.
- Commit with an English, emoji-prefixed commit message.
- **Push and PR each require explicit user authorization (or a combined "push and create PR" authorization); approving only one does not implicitly authorize the other.** Default action after commit: stay local. When push is approved, push only the authorized task/feature branch (`<agent>/<slug>`); never push `dev`, `poc`, or another agent's branch directly. When a branch is ready for review, report its local status and wait for the user's explicit instruction on pushing and/or opening a PR.
- Choose worktree isolation by parallel conflict and impact scope, not line count:
- Read-only Q&A, code audits, and diagnosis do not create a worktree or `.scratch/<slug>/work.md`.
- Follow-up fixes and small adjustments within an already-authorized task or unified worktree may stay in the current worktree.
- New independent features or changes that risk parallel conflict start from the latest `origin/dev` in a dedicated worktree under `local-data/worktrees/<slug>` named `<agent>/<slug>` (or build on another unmerged branch when requested by the user, recorded as `Base:` in `.scratch/<slug>/work.md`). Never switch branches in the main checkout. Follow `docs/agents/branch-workflow.md` for task cards, status reporting, and safe cleanup.
- `dev` is the single integration and release mainline. Reuse the unified `dev` checkout for normal authorized work. Create a branch or worktree only when the user explicitly requests it; record its purpose and merge-back plan first. Read-only diagnosis creates neither.
- Existing unmerged branches and uncommitted work remain untouched until the user requests their integration or disposal. Completed branches are cleaned only after their commits are in `origin/dev`, their work is preserved, and no service uses the worktree. Follow `docs/agents/branch-workflow.md` for synchronization and cleanup.
- Push and PR each require explicit user authorization. An explicit request to synchronize remote `dev` authorizes that bounded fast-forward push; it does not authorize a deployment or unrelated pending changes. Never force-push or rewrite `dev` history. Otherwise commit locally and report the state.
- When a task ends, run `python3 scripts/agent_status.py --no-fetch` (or with fetch if network/remote checks are needed) and report the branch's local state to the user.
## Release Workflow
- For release preparation, deployment, rollback, or resuming release work, read `docs/release/README.md` first and run `python3 scripts/release.py status <release-id>` when a record exists. Follow the recorded state and evidence; a successful rollout alone is not business acceptance.
- Deploy only commits contained in `origin/dev`. When the user approves deploying an unmerged branch for an urgent fix, name the branch in the approval request and in `--purpose`, and open its PR to `dev` the same day.
- Every new release must use exactly the synchronized local `dev` and remote `origin/dev` tip at release time. Integrate and verify fixes on `dev` before preparing a release; unmerged-branch releases have no exception. `scripts/release.py` checks both refs during prepare and refreshes `origin/dev` again before deployment. Existing release records and unchanged components retain their historical identities; later development may advance `dev` beyond the deployed version.
- Fanyu image releases use `scripts/release.py` (`scripts/deploy-k8s.sh` blocks Fanyu). Configuration changes or migrations outside its supported scope require a separately reviewed plan and the corresponding user authorization.
## Credentials

View File

@ -1,73 +1,30 @@
# Branch workflow for parallel agents
# Dev mainline workflow
Several agents work on this repository at once. Every task branch must answer three questions
without anyone reading its history: what it is for, what it was built on, and whether it
has reached `dev`. Git answers the last two; the task card answers the first.
Effective 2026-11-10, replacing the previous automatic task-branch/worktree workflow.
## When to create a dedicated worktree
## Daily work
Choose isolation by parallel conflict risk and impact scope, not by line count:
1. Use `local-data/worktrees/recent-integration` on `dev`. Preserve the main checkout's local-only work and existing unmerged worktrees.
2. Inspect the working tree and run `bash scripts/local/branch-freshness.sh`. Fetch and compare `dev` with `origin/dev` before starting; retain concurrent edits and resolve divergence explicitly.
3. Complete one authorized task at a time in the unified checkout. Stage only that task's changes, verify its scope, and commit with an English emoji-prefixed message.
4. Push only with explicit authorization. A request to synchronize remote `dev` permits the corresponding fast-forward push. PR creation and deployment remain separately authorized actions. Never force-push or truncate `dev` history.
- **Read-only Q&A, code audits, and diagnosis**: stay in the current checkout; do not create a worktree or `.scratch/<slug>/work.md`.
- **Follow-up fixes and small adjustments within an already-authorized task or unified worktree** (such as `local-data/worktrees/recent-integration`): continue in the existing worktree and update its task card scope if needed.
- **New independent tasks or changes that risk parallel conflict**: create a dedicated worktree from `origin/dev`.
New branches and worktrees require the user's explicit request. Before creating one, record its purpose, base, owner, file scope and merge-back plan in `.scratch/<slug>/work.md`. An independent feature or parallel agent is not implicit permission to create another branch. Existing unmerged branches stay frozen until integration or disposal is requested.
## Starting an isolated task
## Release identity
```sh
git fetch origin
git worktree add --no-track -b <agent>/<slug> local-data/worktrees/<slug> origin/dev
```
Every new release commit must equal both `refs/heads/dev` and `refs/remotes/origin/dev`. A detached build checkout is allowed only at that exact commit. An ancestor of `dev`, an unmerged feature tip or a local-only commit is not a release candidate.
- `<agent>` is the tool's usual prefix (`codex`, `claude`, ...). `<slug>` is a short topic
without a date, and is the same slug as `.scratch/<slug>/`.
- Start from `origin/dev`. To build on an unmerged branch, the user must ask for it. Its
PR then contains that branch's commits too, so say so in the PR description.
- Keep `--no-track`: without it the new branch tracks the remote branch it started from,
and a later `git push` could land there. When the user authorizes pushing, push with
`git push -u origin <agent>/<slug>`.
`scripts/release.py prepare` compares the local refs without network access. `deploy` refreshes `origin/dev` and repeats the comparison before any cluster read or write. A changed or unreachable remote blocks deployment. Complete the remaining checks, immutable image provenance and explicit deployment approval in [the release workflow](../release/README.md).
## Task card
Freeze the selected `dev` tip for the release window. If it changes before deployment, prepare and approve a new candidate. Components not included in that release keep their recorded versions. A later development commit may advance `dev`; historical verification does not require the old deployment to equal today's tip.
The first commit on a new task branch adds `.scratch/<slug>/work.md`. Keep it short. Do not
record status in it: `scripts/agent_status.py` derives status from git.
## Cleanup
```md
# <one-line title>
- Preserve all unmerged commits, dirty worktrees, running services and release/recovery evidence. Branch age alone does not make work disposable.
- Delete a merged local branch only after it is no longer checked out. `python3 scripts/agent_status.py --prune` checks containment in `origin/dev` and never deletes unmerged branches.
- For an authorized remote cleanup, verify the actual remote tip is contained in `origin/dev`. Preserve remote counterparts of local unmerged/dirty work. Use the observed tip as a deletion lease so concurrent work cannot be deleted.
- Before removing a merged worktree, preserve its ignored artifacts and release ledger, check dependency links and running-process working directories, then remove it through Git. Do not delete unaccepted release evidence or dependency directories still used by another checkout.
- Keep [the recent changes summary](../recent-changes.md) to ten application changes. Preserve complete Git history and authoritative ADR, release and verification evidence; the summary is not a history-retention limit.
Goal: what the user asked for, in one line
Agent: tool and session that owns the branch
Base: origin/dev @ <short sha> (or the unmerged branch the user chose, and why)
Scope: modules or files this task may change
Out of scope: related work deliberately left out
Risk: API, data, delivery-format or deployment impact; "display only" when none
```
Update `Scope`, `Out of scope` and `Risk` when the plan changes. The card merges into `dev`
with the work and stays as the record of why the change was made.
## Ending a task
1. Run `python3 scripts/agent_status.py` (or `--no-fetch` when offline). It lists for each
branch the commits ahead of and behind `dev`, unpushed commits, a missing card, stale work,
and the newest deployed release with whether its commit is in `dev`.
2. **Do not push or open a PR without the user's explicit authorization.** Report the branch's
local state and tell the user when it is ready. The user may authorize pushing and creating
a PR together in one instruction ("push and create PR") or authorize only one of them;
approving only one never implicitly authorizes the other. When push is authorized, push only
the authorized task branch (`<agent>/<slug>`, never `dev` or `poc`).
3. Only clean up a worktree after verifying all four conditions: its commits are merged into
`origin/dev`, the working tree has no uncommitted or untracked work to keep, no running dev
service (Vite / Go API) occupies it, and any release records under `local-data/releases/`
(especially `deployed_pending_acceptance`) have been copied to the main checkout's
`local-data/releases/`. Then remove the worktree and run `python3 scripts/agent_status.py --prune`
(which deletes only local branches whose commits are all in `origin/dev` and that no worktree
has checked out).
## Release records
`scripts/release.py` writes its ledger under the checkout it runs from, so records are
spread across worktrees. `agent_status.py` reads all of them. Do not delete a worktree that
holds an unaccepted release record, unmerged recovery materials, or active services.
Tests: `python3 -m unittest discover -s tests/agents -p 'test_*.py'`.
At delivery, run `python3 scripts/agent_status.py --no-fetch` and report local/remote `dev`, pending work and cleanup counts. Push, PR and cluster-write approvals continue to follow `AGENTS.md`.

18
docs/recent-changes.md Normal file
View File

@ -0,0 +1,18 @@
# 最近 10 项应用改动
盘点时间:2026-11-10。线上 API/处理器为 `7a1231c7`,本次已同步进本地和远端 `dev`。本次主线治理不计入应用改动;下面按提交时间列出最近十项,完整 Git 历史保留。
| 提交 | 改动 | 盘点状态 |
| --- | --- | --- |
| `404e40c0` | 释放尚未执行业务的前置锁;数据库繁忙时保留原送检作业并有界重试 | 未合入 dev;保留原分支 |
| `d1dc4a38` | 保护失败送检输入、返工工作区及正式标注修订,阻止空白切片生成清空数据 | 未合入 dev;保留原分支 |
| `1ba3a0a6` | 管理员任务池批量读取关联元数据,减少查询往返 | 未合入 dev;保留原分支 |
| `ae52e5d4` | 优化验收池检索、显示信息读取及相同在途查询合并 | 未合入 dev;保留原分支 |
| `7a1231c7` | 将反向检索限定为任务池可达的来源记录 | 已在线上并进入 dev |
| `0fd7e367` | 保留任务池标签与总数之间的空格 | 已在线上并进入 dev |
| `ca25f984` | 调整统计读压测以匹配任务池真实刷新节奏 | 已进入线上源历史和 dev |
| `88526258` | 优化任务池读取及限定范围的统计查询 | 已进入线上源历史和 dev |
| `4170c74b` | 修复验收切换舍弃切片后字幕未恢复 | 已进入线上源历史和 dev |
| `faa44932` | 在已确认租约内重试暂时失败的审查心跳 | 已进入线上源历史和 dev |
此表不代表未合入改动已获部署或业务验收。未合并分支、未提交 UI 工作和历史发布证据保留;新问题的排查结论不等于已完成代码修复。

View File

@ -1,5 +1,11 @@
# 泛宇发布试行流程
## Dev 主线约束(2026-11-10)
发布只使用发布时本地 `dev` 与远端 `origin/dev` 完全一致的提交,取消未合并分支紧急发布例外。先把修复合入主线、完成验证,再准备发布;不能用“提交已被 dev 包含”代替 tip 一致。日常工作与清理按[主线流程](../agents/branch-workflow.md)执行。
`prepare` 离线校验候选与两个本地引用一致;`deploy` 在访问集群前先拉取远端 `dev` 并再次校验。远端不可达、任一 dev 引用不同、候选已落后均阻断,不提供绕过开关。部署授权、镜像来源、迁移审查及业务验收要求保持原有流程。历史发布记录仍可读取与核验,未更新组件保持其原版本;后续开发可使 dev 领先于线上。
日常开发按[分层验证流程](../agents/verification.md)执行,不在每次编辑后重复本发布流程。
本页发布门禁及 `fanyu-policy.json` 保持独立;快速检查报告不能作为缺失发布证据的替代。

View File

@ -57,6 +57,14 @@ def source():
'dirty': bool(run(['git', 'status', '--porcelain', '--untracked-files=normal']).strip())}
def require_mainline(commit, *, refresh=False):
if refresh:
run(['git', 'fetch', '--quiet', 'origin', 'dev'], timeout=30)
for ref in ('refs/heads/dev', 'refs/remotes/origin/dev'):
tip = run(['git', 'rev-parse', '--verify', ref + '^{commit}']).strip()
require(tip == commit, 'Release commit must equal local dev and origin/dev; merge and synchronize dev first.')
def policy():
return json.loads(POLICY.read_text())
@ -283,6 +291,7 @@ def prepare(a):
branch = run(['git', 'branch', '--show-current']).strip()
require(not re.search(r'(^|/)poc($|[-/])', branch), 'POC branches cannot prepare Fanyu releases.')
require(not s['dirty'], 'Prepare requires a clean checkout (use an isolated checkout for unrelated edits).')
require_mainline(s['commit'])
require(bool(re.fullmatch(r'[^\s@]+@sha256:[0-9a-f]{64}', a.image)), 'Use an immutable repository@sha256 image.')
require(a.server.startswith('https://') and '@' not in a.server and '?' not in a.server, 'Use a credential-free HTTPS Kubernetes server URL.')
release_id = a.id or dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8]
@ -370,6 +379,7 @@ def deploy(r, a):
require(r['state'] == 'awaiting_approval' and not r['operations'], 'No fresh deployable plan; inspect status.')
require(r['planHash'] == a.confirm_plan == digest(plan_data(r)), 'Plan hash does not match.')
require(bool(a.approval_ref.strip()), 'Record the explicit user approval reference for this exact plan.')
require_mainline(r['commit'], refresh=True)
age = (dt.datetime.now(dt.timezone.utc) - dt.datetime.fromisoformat(r['baseline']['at'])).total_seconds()
require(0 <= age <= 3600, 'Cluster check is older than one hour; recheck and obtain a new plan approval.')
for key in ('image-provenance', 'change-safety'):

View File

@ -0,0 +1,89 @@
"""Release source identity checks use isolated Git repos, never a company remote."""
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('mainline_release', ROOT / 'scripts/release.py')
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
class MainlineGuardTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.base = Path(self.tmp.name)
self.repo = self.base / 'repo'
self.repo.mkdir()
self.git('init', '-q', '--bare', '-b', 'dev', str(self.base / 'origin.git'))
self.git('init', '-q', '-b', 'dev')
self.git('config', 'user.name', 'ReleaseTest')
self.git('config', 'user.email', 'test@example.invalid')
(self.repo / 'fixture').write_text('base\n')
self.git('add', 'fixture')
self.git('commit', '-qm', 'base')
self.git('remote', 'add', 'origin', str(self.base / 'origin.git'))
self.git('push', '-q', '-u', 'origin', 'dev')
self.commit = self.git('rev-parse', 'HEAD')
patcher = patch.object(m, 'ROOT', self.repo)
patcher.start()
self.addCleanup(patcher.stop)
def git(self, *args):
return subprocess.check_output(['git', *args], cwd=self.repo, text=True, stderr=subprocess.PIPE).strip()
def next_commit(self):
(self.repo / 'fixture').write_text('next\n')
self.git('add', 'fixture')
self.git('commit', '-qm', 'next')
return self.git('rev-parse', 'HEAD')
def test_synced_tip_and_detached_build_are_allowed(self):
m.require_mainline(self.commit, refresh=True)
self.git('switch', '--detach', self.commit)
m.require_mainline(self.commit)
def test_unmerged_feature_commit_is_blocked(self):
self.git('switch', '-c', 'feature')
candidate = self.next_commit()
with self.assertRaises(m.Blocked):
m.require_mainline(candidate)
def test_local_only_dev_commit_is_blocked(self):
candidate = self.next_commit()
with self.assertRaises(m.Blocked):
m.require_mainline(candidate)
def test_remote_advance_is_fetched_and_blocks_old_plan(self):
self.git('switch', '-c', 'feature')
newer = self.next_commit()
self.git('push', '-q', 'origin', 'feature')
subprocess.run(['git', '--git-dir', str(self.base / 'origin.git'), 'update-ref', 'refs/heads/dev', newer], check=True)
self.git('switch', 'dev')
self.assertEqual(self.git('rev-parse', 'origin/dev'), self.commit)
with self.assertRaises(m.Blocked):
m.require_mainline(self.commit, refresh=True)
self.assertEqual(self.git('rev-parse', 'origin/dev'), newer)
def test_missing_remote_or_local_dev_is_blocked(self):
self.git('update-ref', '-d', 'refs/remotes/origin/dev')
with self.assertRaises(m.Blocked):
m.require_mainline(self.commit)
self.git('update-ref', 'refs/remotes/origin/dev', self.commit)
self.git('switch', '--detach', self.commit)
self.git('branch', '-d', 'dev')
with self.assertRaises(m.Blocked):
m.require_mainline(self.commit)
def test_unreachable_remote_blocks_deployment_check(self):
self.git('remote', 'set-url', 'origin', str(self.base / 'missing.git'))
with self.assertRaises(m.Blocked):
m.require_mainline(self.commit, refresh=True)
if __name__ == '__main__':
unittest.main()

View File

@ -50,6 +50,7 @@ class ReleaseTests(unittest.TestCase):
self.start_patch('RECORDS', self.records)
self.start_patch('policy', lambda: copy.deepcopy(self.p))
self.start_patch('source', lambda: {'commit': 'c' * 40, 'dirty': False})
self.start_patch('require_mainline', lambda *args, **kwargs: None)
self.start_patch('run', lambda *args, **kwargs: 'feature/release')
self.start_patch('manifest_platforms', lambda image: ['linux/amd64'])
self.ds = {}
@ -136,6 +137,17 @@ class ReleaseTests(unittest.TestCase):
c['env'] += [{'name': k, 'value': v} for k, v in overrides.items()]
d['status'].update({k: desired['replicas'] for k in ('replicas', 'updatedReplicas', 'readyReplicas')})
def test_mainline_mismatch_blocks_before_cluster_access(self):
self.plan()
approval = self.approve()
with patch.object(m, 'require_mainline', side_effect=m.Blocked('dev changed')) as guard:
with patch.object(m, 'snapshot') as read_cluster:
with self.assertRaises(m.Blocked):
m.deploy(self.r, approval)
guard.assert_called_once_with(self.r['commit'], refresh=True)
read_cluster.assert_not_called()
self.assertEqual(self.writes, [])
def test_current_source_profile_keeps_resources_and_only_updates_image(self):
self.use_current_source_profile()
before = {name: copy.deepcopy(d['spec']) for name, d in self.ds.items()}
@ -453,6 +465,9 @@ class EntrypointTests(unittest.TestCase):
['git', '-c', 'user.name=ReleaseTest', '-c', 'user.email=test@example.invalid',
'commit', '-qm', 'fixture'] ]:
subprocess.run(args, cwd=root, check=True, capture_output=True)
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip()
for ref in ('refs/heads/dev', 'refs/remotes/origin/dev'):
subprocess.run(['git', 'update-ref', ref, commit], cwd=root, check=True, capture_output=True)
def cli(*args):
return subprocess.run([sys.executable, 'scripts/release.py', *args], cwd=root,
text=True, capture_output=True)