186 lines
11 KiB
Python
186 lines
11 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 html
|
||
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请负责人在这条评论下回复「确认范围」,系统将据此准备候选包。'
|
||
marker = '[KG candidate scope ' + cd.acceptance_digest(scope) + ']'
|
||
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
|
||
if not entries:
|
||
cli('task', 'comment', launch['id'], '--body', marker + '\n\n' + body)
|
||
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')]
|
||
cd.require(len(entries) == 1, 'expected one scope preview comment')
|
||
stored = entries[0]
|
||
normalized = html.unescape(stored['content']).replace(
|
||
f"[{task['identifier']}](mention://task/{task['id']})", task['identifier'])
|
||
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):
|
||
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}')
|