File size: 14,886 Bytes
caf8059
 
 
 
 
 
 
 
115b94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
caf8059
 
5ca3c16
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ca3c16
 
 
 
 
 
 
 
 
 
 
caf8059
5ca3c16
 
caf8059
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
5ca3c16
caf8059
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Project-authorized source, documents, real diffs and requirement/test traceability."""
import difflib
import hashlib
import json
from pathlib import Path
from src.apps.workbench.development import brief
from src.modules.skill.domain.models import SkillError,digest

ROOT=Path(__file__).resolve().parents[3]


def saved_snapshot(engine,actor,run_id):
    """Read-only, owner/project checked backup, including before source exists."""
    import io
    import zipfile
    job=engine.job(actor,run_id)
    from src.apps.workbench.project_files import execution_record
    record=execution_record(engine,actor,run_id)
    try:
        delivery=get_delivery(engine,actor,'run',run_id)
        entries={f['path']:f['content'] for f in delivery['files']}
        source_digest=delivery['source_digest']
        if record['record']['source_digest']!=source_digest:
            raise SkillError('SNAPSHOT_CHANGED','候选在读取期间已更新,请重新下载;不会重新调用模型。',409)
    except SkillError as exc:
        if exc.code!='SOURCE_PENDING':raise
        source_digest=None
        run=engine.runtimes[job['scenario']].get(actor,run_id)
        from src.modules.orchestrator.service import AgentRuntime
        try:design=AgentRuntime._operation_output(run,'AO04')['design']
        except (KeyError,StopIteration):design=None
        entries={'docs/requirements.md':run['request']['requirement'],
            'docs/design.md':json.dumps(design,ensure_ascii=False,indent=2) if design else '设计尚未返回;未虚构设计或代码。'}
    entries['evidence/execution-record.json']=json.dumps(record,ensure_ascii=False,indent=2)
    manifest={'run_id':run_id,'source_digest':source_digest,'record_digest':record['digest'],
        'status':record['record']['status'],'verified':bool(record['record']['validation']),
        'human_acceptance':False,'deployment_approved':False,
        'purpose':'saved-work-backup; may be incomplete, cancelled or unverified',
        'files':{path:hashlib.sha256(content.encode('utf8')).hexdigest() for path,content in entries.items()}}
    stream=io.BytesIO()
    with zipfile.ZipFile(stream,'w',zipfile.ZIP_DEFLATED) as archive:
        for path,content in entries.items():archive.writestr(path,content)
        archive.writestr('snapshot-manifest.json',json.dumps(manifest,ensure_ascii=False,indent=2))
    return stream.getvalue()


def draft_page(engine,actor,run_id):
    """Opaque-origin UI-only draft. No VM, Java bridge or network access."""
    import html
    delivery=get_delivery(engine,actor,'run',run_id)
    page=next((f['content'] for f in delivery['files'] if f['path']=='website/index.html'),None)
    if page is None:raise SkillError('DRAFT_PAGE_UNAVAILABLE','尚无网页草稿;已保存内容仍可下载,完整预览等待测试结果。',409)
    policy="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; form-action 'none'; base-uri 'none'"
    srcdoc='<meta http-equiv="Content-Security-Policy" content="'+html.escape(policy,quote=True)+'">'+page
    return ('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>界面草稿 · 未验收</title>'
        '<style>body{margin:0;font:14px system-ui}header{padding:14px;background:#fff7df;color:#594300}iframe{border:0;width:100%;height:calc(100vh - 100px)}</style>'
        '<header><strong>界面草稿 · 未验收</strong><p>这里只展示已生成的页面。Java 接口未连接,业务操作和数据尚未验证;独立测试仍以工作台状态为准。中止后已保存内容仍可下载。</p></header>'
        '<iframe title="已生成界面草稿" sandbox="allow-scripts" referrerpolicy="no-referrer" srcdoc="'+html.escape(srcdoc,quote=True)+'"></iframe></html>')

def _file(path,content,origin,baseline=''):
    diff=''.join(difflib.unified_diff(baseline.splitlines(True),content.splitlines(True),fromfile='a/'+path,tofile='b/'+path))
    lines=diff.splitlines()
    return dict(path=path,content=content,language=path.rsplit('.',1)[-1],origin=origin,
                sha256=hashlib.sha256(content.encode()).hexdigest(),change='unchanged' if content==baseline else 'modified' if baseline else 'added',
                additions=sum(l.startswith('+') and not l.startswith('+++') for l in lines),
                deletions=sum(l.startswith('-') and not l.startswith('---') for l in lines),diff=diff)

def get_delivery(engine,actor,kind,reference):
    if kind not in {'run','example','skill'}:raise SkillError('DELIVERY_KIND_INVALID','交付类型无效。',422)
    run=None;evidence=None
    if kind=='run':
        job=engine.job(actor,reference)
        scenario=job['scenario'];run_id=reference
        run=engine.runtimes[scenario].get(actor,reference)
        evidence=job.get('evidence');source=job.get('source')
    else:
        scenario,run_id,evidence=engine.evidence(actor,kind,reference)
        source=evidence['manifest']['source']
    if evidence:
        engine.check_evidence(evidence)
        source=evidence['manifest']['source']
    if not source:raise SkillError('SOURCE_PENDING','模型尚未返回可展示源码,请继续查看执行进度。',409)
    if source['source_digest']!=digest(source['files']):raise SkillError('SOURCE_DIGEST_MISMATCH','候选源码摘要不符。',409)
    spec=engine.spec(actor,scenario)
    profile=evidence['manifest']['snapshot']['framework'] if evidence else run['snapshot']['framework']
    engine.runtimes[scenario].harness.files({'files':source['files']},profile)
    baseline=(run or {}).get('request',{}).get('baseline')
    if baseline and digest(baseline['files'])!=baseline['source_digest']:raise SkillError('BASELINE_DIGEST_MISMATCH','基线摘要不符。',409)
    old=baseline['files'] if baseline else {}
    origin='codex-reviewed-repair' if evidence and evidence['manifest'].get('repair_origin') else 'model-generated' if run or evidence else 'candidate'
    files=[_file(path,text,'platform-runtime' if scenario=='webapp' and path.endswith('/App.java') else origin,old.get(path,'')) for path,text in source['files'].items()]
    development=evidence['manifest'].get('development',{}) if evidence else {}
    requirement=run['request']['requirement'] if run else development.get('requirement') or brief(scenario,spec['requirement'])
    design=development.get('design')
    if run:
        from src.modules.orchestrator.service import AgentRuntime
        try:design=AgentRuntime._operation_output(run,'AO04')['design']
        except (KeyError,StopIteration):pass
    if scenario=='business-app' and isinstance(design,dict) and design.get('summary'):
        requirement=('# 用户原始需求\n\n'+requirement+'\n\n# 模型补全方案(含待用户确认的假设)\n\n'+design['summary']+'\n\n以上为模型提出的补充建议和假设,具体实现需结合页面及测试结果核对。\n')
    design_text='# 技术设计\n\n'+('来源:本次模型返回的结构化设计。\n\n'+json.dumps(design,ensure_ascii=False,indent=2) if design else '来源:平台固定接口契约;此历史实例未保存可展示的模型设计。\n\n'+spec['module'].CONTRACT)
    body=evidence['manifest'] if evidence else {}
    validation={'verified':bool(evidence),'test':body.get('test'),'preview':body.get('preview'),
                'source_digest':source['source_digest'],'human_acceptance':False}
    config=engine.runtimes[scenario].sandbox.config
    actual_cases=[case.model_dump() for case in config.tests]
    suite_current=engine.runtimes[scenario].sandbox.suite_digest
    # A changed suite cannot inherit the previous test result.
    matched=bool(evidence and body['test'].get('suite_digest')==engine.runtimes[scenario].sandbox.suite_digest)
    passed=matched and body['test'].get('passed') is True
    rows=[]
    if hasattr(spec['module'],'acceptance_cases'):
        for i,row in enumerate(spec['module'].acceptance_cases(),1):
            rows.append({'case':i,'id':row.get('id','case-'+str(i)),
                         'requirement':row.get('requirement','CONTRACT'),
                         'status':'passed' if passed else 'not_verified',
                         'path':actual_cases[i-1]['path']})
    else:
        for i,case in enumerate(actual_cases,1):
            case_requirement=('BIZ-01' if i==1 else 'BIZ-03' if i in (2,8) else 'BIZ-04' if 3<=i<=7 else 'BIZ-02' if 9<=i<=21 else 'BIZ-05') if scenario=='erp' else ('PDF-01' if i==1 else 'PDF-03' if 2<=i<=5 else 'PDF-02' if i==23 else 'PDF-04') if scenario=='pdf' else 'CONTRACT'
            rows.append({'case':i,'id':'http-'+str(i),'requirement':case_requirement,'path':case['path'],'status':'passed' if passed else 'not_verified'})
    ui={'requirement':{'erp':'BIZ-06','calculator':'CALC-06','pdf':'PDF-05'}.get(scenario,'UI'),
        'status':'awaiting-browser-validation','note':'HTTP测试不代表页面交互已通过;网页系统测试另有独立报告。'}
    trace={'source_digest':source['source_digest'],'suite_digest':suite_current,'cases':rows,'website':ui}
    table='# 需求与系统测试对应表\n\n|用例|需求编号|接口|实际结果|\n|---|---|---|---|\n'
    table+=''.join(f"|{r['id']}|{r['requirement']}|{r['path']}|{r['status']}|\n" for r in rows)
    table+='\n网页交互检查另行记录,HTTP通过不替代网页验收。\n'
    docs={'docs/requirements.md':requirement,'docs/design.md':design_text,'docs/acceptance.md':table,
          'tests/traceability.json':json.dumps(trace,ensure_ascii=False,indent=2),
          'tests/report.json':json.dumps(validation,ensure_ascii=False,indent=2),
          'README.md':f"# {spec['name']}\n\n本制品包含Java源码、需求、技术设计、逐项测试对应表和配套网站。\n\n在ZKCoding中选本制品并点击‘打开网站预览’,平台会按固定依赖在无网QEMU重新编译、测试、运行Java,并打开配套网站。网站通过认证的预览代理调用本次Java服务。\n\n源码摘要:{source['source_digest']}。技术验证不替代人工验收。\n\nwebsite下页面为平台提供的配套交互模板,其来源独立标识;实际业务计算/解析在Java源码中。网页模板需要ZKCoding会话和预览代理,不是脱离平台即可双击运行的静态应用。\n"}
    review=(run or {}).get('outputs',{}).get('code_review',{}).get('review') or development.get('code_review')
    if review:
        review_text='# 代码检视记录\n\n来源:模型检视,须结合独立运行结果核对。\n\n'+review['summary']+'\n\n'
        review_text+='\n'.join('- '+finding for finding in review['findings'])+'\n\n'
        review_text+='检视源码摘要:'+review['reviewed_source_digest']+'\n\n'
        if review.get('superseded_by_repair'):review_text+='之后发生诊断修复,最终源码不能冒称已被本轮检视覆盖。\n\n'
        for path in review['changed_paths']:
            review_text+='```diff\n'+''.join(difflib.unified_diff(review['original_candidate'].get(path,'').splitlines(True),
                review['reviewed_candidate'].get(path,'').splitlines(True),fromfile='before/'+path,tofile='reviewed/'+path))+'\n```\n'
        docs['docs/code-review.md']=review_text
        docs['tests/code-review.json']=json.dumps(review,ensure_ascii=False,indent=2)
    for path,text in docs.items():files.append(_file(path,text,'run-record' if path.endswith('requirements.md') and run else 'platform-validation'))
    if scenario not in {'erp','erp-orders','calculator','pdf'}:
        docs_text=f"# {spec['name']}\n\n本制品包含Java源码、需求、接口技术设计、逐项HTTP测试对应表及验证报告。\n\n在ZKCoding中选择本制品,点击‘运行沙箱预览’,平台在无网QEMU重新编译、测试并运行Java,可通过工作台接口面板提交请求。\n\n源码摘要:{source['source_digest']}。技术通过仍待用户验收。\n"
        files=[f if f['path']!='README.md' else _file('README.md',docs_text,'platform-validation') for f in files]
    if scenario=='webapp':
        docs_text=(f"# {spec['name']}\n\n本次业务页面是模型依据当前需求生成的 `website/index.html`,可作为独立静态网页打开。"
                   "Java 源码是平台固定的隔离健康服务,不承载页面业务逻辑。\n\n"
                   "在 ZKCoding 中点击‘打开网站预览’,平台先在无网 QEMU 编译并测试固定 Java 服务,"
                   "再以受限沙箱展示本次页面。HTTP 技术测试不能替代网页交互验收。\n\n"
                   f"源码摘要:{source['source_digest']}。\n")
        files=[f if f['path']!='README.md' else _file('README.md',docs_text,'platform-validation') for f in files]
    if scenario=='business-app':
        docs_text=(f"# {spec['name']}\n\nJava 服务和网页由模型根据本次需求生成。网页通过平台受限预览桥调用隔离 Java 服务。\n\n"
                   "QEMU 自动检查编译、健康和平台接口;业务功能需按本次需求另行验证。"
                   "CSV 数据保存在预览虚拟机中,租约结束后重置。\n\n"
                   f"源码摘要:{source['source_digest']}。\n")
        files=[f if f['path']!='README.md' else _file('README.md',docs_text,'platform-validation') for f in files]
    for path in sorted((Path(__file__).parent/'preview_site').glob('*')) if scenario in {'erp','erp-orders','calculator','pdf'} else []:
        if path.name in {'index.html','site.js','site.css'}:files.append(_file('website/'+path.name,path.read_text(encoding='utf-8'),'platform-template'))
    if scenario=='pdf':
        from src.modules.execution.pdf_dependency import URL,VERSION,SHA512,dependency_bytes
        content={'coordinate':'org.apache.pdfbox:pdfbox-app','version':VERSION,'url':URL,'sha512':SHA512,
                 'sha256':hashlib.sha256(dependency_bytes()).hexdigest(),'license':'Apache-2.0'}
        files.append(_file('dependencies/pdfbox.json',json.dumps(content,indent=2),'platform-contract'))
    summary=f"{spec['name']}:{len(source['files'])} 个源码文件,{len(actual_cases)} 项独立HTTP验收;"+('技术通过,等待人工验收。' if passed else '当前候选尚未通过全部验收。')
    if len({f['path'] for f in files})!=len(files):
        raise SkillError('DELIVERY_PATH_CONFLICT','生成文件与平台交付文档重名,需保留不同路径后重新验证。',409)
    return dict(scenario=scenario,run_id=run_id,source_digest=source['source_digest'],summary=summary,
                validation=validation,verified=bool(evidence),preview_allowed=bool(evidence),files=files,
                delivery_digest=digest({f['path']:f['sha256'] for f in files}))