Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bb57a9835c | |||
| 49f9994ea6 | |||
| 501fbae6ff | |||
| 45aef5016a | |||
| c90cb803fa | |||
| e6a9acc32c | |||
| a3dcaa2f5b | |||
| c33c7e2700 | |||
| 91f9e00010 |
@@ -1,5 +1,21 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 开发快照 0.1.421(负责人手动切换需求状态)
|
||||||
|
|
||||||
|
- 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。
|
||||||
|
|
||||||
|
## 开发快照 0.1.420(需求单候选排队)
|
||||||
|
|
||||||
|
- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。
|
||||||
|
|
||||||
|
## 开发快照 0.1.419(候选预检识别落地 merge)
|
||||||
|
|
||||||
|
- 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。
|
||||||
|
|
||||||
|
## 开发快照 0.1.418(原需求单发布)
|
||||||
|
|
||||||
|
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
|
||||||
|
|
||||||
## 开发快照 0.1.417(知识治理发布助理接收提测交接)
|
## 开发快照 0.1.417(知识治理发布助理接收提测交接)
|
||||||
|
|
||||||
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
|
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Advance original-task candidate queue
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py
|
||||||
|
TimeoutStartSec=180
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Check reviewed demand tasks waiting for QA
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnStartupSec=30s
|
||||||
|
OnUnitInactiveSec=45s
|
||||||
|
AccuracySec=5s
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
# 知识治理候选和批次验收
|
# 知识治理候选和批次验收
|
||||||
|
|
||||||
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
|
## 需求单的六个状态
|
||||||
|
|
||||||
## 从提测评论接单
|
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
|
||||||
|
|
||||||
白小浅在业务单提交通过的预检后,评论自动化把来源任务和评论 UUID 交给 `scripts/release_handoff.py preflight`。执行器核验作者、最新结论、知识治理仓库的落地记录、主线范围和所选版本的 CI。相同业务单与提交复用同一发布单。已在测试中的旧单可用 `recover <业务任务号>` 从原记录补接。
|
## 在原需求单发布
|
||||||
|
|
||||||
发布单的预览列明线上基线、候选提交及所有其他随批提交。负责人在**该预览的评论线程**回复「确认范围」后准备候选。已有负责人计划仍可使用。每项来源支持 `{"task":"<UUID>","pr":123}` 或 `{"task":"<UUID>","commit":"<完整落地 SHA>"}`。固定历史候选可用 `release_assistant.py plan <发布单> <业务单>:<来源> --sha <完整 SHA>`。
|
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
|
||||||
|
|
||||||
候选就绪后,业务和批次 QA 均按下方格式提交真实报告。`kg-qa-v1` 评论触发登记,两处报告全部齐全才写入验收记录。已在「测试中」的业务单通过原单召唤 QA 执行新包复测。遇到建单或派测回执未知,核对远端记录后恢复。
|
## 旧版独立发布单的存量操作
|
||||||
|
|
||||||
## 发起候选
|
|
||||||
|
|
||||||
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,12 @@ def timeline(task_id):
|
|||||||
|
|
||||||
def owner_plan(task_id):
|
def owner_plan(task_id):
|
||||||
task(task_id)
|
task(task_id)
|
||||||
|
single = STATE / 'handoffs' / (task_id + '.single.json')
|
||||||
|
if single.is_file():
|
||||||
|
plan = cd.read_json(cd.immutable_file(single))
|
||||||
|
candidate.check_plan(plan)
|
||||||
|
cd.require(plan['task'] == task_id and [i['task'] for i in plan['items']] == [task_id], 'invalid single-task plan')
|
||||||
|
return plan
|
||||||
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
||||||
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
||||||
match = next((row for row in matches if row), None)
|
match = next((row for row in matches if row), None)
|
||||||
@@ -105,24 +111,33 @@ def publish_candidate(plan, receipt, run):
|
|||||||
f'发布任务 {task(plan["task"])["url"]}')
|
f'发布任务 {task(plan["task"])["url"]}')
|
||||||
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
|
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
|
||||||
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
|
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
|
||||||
|
single = [item['task'] for item in plan['items']] == [plan['task']]
|
||||||
|
if single:
|
||||||
|
body = body.split('业务单记录用例')[0] + '请在本单逐项记录实测证据。在结构化报告加 cases 对象,business 和 regression 各列本轮通过的业务及同批回归用例编号,两组编号独立,合计等于 required。验收登记后,由负责人在本单切到待发布。'
|
||||||
|
record = task(plan['task']) if single else {}
|
||||||
|
manual = (record.get('typeId') or (record.get('type') or {}).get('id')) == '1b7f1bb1-72c2-4106-b305-85604cf6d7e2'
|
||||||
|
if manual:
|
||||||
|
body += '\n候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
|
||||||
key = 'ready ' + receipt['bundle']
|
key = 'ready ' + receipt['bundle']
|
||||||
add_comment(plan['task'], key, body)
|
add_comment(plan['task'], key, body)
|
||||||
for item in plan['items']:
|
for item in plan['items']:
|
||||||
item_id = item['task']
|
item_id = item['task']
|
||||||
status = (task(item_id).get('status') or {}).get('id')
|
status = (task(item_id).get('status') or {}).get('id')
|
||||||
|
if manual and status == WAIT_TEST:
|
||||||
|
continue
|
||||||
if status == TESTING:
|
if status == TESTING:
|
||||||
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
|
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
|
||||||
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
|
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
|
||||||
f'{item_id}: another QA round is already in progress')
|
f'{item_id}: another QA round is already in progress')
|
||||||
add_comment(item_id, key, body)
|
add_comment(item_id, key, body)
|
||||||
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
if single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
||||||
summon_qa(plan, item_id, body)
|
summon_qa(plan, item_id, body)
|
||||||
continue
|
continue
|
||||||
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
||||||
add_comment(item_id, key, body)
|
add_comment(item_id, key, body)
|
||||||
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
||||||
f'{item_id}: task status changed during candidate handoff')
|
f'{item_id}: task status changed during candidate handoff')
|
||||||
managed = (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
|
managed = single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
|
||||||
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
|
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
|
||||||
if managed:
|
if managed:
|
||||||
cd.record(invitation, {'state': 'sending'})
|
cd.record(invitation, {'state': 'sending'})
|
||||||
@@ -131,7 +146,7 @@ def publish_candidate(plan, receipt, run):
|
|||||||
if managed:
|
if managed:
|
||||||
cd.record(invitation, {'state': 'sent', 'via': 'status'})
|
cd.record(invitation, {'state': 'sent', 'via': 'status'})
|
||||||
|
|
||||||
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
if not single and (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
|
||||||
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
|
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
|
||||||
|
|
||||||
|
|
||||||
@@ -154,7 +169,7 @@ def register(task_id):
|
|||||||
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
||||||
runtime.attest(directory / 'bundle', receipt)
|
runtime.attest(directory / 'bundle', receipt)
|
||||||
reports = {}
|
reports = {}
|
||||||
tasks = [item['task'] for item in plan['items']] + [task_id]
|
tasks = list(dict.fromkeys([item['task'] for item in plan['items']] + [task_id]))
|
||||||
for item_id in tasks:
|
for item_id in tasks:
|
||||||
obj = task(item_id)
|
obj = task(item_id)
|
||||||
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Drain reviewed demand tasks through the shared candidate environment."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
import release_handoff as h
|
||||||
|
|
||||||
|
cd = h.cd
|
||||||
|
coordinator = h.coordinator
|
||||||
|
|
||||||
|
|
||||||
|
def release_published_slot(compose):
|
||||||
|
directory = compose.parent
|
||||||
|
ready = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
||||||
|
task = h.assistant.task_record(ready['task'])
|
||||||
|
published = cd.metadata(task, 'cd_release') or {}
|
||||||
|
if task['status']['id'] != cd.PUBLISHED or not all(published.get(k) == ready[k] for k in ('sha', 'bundle')):
|
||||||
|
return False
|
||||||
|
project = 'kg-batch-' + ready['bundle'][:20]
|
||||||
|
cd.require(ready['mode'] == 'acceptance' and cd.hash_file(directory / 'bundle/release.json') == ready['bundle'],
|
||||||
|
'published QA archive changed')
|
||||||
|
cd.require(set(ready['containers']) == {'api', 'web', 'worker'}, 'unexpected candidate service set')
|
||||||
|
ids = []
|
||||||
|
for role, name in ready['containers'].items():
|
||||||
|
cd.require(name == project + '-' + role, 'candidate name mismatch')
|
||||||
|
info = json.loads(cd.run(['docker', 'inspect', name], 'inspect QA container'))[0]
|
||||||
|
labels = info['Config']['Labels']
|
||||||
|
cd.require(labels.get('com.docker.compose.project') == project and info['Image'] == ready['images'][role],
|
||||||
|
'candidate container identity changed')
|
||||||
|
ids.append(info['Id'])
|
||||||
|
cd.run(['docker', 'stop', *ids], 'retire published QA environment', timeout=90)
|
||||||
|
info = json.loads(cd.run(['docker', 'inspect', *ids], 'verify stopped QA containers'))
|
||||||
|
cd.require(len(info) == len(ids) and not any(row['State']['Running'] for row in info), 'QA slot still running')
|
||||||
|
compose.rename(directory / 'compose.released.json')
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def in_flight(state):
|
||||||
|
for path in state.glob('*.dispatch.json'):
|
||||||
|
claim = cd.read_json(cd.immutable_file(path))
|
||||||
|
key = path.name.split('.')[0]
|
||||||
|
if (state / key / 'ready.json').is_file():
|
||||||
|
continue
|
||||||
|
if claim['state'] != 'queued':
|
||||||
|
return True
|
||||||
|
run = h.candidate.read_forge(h.candidate.API + '/actions/runs/' + str(claim['run']))
|
||||||
|
if run['status'] != 'completed' or run.get('conclusion') == 'success':
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def drain():
|
||||||
|
state = coordinator.STATE
|
||||||
|
waiting = state / 'waiting'
|
||||||
|
waiting.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||||
|
entries = sorted(waiting.glob('*.json'), key=lambda p: (p.stat().st_mtime_ns, p.name))
|
||||||
|
entries = [(p, cd.read_json(cd.immutable_file(p))) for p in entries]
|
||||||
|
entries = [(p, e) for p, e in entries if e['state'] == 'waiting_for_slot']
|
||||||
|
if not entries:
|
||||||
|
return 'idle'
|
||||||
|
with cd.deploy_lock(state / 'runtime.lock'):
|
||||||
|
for compose in state.glob('*/compose.json'):
|
||||||
|
if not release_published_slot(compose):
|
||||||
|
return 'occupied'
|
||||||
|
if in_flight(state):
|
||||||
|
return 'building'
|
||||||
|
path, entry = entries[0]
|
||||||
|
task = h.assistant.task_record(entry['task'])
|
||||||
|
try:
|
||||||
|
sha, _ = h.resolve(task, entry['event'])
|
||||||
|
cd.require(sha == entry['sha'], 'review changed before building')
|
||||||
|
live = h.assistant.worker.main_site_sha()
|
||||||
|
if h.candidate.git('merge-base', live, sha, cwd=h.assistant.SOURCE, allowed=(0, 1)) == sha:
|
||||||
|
notice = f'主站当前版本 `{live}` 已包含候选提交 `{sha}`。请核对该需求的发布与验收记录。'
|
||||||
|
entry.update(state='included_in_live')
|
||||||
|
else:
|
||||||
|
result = h.prepare_from_review(task, entry['event'])
|
||||||
|
entry.update(state='dispatched', result=result)
|
||||||
|
notice = '候选构建已排队。' + result['url']
|
||||||
|
except cd.CDError as exc:
|
||||||
|
entry.update(state='blocked', reason=str(exc))
|
||||||
|
notice = '候选准备已停止。' + str(exc)
|
||||||
|
cd.record(path, entry)
|
||||||
|
coordinator.add_comment(task['id'], 'queue-result ' + entry['event'], notice)
|
||||||
|
return entry['state']
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print(drain())
|
||||||
@@ -42,7 +42,7 @@ def check_plan(plan):
|
|||||||
items = plan['items']
|
items = plan['items']
|
||||||
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
|
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
|
||||||
for item in items:
|
for item in items:
|
||||||
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and item['task'] != plan['task'],
|
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and (item['task'] != plan['task'] or len(items) == 1),
|
||||||
'invalid requirement identity')
|
'invalid requirement identity')
|
||||||
by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0
|
by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0
|
||||||
by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit'])
|
by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit'])
|
||||||
@@ -91,6 +91,13 @@ def check_qa(plan, receipt, reports, authors):
|
|||||||
cd.require(all(type(v) is int for v in values) and values[0] > 0
|
cd.require(all(type(v) is int for v in values) and values[0] > 0
|
||||||
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
|
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
|
||||||
f'{task}: required QA cases have not passed')
|
f'{task}: required QA cases have not passed')
|
||||||
|
if [i['task'] for i in plan['items']] == [plan['task']]:
|
||||||
|
cases = report.get('cases')
|
||||||
|
cd.require(isinstance(cases, dict) and all(isinstance(cases.get(k), list) and cases[k]
|
||||||
|
for k in ('business', 'regression')), 'single-task QA needs business and regression cases')
|
||||||
|
ids = cases['business'] + cases['regression']
|
||||||
|
cd.require(all(isinstance(v, str) and v.strip() for v in ids) and len(set(ids)) == len(ids) == values[0],
|
||||||
|
'single-task QA case IDs must match the required count')
|
||||||
|
|
||||||
|
|
||||||
def git(*args, cwd=None, allowed=(0,)):
|
def git(*args, cwd=None, allowed=(0,)):
|
||||||
|
|||||||
+57
-55
@@ -1,7 +1,6 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
|
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
|
||||||
import argparse
|
import argparse
|
||||||
import html
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -38,8 +37,9 @@ def review_identity(task, rows, event):
|
|||||||
review = reviews[0]
|
review = reviews[0]
|
||||||
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0],
|
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0],
|
||||||
'preflight is not a passing verdict for this task')
|
'preflight is not a passing verdict for this task')
|
||||||
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content']))
|
hashes = set(re.findall(r'落地[^\S\r\n]*(?:(merge)|merge)?[^\S\r\n]*`([0-9a-f]{7,40})`', review['content']))
|
||||||
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit')
|
cd.require(hashes, 'preflight missing landed commit marker')
|
||||||
|
cd.require(len(hashes) == 1, 'preflight contains multiple landed commits')
|
||||||
short = hashes.pop()
|
short = hashes.pop()
|
||||||
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
|
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
|
||||||
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
|
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
|
||||||
@@ -70,7 +70,7 @@ def resolve(task, event):
|
|||||||
return sha, sha
|
return sha, sha
|
||||||
|
|
||||||
|
|
||||||
def frozen_approval(task_id):
|
def frozen_approval(task_id, comment_id=None):
|
||||||
"""An owner reply to the specific, unedited scope preview authorizes this immutable local plan."""
|
"""An owner reply to the specific, unedited scope preview authorizes this immutable local plan."""
|
||||||
path = DIRECTORY / (task_id + '.preview.json')
|
path = DIRECTORY / (task_id + '.preview.json')
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
@@ -81,64 +81,66 @@ def frozen_approval(task_id):
|
|||||||
cd.require(parent.get('content') == saved['content'], 'scope preview has changed')
|
cd.require(parent.get('content') == saved['content'], 'scope preview has changed')
|
||||||
replies = [r for r in rows if r.get('parentId') == saved['comment'] and author(r) == cd.RELEASE_OWNER
|
replies = [r for r in rows if r.get('parentId') == saved['comment'] and author(r) == cd.RELEASE_OWNER
|
||||||
and (r.get('author') or {}).get('type') == 'human' and not r.get('runId')]
|
and (r.get('author') or {}).get('type') == 'human' and not r.get('runId')]
|
||||||
if replies and max(replies, key=lambda r: r['createdAt'])['content'].strip() == '确认范围':
|
if replies:
|
||||||
return saved['plan']
|
latest = max(replies, key=lambda r: r['createdAt'])
|
||||||
|
if ((comment_id is None or latest['id'] == comment_id)
|
||||||
|
and latest['content'].strip() in ('确认范围', '「确认范围」')):
|
||||||
|
return saved['plan']
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def preflight(task, event=None):
|
def preflight(task, event=None):
|
||||||
|
"""Persist the task's verified review before trying the shared QA environment."""
|
||||||
|
sha, _ = resolve(task, event)
|
||||||
|
if event is None:
|
||||||
|
reviews = [r for r in comments(task['id']) if author(r) == WHITE and r['content'].startswith('🚦')]
|
||||||
|
event = max(reviews, key=lambda r: r['createdAt'])['id']
|
||||||
|
review_identity(task, reviews, event)
|
||||||
|
waiting = coordinator.STATE / 'waiting'
|
||||||
|
waiting.mkdir(mode=0o700, exist_ok=True, parents=True)
|
||||||
|
path = waiting / (event + '.json')
|
||||||
|
with cd.deploy_lock(waiting / 'queue.lock'):
|
||||||
|
if not path.exists():
|
||||||
|
cd.record(path, {'task': task['id'], 'event': event, 'sha': sha, 'state': 'waiting_for_slot'})
|
||||||
|
entry = cd.read_json(cd.immutable_file(path))
|
||||||
|
cd.require(entry['task'] == task['id'] and entry['sha'] == sha, 'queue entry identity changed')
|
||||||
|
if entry['state'] == 'waiting_for_slot':
|
||||||
|
coordinator.add_comment(task['id'], 'waiting ' + event, f'候选已排队,目标提交 `{sha}`。环境可用后自动准备,看到候选就绪回执时请负责人切到「测试中」。')
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_from_review(task, event):
|
||||||
|
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
|
||||||
sha, ref = resolve(task, event)
|
sha, ref = resolve(task, event)
|
||||||
label = f"知识治理发布批次|{task['identifier']} · {sha[:12]}"
|
|
||||||
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
claim = DIRECTORY / f"{task['id']}-{sha}.json"
|
|
||||||
with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
|
with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
|
||||||
# Validate range, all ingredients and CI before creating any task. A fresh UUID is only a dry-run identity.
|
base = assistant.worker.main_site_sha()
|
||||||
import uuid
|
revisions = candidate.git('rev-list', '--first-parent', f'{base}..{sha}', cwd=assistant.SOURCE).splitlines()
|
||||||
scope = {'task': str(uuid.uuid4()), 'items': [{'task': task['id'], **({'commit': sha} if ref == sha else {'pr': int(ref)})}],
|
task_id = task['id']
|
||||||
'sha': sha, 'base': assistant.worker.main_site_sha()}
|
source = {'commit': sha} if ref == sha else {'pr': int(ref)}
|
||||||
scope['extra'] = [s for s in candidate.git('rev-list', '--first-parent', f"{scope['base']}..{sha}", cwd=assistant.SOURCE).splitlines() if s != sha]
|
plan = {'task': task_id, 'items': [dict(source, task=task_id)], 'base': base, 'sha': sha,
|
||||||
candidate.verify_source(scope, assistant.SOURCE)
|
'extra': [revision for revision in revisions if revision != sha]}
|
||||||
if event:
|
candidate.verify_source(plan, assistant.SOURCE)
|
||||||
review_identity(task, comments(task['id']), event)
|
latest = coordinator.task(task_id)
|
||||||
children = cli('task', 'list', '--parent', task['id'], '--limit', '100')
|
cd.require(latest['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'task left QA stage')
|
||||||
matches = [r for r in children if r['title'] == label]
|
review_identity(latest, comments(task_id), event)
|
||||||
cd.require(len(children) < 100 and len(matches) <= 1, 'ambiguous release record')
|
path = DIRECTORY / (task_id + '.single.json')
|
||||||
if matches:
|
|
||||||
cd.require(claim.exists(), 'unclaimed release record needs reconciliation')
|
|
||||||
launch = coordinator.task(matches[0]['id'])
|
|
||||||
else:
|
|
||||||
cd.require(not claim.exists(), 'previous creation outcome needs reconciliation')
|
|
||||||
cd.record(claim, {'state': 'creating'})
|
|
||||||
created = cli('task', 'create', '--space', cd.SPACE, '--parent', task['id'], '--type', '需求',
|
|
||||||
'--title', label, '--status', '待开始', '--assignee', 'agent:' + ASSISTANT,
|
|
||||||
'--body', f"{task['identifier']} 独立发布单。系统将回填版本范围预览,请等待负责人确认。")
|
|
||||||
launch = coordinator.task(created['id'])
|
|
||||||
cd.require(launch['parentTaskId'] == task['id'] and launch['title'] == label and
|
|
||||||
(launch.get('delegate') or {}).get('id') == ASSISTANT, 'release handoff readback mismatch')
|
|
||||||
cd.record(claim, {'state': 'created', 'release': launch['id']})
|
|
||||||
scope['task'] = launch['id']
|
|
||||||
candidate.check_plan(scope)
|
|
||||||
path = DIRECTORY / (launch['id'] + '.preview.json')
|
|
||||||
if path.exists():
|
if path.exists():
|
||||||
saved = cd.read_json(cd.immutable_file(path))
|
previous = cd.read_json(cd.immutable_file(path))
|
||||||
cd.require(scope == saved['plan'], 'baseline or scope changed; review a fresh batch')
|
cd.require(previous == plan, 'existing candidate differs; reconcile its QA round before replacement')
|
||||||
return {'state': 'existing_preview', 'url': launch['url'], 'plan': scope}
|
else:
|
||||||
lines = [f"{s[:12]} {candidate.git('show', '-s', '--format=%s', s, cwd=assistant.SOURCE)}" for s in scope['extra']]
|
cd.require(not cd.metadata(latest, 'cd_acceptance'), 'task already has a registered candidate')
|
||||||
safe_title = ' '.join(task['title'].splitlines()).replace('```', '')
|
cd.record(path, plan)
|
||||||
body = f"发布范围预览 · {task['identifier']}\n\n线上基线 `{scope['base']}`\n\n候选 `{sha}`\n\n本次修复:{safe_title}\n\n同批改动:\n" + '\n'.join(lines or ['无']) + '\n\n请负责人在这条评论下回复「确认范围」,系统将据此准备候选包。'
|
extras = [candidate.git('show', '-s', '--format=%h %s', s, cwd=assistant.SOURCE) for s in plan['extra']]
|
||||||
marker = '[KG candidate scope ' + cd.acceptance_digest(scope) + ']'
|
# Keep source text literal inside a code block. HiFox expands task references in prose.
|
||||||
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
|
scope = '\n'.join(extras) or '无'
|
||||||
if not entries:
|
body = f'本单候选版本 `{sha}`,线上基线 `{base}`。同批主干变更:\n\n```text\n{scope}\n```'
|
||||||
cli('task', 'comment', launch['id'], '--body', marker + '\n\n' + body)
|
marker = '[KG single ' + cd.acceptance_digest(plan) + ']'
|
||||||
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
|
if not any(r['content'].startswith(marker) for r in comments(task_id)):
|
||||||
cd.require(len(entries) == 1, 'expected one scope preview comment')
|
cli('task', 'comment', task_id, '--body', marker + '\n\n' + body)
|
||||||
stored = entries[0]
|
cd.require(any(r['content'].startswith(marker) and sha in r['content'] and base in r['content']
|
||||||
normalized = html.unescape(stored['content']).replace(
|
for r in comments(task_id)), 'candidate scope readback failed')
|
||||||
f"[{task['identifier']}](mention://task/{task['id']})", task['identifier'])
|
return coordinator.queue(task_id)
|
||||||
cd.require(normalized == marker + '\n\n' + body, 'scope preview readback differs from plan')
|
|
||||||
comment = stored['id']
|
|
||||||
cd.record(path, {'plan': scope, 'comment': comment, 'content': stored['content']})
|
|
||||||
return {'state': 'awaiting_scope', 'url': launch['url'], 'plan': scope}
|
|
||||||
|
|
||||||
|
|
||||||
def qa(task, row):
|
def qa(task, row):
|
||||||
@@ -172,7 +174,7 @@ def main():
|
|||||||
if args.action == 'preflight':
|
if args.action == 'preflight':
|
||||||
return preflight(task, args.comment)
|
return preflight(task, args.comment)
|
||||||
if args.action == 'scope':
|
if args.action == 'scope':
|
||||||
cd.require(author(row) == cd.RELEASE_OWNER and row['content'].strip() == '确认范围' and frozen_approval(task['id']),
|
cd.require(frozen_approval(task['id'], row['id']),
|
||||||
'require the release owner reply on the exact scope preview')
|
'require the release owner reply on the exact scope preview')
|
||||||
return coordinator.queue(task['id'])
|
return coordinator.queue(task['id'])
|
||||||
return qa(task, row)
|
return qa(task, row)
|
||||||
|
|||||||
@@ -23,6 +23,21 @@ class CandidateReleaseTest(unittest.TestCase):
|
|||||||
for n, sha in ((20, A), (21, B))}
|
for n, sha in ((20, A), (21, B))}
|
||||||
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
||||||
|
|
||||||
|
def test_one_requirement_owns_its_own_release(self):
|
||||||
|
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
||||||
|
candidate.check_scope(plan, self.prs.__getitem__, [A, B])
|
||||||
|
with self.assertRaises(cd.CDError):
|
||||||
|
candidate.check_plan(dict(plan, items=plan['items'] + [{'task': QA2, 'pr': 20}]))
|
||||||
|
|
||||||
|
def test_single_report_covers_business_and_batch(self):
|
||||||
|
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
|
||||||
|
report = self.result()
|
||||||
|
for missing in ({}, {'business': ['C-001']}, {'business': [], 'regression': ['R-001']}):
|
||||||
|
with self.assertRaises(cd.CDError):
|
||||||
|
candidate.check_qa(plan, RUN, {TASK: (self.report, dict(report, cases=missing))}, {OWNER})
|
||||||
|
complete = dict(report, cases={'business': ['C-001'], 'regression': ['R-001']}, required=2, passed=2)
|
||||||
|
candidate.check_qa(plan, RUN, {TASK: (self.report, complete)}, {OWNER})
|
||||||
|
|
||||||
def test_scope_accounts_for_entire_main_range(self):
|
def test_scope_accounts_for_entire_main_range(self):
|
||||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||||
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
|
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import unittest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import candidate_queue as queue
|
||||||
import release_handoff as h
|
import release_handoff as h
|
||||||
|
|
||||||
|
|
||||||
@@ -22,6 +23,68 @@ class ReleaseHandoffTest(unittest.TestCase):
|
|||||||
with self.assertRaises(h.cd.CDError):
|
with self.assertRaises(h.cd.CDError):
|
||||||
h.review_identity(self.task, [self.review, newer], 'comment')
|
h.review_identity(self.task, [self.review, newer], 'comment')
|
||||||
|
|
||||||
|
def test_landed_commit_marker_in_merge_chain(self):
|
||||||
|
header = self.review['content'].splitlines()[0]
|
||||||
|
for marker in ('落地', '落地(merge)', '落地 merge'):
|
||||||
|
row = dict(self.review, content=f'{header}\n源 `b2248a9` ➔ {marker} `d76363c`(11:56)➔ main `c90cb80`')
|
||||||
|
self.assertEqual(h.review_identity(self.task, [row], 'comment')[0], 'd76363c')
|
||||||
|
for body, error in [('源 `b2248a9`', 'missing landed commit'),
|
||||||
|
('落地 merge `d76363c`,落地 `c90cb80`', 'multiple landed commits')]:
|
||||||
|
row = dict(self.review, content=f'{header}\n{body}')
|
||||||
|
with self.assertRaisesRegex(h.cd.CDError, error):
|
||||||
|
h.review_identity(self.task, [row], 'comment')
|
||||||
|
|
||||||
|
def test_busy_candidate_waits_on_original_task_without_dispatch(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||||
|
patch.object(h.coordinator, 'add_comment'), patch.object(h.coordinator, 'queue') as dispatch:
|
||||||
|
task_id = '00000001-1111-2222-3333-444444444444'
|
||||||
|
event = '00000002-1111-2222-3333-444444444444'
|
||||||
|
slot = Path(tmp) / 'another' / 'compose.json'
|
||||||
|
slot.parent.mkdir()
|
||||||
|
slot.touch()
|
||||||
|
first = h.preflight({'id': task_id}, event)
|
||||||
|
second = h.preflight({'id': task_id}, event)
|
||||||
|
self.assertEqual(first, second)
|
||||||
|
self.assertEqual(first['state'], 'waiting_for_slot')
|
||||||
|
self.assertEqual(len(list((Path(tmp) / 'waiting').glob('*.json'))), 1)
|
||||||
|
dispatch.assert_not_called()
|
||||||
|
|
||||||
|
def test_waiter_dispatches_once_when_slot_is_free(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
|
||||||
|
patch.object(h.assistant, 'task_record', return_value={'id': 'task'}), \
|
||||||
|
patch.object(h.assistant.worker, 'main_site_sha', return_value='b' * 40), \
|
||||||
|
patch.object(h.candidate, 'git', return_value='b' * 40), \
|
||||||
|
patch.object(h.coordinator, 'add_comment'), \
|
||||||
|
patch.object(h, 'prepare_from_review', return_value={'url': 'https://example.test/run/1'}) as build:
|
||||||
|
h.preflight({'id': 'task'}, 'event')
|
||||||
|
self.assertEqual(queue.drain(), 'dispatched')
|
||||||
|
self.assertEqual(queue.drain(), 'idle')
|
||||||
|
build.assert_called_once_with({'id': 'task'}, 'event')
|
||||||
|
|
||||||
|
def test_active_qa_slot_is_preserved(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
|
||||||
|
patch.object(h.assistant, 'task_record', return_value={'status': {'id': 'testing'}}), \
|
||||||
|
patch.object(h.cd, 'run') as docker:
|
||||||
|
root = Path(tmp)
|
||||||
|
(root / 'waiting').mkdir()
|
||||||
|
h.cd.record(root / 'waiting/event.json', {'state': 'waiting_for_slot'})
|
||||||
|
(root / 'slot').mkdir()
|
||||||
|
(root / 'slot/compose.json').touch()
|
||||||
|
h.cd.record(root / 'slot/ready.json', {'task': 'task'})
|
||||||
|
self.assertEqual(queue.drain(), 'occupied')
|
||||||
|
docker.assert_not_called()
|
||||||
|
|
||||||
|
def test_ready_demand_waits_for_owner_to_start_testing(self):
|
||||||
|
record = {'id': 'task', 'typeId': '1b7f1bb1-72c2-4106-b305-85604cf6d7e2', 'url': 'https://example.test/task',
|
||||||
|
'status': {'id': h.coordinator.WAIT_TEST}}
|
||||||
|
plan = {'task': 'task', 'items': [{'task': 'task'}]}
|
||||||
|
with patch.object(h.coordinator, 'task', return_value=record), patch.object(h.coordinator, 'add_comment'), \
|
||||||
|
patch.object(h.coordinator.hfx, 'hifox') as cli:
|
||||||
|
h.coordinator.publish_candidate(plan, dict(sha='a'*40, bundle='b'*64, url='https://example.test'), '1')
|
||||||
|
cli.assert_not_called()
|
||||||
|
|
||||||
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
|
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
|
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
|
||||||
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
|
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
|
||||||
@@ -31,6 +94,10 @@ class ReleaseHandoffTest(unittest.TestCase):
|
|||||||
'author': {'id': h.cd.RELEASE_OWNER, 'type': 'human'}}
|
'author': {'id': h.cd.RELEASE_OWNER, 'type': 'human'}}
|
||||||
with patch.object(h, 'comments', return_value=[parent, reply]):
|
with patch.object(h, 'comments', return_value=[parent, reply]):
|
||||||
self.assertEqual(h.frozen_approval('task'), saved['plan'])
|
self.assertEqual(h.frozen_approval('task'), saved['plan'])
|
||||||
|
quoted = dict(reply, content='「确认范围」')
|
||||||
|
with patch.object(h, 'comments', return_value=[parent, quoted]):
|
||||||
|
self.assertEqual(h.frozen_approval('task', 'ok'), saved['plan'])
|
||||||
|
self.assertIsNone(h.frozen_approval('task', 'other'))
|
||||||
for bad in (dict(reply, parentId=None), dict(reply, runId='agent-run'), dict(reply, content='先不确认范围')):
|
for bad in (dict(reply, parentId=None), dict(reply, runId='agent-run'), dict(reply, content='先不确认范围')):
|
||||||
with patch.object(h, 'comments', return_value=[parent, bad]):
|
with patch.object(h, 'comments', return_value=[parent, bad]):
|
||||||
self.assertIsNone(h.frozen_approval('task'))
|
self.assertIsNone(h.frozen_approval('task'))
|
||||||
|
|||||||
Reference in New Issue
Block a user