167 lines
8.9 KiB
Python
167 lines
8.9 KiB
Python
#!/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, comment_id=None):
|
||
"""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:
|
||
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
|
||
|
||
|
||
def preflight(task, event=None):
|
||
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
|
||
sha, ref = resolve(task, event)
|
||
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||
with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
|
||
base = assistant.worker.main_site_sha()
|
||
revisions = candidate.git('rev-list', '--first-parent', f'{base}..{sha}', cwd=assistant.SOURCE).splitlines()
|
||
task_id = task['id']
|
||
source = {'commit': sha} if ref == sha else {'pr': int(ref)}
|
||
plan = {'task': task_id, 'items': [dict(source, task=task_id)], 'base': base, 'sha': sha,
|
||
'extra': [revision for revision in revisions if revision != sha]}
|
||
candidate.verify_source(plan, assistant.SOURCE)
|
||
latest = coordinator.task(task_id)
|
||
cd.require(latest['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'task left QA stage')
|
||
review_identity(latest, comments(task_id), event)
|
||
path = DIRECTORY / (task_id + '.single.json')
|
||
if path.exists():
|
||
previous = cd.read_json(cd.immutable_file(path))
|
||
cd.require(previous == plan, 'existing candidate differs; reconcile its QA round before replacement')
|
||
else:
|
||
cd.require(not cd.metadata(latest, 'cd_acceptance'), 'task already has a registered candidate')
|
||
cd.record(path, plan)
|
||
extras = [candidate.git('show', '-s', '--format=%h %s', s, cwd=assistant.SOURCE) for s in plan['extra']]
|
||
# Keep source text literal inside a code block. HiFox expands task references in prose.
|
||
scope = '\n'.join(extras) or '无'
|
||
body = f'本单候选版本 `{sha}`,线上基线 `{base}`。同批主干变更:\n\n```text\n{scope}\n```'
|
||
marker = '[KG single ' + cd.acceptance_digest(plan) + ']'
|
||
if not any(r['content'].startswith(marker) for r in comments(task_id)):
|
||
cli('task', 'comment', task_id, '--body', marker + '\n\n' + body)
|
||
cd.require(any(r['content'].startswith(marker) and sha in r['content'] and base in r['content']
|
||
for r in comments(task_id)), 'candidate scope readback failed')
|
||
return coordinator.queue(task_id)
|
||
|
||
|
||
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(frozen_approval(task['id'], row['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}')
|