feat(release): 从预检评论接单并固定候选版本
build / build (push) Successful in 2m28s

This commit is contained in:
姚章浩
2026-11-24 14:39:43 +08:00
parent 8d873680cc
commit 4a12b20e9b
9 changed files with 447 additions and 8 deletions
+37 -4
View File
@@ -42,12 +42,19 @@ def owner_plan(task_id):
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)
if match is None:
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
plan = json.loads(match[1])
from release_handoff import frozen_approval
plan = frozen_approval(task_id)
cd.require(plan, 'release owner must confirm the scope preview or post a kg-release-v1 plan')
else:
plan = json.loads(match[1])
candidate.check_plan(plan)
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
for item in plan['items']:
requirement = task(item['task'])
if 'commit' in item:
# The owner's authenticated plan binds this requirement to the exact landed commit.
# verify_source also checks the complete first-parent range and exact candidate CI.
continue
identifier = requirement.get('identifier')
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
@@ -96,21 +103,47 @@ def publish_candidate(plan, receipt, run):
f'归档 `{receipt["bundle"]}`\n\n'
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
f'发布任务 {task(plan["task"])["url"]}')
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
key = 'ready ' + receipt['bundle']
add_comment(plan['task'], key, body)
for item in plan['items']:
item_id = item['task']
status = (task(item_id).get('status') or {}).get('id')
if status == TESTING:
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
f'{item_id}: another QA round is already in progress')
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(),
f'{item_id}: another QA round is already in progress')
add_comment(item_id, key, body)
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, item_id, body)
continue
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
add_comment(item_id, key, body)
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
f'{item_id}: task status changed during candidate handoff')
managed = (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
if managed:
cd.record(invitation, {'state': 'sending'})
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
if managed:
cd.record(invitation, {'state': 'sent', 'via': 'status'})
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
def summon_qa(plan, target, body):
directory = STATE / cd.acceptance_digest(plan)
path = directory / (target + '.qa-invite.json')
if path.exists():
cd.require(cd.read_json(cd.immutable_file(path)).get('state') == 'sent', 'QA invitation outcome needs reconciliation')
return
cd.record(path, {'state': 'sending'})
result = hfx.hifox(CLI, 'task', 'summon', target, '--agent', 'crew:baa5ca58-1228-4da5-9bf8-b9927075e4be', '--body', body)
cd.record(path, {'state': 'sent', 'result': result})
def register(task_id):
+10 -3
View File
@@ -42,9 +42,12 @@ def check_plan(plan):
items = plan['items']
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
for item in items:
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and item['task'] != plan['task'],
'invalid requirement identity')
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'])
cd.require(by_pr or by_commit, 'invalid requirement or PR/landed commit')
cd.require(len({i['task'] for i in items}) == len(items) == len({i.get('pr', i.get('commit')) for i in items}),
'duplicate requirement or PR')
extra = plan['extra']
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
@@ -55,6 +58,10 @@ def check_scope(plan, read_pr, first_parents):
check_plan(plan)
required = set(plan['extra'])
for item in plan['items']:
if 'commit' in item:
cd.require(item['commit'] not in required, 'landed commit is listed in multiple scope entries')
required.add(item['commit'])
continue
pr = read_pr(item['pr'])
sha = pr.get('merge_commit_sha')
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
+1 -1
View File
@@ -446,7 +446,7 @@ def cmd_internal_contracts(go: str) -> int:
cwd=ROOT).returncode
if qa_rc:
return qa_rc
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
for pattern in ('test_production_cd.py', 'test_candidate_release.py', 'test_release_handoff.py'):
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
if cd_rc:
return cd_rc
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Read live release evidence and preview a plan without publishing or dispatching."""
import argparse
import json
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
import candidate_coordinator as coordinator
import candidate_release as candidate
import candidate_worker as worker
import production_cd as cd
SOURCE = Path.home() / '.local/share/kg-candidate-source.git'
SITE = 'http://100.85.111.121:8088/'
def task_record(value):
cd.require(cd.matches(cd.UUID, value) or re.fullmatch(r'CYWL-[1-9][0-9]{0,8}', value),
'provide a task UUID or CYWL task number')
record = coordinator.hfx.hifox(coordinator.CLI, 'task', 'view', value)
cd.require(isinstance(record, dict) and record.get('spaceId') == cd.SPACE, 'task is outside the release space')
cd.require(cd.matches(cd.UUID, record.get('id')) and value in (record['id'], record.get('identifier')),
'task identity did not match')
return record
def ci_state(sha):
status = candidate.read_forge(f'{candidate.API}/commits/{sha}/status')
contexts = {line.split('#', 1)[0].strip() for line in candidate.CONTEXTS.read_text().splitlines()} - {''}
latest = {name: next((row for row in status.get('statuses') or [] if row.get('context') == name), None)
for name in sorted(contexts)}
result = {}
for name, row in latest.items():
row = row or {}
url = (row.get('target_url') or '').replace('http://192.168.50.223:3000/', cd.FORGE + '/', 1)
if url.startswith('/' + cd.REPO + '/'):
url = cd.FORGE + url
result[name] = {'status': row.get('status', 'not_reported'), 'url': url if url.startswith(cd.FORGE + '/') else ''}
return result
def snapshot():
branch = candidate.read_forge(f'{candidate.API}/branches/main')
sha = branch['commit']['id']
cd.require(cd.matches(cd.SHA, sha), 'Gitea did not return a full main SHA')
active = worker.main_site_sha()
block = None
try:
coordinator.runtime.qa_database(Path.home() / '.config/knowledge-governance/qa.json')
except (cd.CDError, coordinator.runtime.qa_env.QAError, OSError):
block = '候选执行机未就绪。缺少可用的专用 QA 数据库连接配置。'
return {'main_sha': sha, 'main_ci': ci_state(sha), 'site': SITE, 'site_api_sha': active,
'candidate_configuration_block': block}
def pr_record(number):
cd.require(type(number) is int and number > 0, 'invalid PR number')
result = candidate.read_forge(f'{candidate.API}/pulls/{number}')
return {**result, 'public_url': f'{cd.FORGE}/{cd.REPO}/pulls/{number}'}
def describe_task(value):
task = task_record(value)
acceptance = cd.metadata(task, 'cd_acceptance')
release = cd.metadata(task, 'cd_release')
result = {'task': task['identifier'], 'uuid': task['id'], 'url': task['url'],
'status': (task.get('status') or {}).get('name'), 'acceptance': acceptance, 'release': release}
try:
plan = coordinator.owner_plan(task['id'])
except cd.CDError as exc:
result['candidate'] = {'state': 'unavailable', 'reason': str(exc)}
return result
key = cd.acceptance_digest(plan)
receipt = coordinator.STATE / key / 'ready.json'
dispatch = coordinator.STATE / (key + '.dispatch.json')
if receipt.is_file():
data = cd.read_json(cd.immutable_file(receipt))
result['candidate'] = {field: data.get(field) for field in ('sha', 'bundle', 'url', 'mode', 'ready_at')}
elif dispatch.is_file():
data = cd.read_json(cd.immutable_file(dispatch))
result['candidate'] = {field: data.get(field) for field in ('state', 'run', 'url')}
if data.get('run') and cd.matches(coordinator.hfx.RUN_ID, data['run']):
run = candidate.read_forge(candidate.API + '/actions/runs/' + data['run'])
result['candidate'].update(workflow_status=run.get('status'), conclusion=run.get('conclusion'))
else:
result['candidate'] = {'state': 'unprepared', 'sha': plan['sha']}
return result
def preview(release_task, items, candidate_sha=None):
state = snapshot()
sha, base = candidate_sha or state['main_sha'], state['site_api_sha']
cd.require(cd.matches(cd.SHA, sha), 'invalid candidate SHA')
launch = task_record(release_task)
cd.require((launch.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
'choose a separate pre-approval release task')
content = []
landed = set()
for pair in items:
task_key, separator, number = pair.partition(':')
if separator and cd.matches(cd.SHA, number):
requirement = task_record(task_key)
landed.add(number)
content.append({'task': requirement['id'], 'commit': number})
continue
cd.require(bool(separator) and bool(re.fullmatch(r'[1-9][0-9]{0,8}', number)), 'expected task:PR')
requirement = task_record(task_key)
pr = pr_record(int(number))
change = pr.get('merge_commit_sha')
cd.require(pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, change),
f'PR #{number} has not landed on main')
fields = [pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')]
cd.require(bool(re.search(rf"(?<![\w-]){re.escape(requirement['identifier'])}(?!\w)",
' '.join(value or '' for value in fields), re.IGNORECASE)), 'PR task mismatch')
landed.add(change)
content.append({'task': requirement['id'], 'pr': int(number)})
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=SOURCE)
cd.require(candidate.git('rev-parse', 'origin/main', cwd=SOURCE) == state['main_sha'], 'main changed while reading release scope')
cd.require(candidate.git('merge-base', sha, base, cwd=SOURCE, allowed=(0, 1)) == base,
'main does not contain the running source')
rows = candidate.git('log', '--first-parent', '--format=%H %s', f'{base}..{sha}', cwd=SOURCE).splitlines()
extra = [{'sha': line.split(' ', 1)[0], 'subject': line.partition(' ')[2]}
for line in rows if line.split(' ', 1)[0] not in landed]
plan = {'task': launch['id'], 'base': base, 'sha': sha, 'items': content, 'extra': [row['sha'] for row in extra]}
candidate.verify_source(plan, SOURCE)
return {'state': 'preview_only', 'release_task': launch['url'], 'plan': plan,
'extra_for_owner_review': extra, 'candidate_ci': ci_state(sha), 'main_ci': state['main_ci'],
'candidate_configuration_block': state['candidate_configuration_block']}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
status = sub.add_parser('status')
status.add_argument('--task')
status.add_argument('--pr', type=int)
plan = sub.add_parser('plan')
plan.add_argument('release_task')
plan.add_argument('items', nargs='+', metavar='TASK:PR_OR_COMMIT')
plan.add_argument('--sha')
args = parser.parse_args()
if args.command == 'plan':
result = preview(args.release_task, args.items, args.sha)
else:
result = snapshot()
if args.pr is not None:
pr = pr_record(args.pr)
result['pr'] = {'number': args.pr, 'state': pr.get('state'), 'url': pr['public_url'],
'merged': pr.get('merged'), 'landed_sha': pr.get('merge_commit_sha'),
'head_sha': (pr.get('head') or {}).get('sha')}
if args.task:
result['release_task'] = describe_task(args.task)
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except HTTPError as exc:
sys.exit(f'Release assistant: provider HTTP {exc.code}')
except cd.CDError as exc:
sys.exit(f'Release assistant: {exc}')
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
sys.exit(f'Release assistant: {type(exc).__name__}')
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
import argparse
import json
import re
import sys
import candidate_coordinator as coordinator
import candidate_release as candidate
import production_cd as cd
import release_assistant as assistant
WHITE = '85f8325f-2b75-423d-a05a-4c7b2dd2c8e6'
ASSISTANT = '3b0b9cbb-d46d-4a06-b6cb-bafa7837499b'
DEVELOPERS = {'ea783c59-2100-465b-96d9-b02846b15a69', '6643e064-50de-49c5-bdaa-efc916187165',
'649363a5-34e5-49c9-b0bc-7fa0371c5a86'}
DIRECTORY = coordinator.STATE / 'handoffs'
REPO_URL = cd.FORGE + '/' + cd.REPO
def cli(*args):
return coordinator.hfx.hifox(coordinator.CLI, *args)
def comments(task):
return cli('task', 'comment', 'list', task, '--limit', '0')
def author(row):
return (row.get('author') or {}).get('id')
def review_identity(task, rows, event):
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id']
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
review = reviews[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')
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content']))
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit')
short = hashes.pop()
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)
if packages:
cd.require(packages[0]['createdAt'] <= review['createdAt'], 'new developer delivery needs fresh preflight')
return short, packages[0]['content'] if packages else ''
def resolve(task, event):
cd.require(task['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'require a QA-stage business task')
cd.require(not any(f.get('name') == 'staging_tag' and (f.get('value') or {}).get('text') == 'manual'
for f in task.get('customFields') or []), 'manually managed QA task')
short, package = review_identity(task, comments(task['id']), event)
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=assistant.SOURCE)
sha = candidate.git('rev-parse', '--verify', short + '^{commit}', cwd=assistant.SOURCE)
cd.require(cd.matches(cd.SHA, sha), 'ambiguous landed commit')
# For standard merges, the first-parent merge message supplies the PR number. Verify its identity with Gitea.
subject = candidate.git('show', '-s', '--format=%s', sha, cwd=assistant.SOURCE)
numbers = set(re.findall(r'#(\d+)\b', subject)) | set(re.findall(re.escape(REPO_URL) + r'/pulls/(\d+)\b', package))
for number in sorted(numbers):
pr = assistant.pr_record(int(number))
if pr.get('merge_commit_sha') == sha and pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main':
fields = ' '.join(v or '' for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
if re.search(rf"(?<![\w-]){re.escape(task['identifier'])}(?![\w-])", fields, re.I):
return sha, number
cd.require(REPO_URL + '/commit/' + sha in package and re.search(r'已合并[^\n]*' + sha, package),
'developer delivery does not confirm this landed revision in the governance repository')
return sha, sha
def frozen_approval(task_id):
"""An owner reply to the specific, unedited scope preview authorizes this immutable local plan."""
path = DIRECTORY / (task_id + '.preview.json')
if not path.exists():
return None
saved = cd.read_json(cd.immutable_file(path))
rows = comments(task_id)
parent = next((r for r in rows if r['id'] == saved['comment']), {})
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
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() == '确认范围':
return saved['plan']
return None
def preflight(task, event=None):
sha, ref = resolve(task, event)
label = f"知识治理发布批次|{task['identifier']} · {sha[:12]}"
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
claim = DIRECTORY / f"{task['id']}-{sha}.json"
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.
import uuid
scope = {'task': str(uuid.uuid4()), 'items': [{'task': task['id'], **({'commit': sha} if ref == sha else {'pr': int(ref)})}],
'sha': sha, 'base': assistant.worker.main_site_sha()}
scope['extra'] = [s for s in candidate.git('rev-list', '--first-parent', f"{scope['base']}..{sha}", cwd=assistant.SOURCE).splitlines() if s != sha]
candidate.verify_source(scope, assistant.SOURCE)
if event:
review_identity(task, comments(task['id']), event)
children = cli('task', 'list', '--parent', task['id'], '--limit', '100')
matches = [r for r in children if r['title'] == label]
cd.require(len(children) < 100 and len(matches) <= 1, 'ambiguous release record')
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():
saved = cd.read_json(cd.immutable_file(path))
cd.require(scope == saved['plan'], 'baseline or scope changed; review a fresh batch')
return {'state': 'existing_preview', 'url': launch['url'], 'plan': scope}
lines = [f"{s[:12]} {candidate.git('show', '-s', '--format=%s', s, cwd=assistant.SOURCE)}" for s in scope['extra']]
safe_title = ' '.join(task['title'].splitlines()).replace('```', '')
body = f"发布范围预览 · {task['identifier']}\n\n线上基线 `{scope['base']}`\n\n候选 `{sha}`\n\n本次修复:{safe_title}\n\n同批改动:\n" + '\n'.join(lines or ['无']) + '\n\n请负责人在这条评论下回复「确认范围」,系统将据此准备候选包。'
comment = coordinator.add_comment(launch['id'], 'scope ' + cd.acceptance_digest(scope), body)
stored = next(r for r in comments(launch['id']) if r['id'] == comment)
cd.record(path, {'plan': scope, 'comment': comment, 'content': stored['content']})
return {'state': 'awaiting_scope', 'url': launch['url'], 'plan': scope}
def qa(task, row):
cd.require(author(row) in coordinator.QA_AUTHORS and row.get('taskId') == task['id'], 'require designated QA author')
match = coordinator.QA_FENCE.search(row['content'])
cd.require(match, 'missing structured QA evidence')
report = json.loads(match[1]); bundle = report.get('bundle')
cd.require(cd.matches(cd.HASH, bundle), 'missing tested archive digest')
hits = []
for p in coordinator.STATE.glob('*/ready.json'):
receipt = cd.read_json(cd.immutable_file(p))
if receipt.get('bundle') == bundle and receipt.get('sha') == report.get('sha'):
manifest = cd.read_json(cd.immutable_file(p.parent / 'bundle/release.json'))
hits.append(manifest['task'])
cd.require(len(hits) == 1, 'require one formal candidate for this report')
plan = coordinator.owner_plan(hits[0])
cd.require(task['id'] in [plan['task']] + [i['task'] for i in plan['items']], 'report is outside the batch')
return coordinator.register(hits[0])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('preflight', 'qa', 'scope', 'recover'))
parser.add_argument('task'); parser.add_argument('comment', nargs='?'); args = parser.parse_args()
task = assistant.task_record(args.task)
if args.action == 'recover':
return preflight(task)
cd.require(cd.matches(cd.UUID, args.comment), 'require comment event UUID')
rows = comments(task['id']); row = next((r for r in rows if r['id'] == args.comment), {})
cd.require(row.get('taskId') == task['id'], 'event comment belongs to another task')
if args.action == 'preflight':
return preflight(task, args.comment)
if args.action == 'scope':
cd.require(author(row) == cd.RELEASE_OWNER and row['content'].strip() == '确认范围' and frozen_approval(task['id']),
'require the release owner reply on the exact scope preview')
return coordinator.queue(task['id'])
return qa(task, row)
if __name__ == '__main__':
try:
print(json.dumps(main(), ensure_ascii=False))
except (cd.CDError, OSError, ValueError, KeyError) as exc:
sys.exit(f'Release handoff: {exc}')
+7
View File
@@ -28,6 +28,13 @@ class CandidateReleaseTest(unittest.TestCase):
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
def test_reviewed_direct_commit_can_be_pinned_before_later_main_changes(self):
plan = dict(self.plan, items=[{'task': QA1, 'commit': B}], extra=[A])
candidate.check_scope(plan, self.prs.__getitem__, [B, A])
for invalid in (dict(plan, extra=[A, B]), dict(plan, items=[{'task': QA1, 'commit': B[:7]}])):
with self.assertRaises(cd.CDError):
candidate.check_scope(invalid, self.prs.__getitem__, [B, A])
def test_pr_must_be_merged_on_main_and_match_range(self):
self.prs[20]['base']['ref'] = 'test'
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
+38
View File
@@ -0,0 +1,38 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import release_handoff as h
class ReleaseHandoffTest(unittest.TestCase):
def setUp(self):
self.task = {'id': 'task'}
self.review = {'id': 'comment', 'taskId': 'task', 'createdAt': '2', 'author': {'id': h.WHITE},
'content': '🚦 可测试 ✅|[任务](mention://task/task)\n落地 `abcdef1`'}
def test_latest_passing_review_and_task_identity(self):
self.assertEqual(h.review_identity(self.task, [self.review], 'comment')[0], 'abcdef1')
for invalid in (dict(self.review, author={'id': 'other'}), dict(self.review, taskId='other'),
dict(self.review, content='🚦 不可测试,引用「可测试」')):
with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [invalid], 'comment')
newer = dict(self.review, id='new', createdAt='3', content='🚦 未通过')
with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [self.review, newer], 'comment')
def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
h.cd.record(Path(tmp) / 'task.preview.json', saved)
parent = {'id': 'preview', 'content': saved['content']}
reply = {'id': 'ok', 'createdAt': '2', 'content': '确认范围', 'parentId': 'preview',
'author': {'id': h.cd.RELEASE_OWNER, 'type': 'human'}}
with patch.object(h, 'comments', return_value=[parent, reply]):
self.assertEqual(h.frozen_approval('task'), saved['plan'])
for bad in (dict(reply, parentId=None), dict(reply, runId='agent-run'), dict(reply, content='先不确认范围')):
with patch.object(h, 'comments', return_value=[parent, bad]):
self.assertIsNone(h.frozen_approval('task'))
with patch.object(h, 'comments', return_value=[dict(parent, content='changed'), reply]), self.assertRaises(h.cd.CDError):
h.frozen_approval('task')