feat: complete native BOM and Harness execution acceptance

This commit is contained in:
阿白叔 committed 2026-11-12 19:21:55 +08:00
1 parent 4f8fbd7806
commit 65438cb7e5
234 files changed
+24402 -865

No files matched your search

+20
View File
@@ -39,6 +39,7 @@ def main():
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
parser.add_argument('--create-task', action='store_true', help='Create real project tasks from a live native model conversation')
parser.add_argument('--workfolder-workspace', action='store_true', help='Select the engineering folder as the native Harness workspace before task creation')
args = parser.parse_args()
if args.auto_intervention_check and not args.incident:
parser.error('--auto-intervention-check requires --incident')
@@ -115,6 +116,23 @@ def main():
def tick():
try:
if args.workfolder_workspace and not state.get('workspacePicked'):
import win32gui
handle = win32gui.FindWindow('#32770', 'Select Workspace Directory')
if handle:
from pywinauto import Desktop, keyboard
picker = Desktop(backend='uia').window(handle=handle)
if not state.get('workspacePickerTyped'):
picker.set_focus()
keyboard.send_keys('%d')
QApplication.clipboard().setText(str(project_root.resolve()))
keyboard.send_keys('^v{ENTER}')
state['workspacePickerTyped'] = time.monotonic()
elif time.monotonic()-state['workspacePickerTyped'] > 1:
picker.capture_as_image().save(str(output / 'native-workspace-picker.png'))
picker.child_window(auto_id='1', control_type='Button').click_input()
state['workspacePicked'] = True
report['checks'].append('typed engineering folder in actual Win32 workspace picker and clicked Select Folder')
if time.monotonic() > state['deadline']:
raise TimeoutError('Native desktop acceptance timed out')
if state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view.retry.isVisible():
@@ -224,6 +242,8 @@ def main():
command.append('--file-check')
if args.outbox_only:
command.append('--outbox-only')
if args.workfolder_workspace:
command.extend(['--workspace-root', str(project_root)])
state['child'] = subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
state['phase'] = 'web'
+6
View File
@@ -0,0 +1,6 @@
/** Test-only host wrapper; production runtime composition remains unchanged. */
import {bootRuntime} from '../integration/dsh/start.mjs';
import {observeRuntime} from './acceptance_runtime_state.mjs';
const {ctx}=await bootRuntime({announce:false});
observeRuntime(ctx);
console.log('DX_DSH_READY '+JSON.stringify({url:ctx.connection.authenticatedUrl(`http://127.0.0.1:${ctx.webServer.port}/`)}));
+201
View File
@@ -0,0 +1,201 @@
"""Run seeded stratified real-model tasks through the embedded UI in isolation."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from acceptance_workspace import create_workspace_root
import time
import zipfile
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def fixtures(workspace):
cases = []
def add(name, files, request, expected, *, goal=False):
directory = workspace / f'{len(cases)+1:02d}-{name}'
directory.mkdir(parents=True)
for filename, text in files.items():
target = directory / filename
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding='utf-8')
cases.append({'id': directory.name, 'directory': str(directory), 'request': request,
'expected': expected, 'goal': goal,
'input_hashes': {str(p.relative_to(directory)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in directory.rglob('*') if p.is_file()}})
return directory
add('facts', {'notes.md': '工程 Board-A;目标位号 R1、R3;新料号 NEW-73;不执行CAD。\n'},
'阅读 notes.md,生成 result.json:project、references(数组)、new_part_number。',
{'result.json': {'project': 'Board-A', 'references': ['R1', 'R3'], 'new_part_number': 'NEW-73'}})
directory = add('unicode', {'中文目录/说明.txt': '第一行:电阻 Ω\n第二行:中文路径 ✓\n'},
'将中文目录/说明.txt 原样复制成 result.txt,保留两行文字和换行。',
{'result.txt': '第一行:电阻 Ω\n第二行:中文路径 ✓\n'})
cases[-1]['expected']['result.txt'] = (directory / '中文目录/说明.txt').read_bytes().decode('utf-8')
add('bom-totals', {'bom.csv': 'part,quantity\nA,2\nB,3\nA,4\n'},
'汇总 bom.csv 中每个料号数量,生成 result.json,格式为 {"A":数量,"B":数量,"total":总数量}。',
{'result.json': {'A': 6, 'B': 3, 'total': 9}})
add('duplicates', {'bom.csv': 'project,refdes,part\nBoard-A,R1,A\nBoard-A,R2,B\nBoard-A,R1,C\nBoard-B,R1,D\n'},
'按 project+refdes 查找重复位号。result.json 的 duplicates 数组只列重复身份,每项包含 project、refdes。不同工程同位号不是重复。',
{'result.json': {'duplicates': [{'project': 'Board-A', 'refdes': 'R1'}]}})
add('comparison', {'before.csv': 'refdes,part\nR1,A\nR2,B\nR3,C\n', 'after.csv': 'refdes,part\nR1,A\nR2,X\nR3,C\n'},
'比较 before.csv 和 after.csv,result.json 的 changes 数组记录改变的 refdes、before、after。',
{'result.json': {'changes': [{'refdes': 'R2', 'before': 'B', 'after': 'X'}]}})
add('missing-fields', {'bom.csv': 'refdes,old,new\nR1,A,B\nR2,B,\nR3,,C\n'},
'检查 bom.csv 每行 refdes、old、new 必填。result.json 的 invalid_rows 写 Excel 风格行号(表头第1行),只列无效行。',
{'result.json': {'invalid_rows': [3, 4]}})
add('mapping-copy', {'source.json': '{"R1":"OLD-A","R2":"KEEP","R3":"OLD-A"}'},
'把 source.json 中 OLD-A 替换成 NEW-A,保存 result.json;保留其他值和源文件。',
{'result.json': {'R1': 'NEW-A', 'R2': 'KEEP', 'R3': 'NEW-A'}})
add('nested-edit', {'config.json': '{"name":"Board-A","options":{"enabled":false,"limit":3},"note":"保留我"}'},
'读取 config.json,生成 result.json,只把 options.enabled 改为 true、options.limit 改为 7。其他字段原样保留。',
{'result.json': {'name': 'Board-A', 'options': {'enabled': True, 'limit': 7}, 'note': '保留我'}})
directory = add('zip', {}, '解压资料.zip,读取内部说明文件。生成 result.json:marker 填说明中的验收码,count 填清单中的数量。',
{'result.json': {'marker': 'ZIP-7391', 'count': 12}})
with zipfile.ZipFile(directory / '资料.zip', 'w') as archive:
archive.writestr('nested/readme.txt', '验收码 ZIP-7391\n')
archive.writestr('nested/count.json', '{"count":12}')
cases[-1]['input_hashes']['资料.zip'] = hashlib.sha256((directory / '资料.zip').read_bytes()).hexdigest()
add('log-cause', {'run.log': '09:00 INFO start\n09:01 ERROR LIBRARY_NOT_FOUND missing central.lmc\n09:02 ERROR EXECUTION_ABORTED\n09:03 INFO saved=0\n'},
'根据 run.log 找出第一条错误及保存数量。result.json 写 root_error、saved、execution_succeeded(布尔值)。不要把随后中止当作最初原因。',
{'result.json': {'root_error': 'LIBRARY_NOT_FOUND', 'saved': 0, 'execution_succeeded': False}})
add('recursive-files', {'a/one.txt': 'accept_id=A11\n', 'b/two.txt': 'accept_id=B22\n', 'b/deep/three.txt': 'accept_id=C33\n', 'ignore.md': '无编号'},
'递归检查所有 .txt 文件,提取 accept_id,按字母排序。result.json 写 ids 数组。',
{'result.json': {'ids': ['A11', 'B22', 'C33']}})
add('decimal', {'prices.csv': 'part,qty,unit_price\nA,3,1.25\nB,2,4.50\nC,7,1.00\n'},
'计算 prices.csv 总金额,生成 result.json:total 用两位小数字符串,currency 填 CNY。',
{'result.json': {'total': '19.75', 'currency': 'CNY'}})
add('ambiguous-project', {'catalog.json': '[{"name":"Board-A","path":"X:/a.prj"},{"name":"Board-A","path":"Y:/a.prj"}]'},
'用户只有工程名 Board-A,目录 catalog.json 中有两个同名工程。不要任选一个。result.json 写 status="ambiguous"、candidate_count、selected_path=null。',
{'result.json': {'status': 'ambiguous', 'candidate_count': 2, 'selected_path': None}})
add('large-table', {'numbers.csv': 'id,value\n'+''.join(f'{i},{i}\n' for i in range(1, 601))},
'核对 numbers.csv 全部数据,result.json 写 count、sum、min、max。必须实际读取完整表格。',
{'result.json': {'count': 600, 'sum': 180300, 'min': 1, 'max': 600}})
add('value-policy', {'rows.json': '[{"refdes":"R1","mode":"inherit"},{"refdes":"R2","mode":"preserve"},{"refdes":"R3","mode":"custom","custom":"47k"}]'},
'任务默认 Value 策略是 part_label。解析 rows.json:inherit 使用默认,其余使用显式策略。result.json 用位号作键,对应实际策略名;custom 项写 custom:47k。',
{'result.json': {'R1': 'part_label', 'R2': 'preserve', 'R3': 'custom:47k'}})
add('merge-files', {'a.json': '["R3","R1","R2"]', 'b.json': '["R2","R4"]'},
'合并 a.json、b.json,去重并排序,result.json 写 references 数组与 count。',
{'result.json': {'references': ['R1', 'R2', 'R3', 'R4'], 'count': 4}})
add('missing-file', {}, '尝试读取不存在的 missing-report.txt。若不存在,result.json 写 status="missing"、content=null;不要编造内容。',
{'result.json': {'status': 'missing', 'content': None}})
add('invalid-json', {'broken.json': '{"refdes":"R1","part":"A",}'},
'broken.json 无法按标准 JSON 解析。修正语法另存 result.json,保留原数据,不改变原文件。',
{'result.json': {'refdes': 'R1', 'part': 'A'}})
add('goal-workflow', {f'inputs/part-{i}.json': json.dumps({'id': i, 'quantity': i*3}) for i in range(1, 7)},
'建立 goal 并持续完成这个任务:逐个检查 inputs 中六份 JSON,为每个输入生成 outputs/part-N.json,包含 id 和 double_quantity(quantity乘2)。最后生成 result.json,count=6、total_double_quantity 为全部乘2后的和。核对所有产物后完成 goal。不要只给计划。',
{'result.json': {'count': 6, 'total_double_quantity': 126},
**{f'outputs/part-{i}.json': {'id': i, 'double_quantity': i*6} for i in range(1, 7)}}, goal=True)
add('repair-and-run', {'calculate.py': 'import json\nvalues=[2,4,6]\nresult=sum(values)+1\nprint(json.dumps({"sum":result,"count":len(values)}))\n'},
'calculate.py 求和有一个错误。保留原文件,写出修复后的 fixed.py,实际运行它,并把运行的 JSON 输出保存 result.json。预期 sum=12、count=3。必须实际运行验证,最后报告结果。',
{'result.json': {'sum': 12, 'count': 3}})
assert len(cases) == 20
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=REPO / 'outputs/harness-acceptance-20')
parser.add_argument('--port', type=int, default=9231)
parser.add_argument('--provider-config', type=Path, default=Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/trial-task-center/dsh')
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--seed', type=int, help='Replay a recorded seed; omit for system randomness')
parser.add_argument('--count', type=int, default=20)
parser.add_argument('--legacy-fixed', action='store_true', help='Historical fixed regression cases; not random acceptance')
parser.add_argument('--case', action='append', help='Run named cases only, retaining their original sample IDs')
parser.add_argument('--windows-shell', action='store_true', help='Use the installed Windows PowerShell rather than the Codex process PATH')
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
run_parent = Path(os.environ['LOCALAPPDATA']) / 'DxProductivity/acceptance-workspaces'
run_parent.mkdir(parents=True, exist_ok=True)
run = create_workspace_root(run_parent, 'click20-')
data = run / 'data'
workspace = data / 'dsh/harness-home/workspace'
from random_acceptance_cases import generate
seed, cases = (None, fixtures(workspace)) if args.legacy_fixed else generate(workspace, args.seed, args.count)
if args.case:
cases = [case for case in cases if case['id'] in args.case]
if len(cases) != len(set(args.case)):
raise ValueError('Unknown sample ID')
manifest = {'git_head': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip(),
'source_patch_sha256': hashlib.sha256(subprocess.check_output(['git', 'diff', '--binary', 'HEAD'], cwd=REPO)).hexdigest(),
'data': str(data), 'workspace': str(workspace), 'cases': cases, 'real_model': not args.prepare_only, 'real_cad': False,
'windows_shell': args.windows_shell,
'seed': str(seed) if seed is not None else None, 'generation': 'legacy-fixed' if args.legacy_fixed else 'stratified-random-v1',
'command': [sys.executable, str(Path(__file__).resolve()), *sys.argv[1:]],
'generator_sha256': hashlib.sha256((REPO / 'tools/random_acceptance_cases.py').read_bytes()).hexdigest(),
'coverage': sorted({case.get('stratum', case['id']) for case in cases}),
'runtime': 'embedded-harness', 'comparison': 'not-run',
'unsupported_coverage': ['real CAD', 'in-flight tool cancellation', 'native runtime paired baseline']}
manifest_path = output / 'manifest.json'
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
print('MANIFEST='+str(manifest_path), flush=True)
if args.prepare_only:
return 0
from accept_dsh_desktop import copy_provider_configuration
copy_provider_configuration(args.provider_config, data / 'dsh')
if args.windows_shell:
shell = Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
profile = data / 'dsh/harness-home/profiles/dx-task/cordis.patch.yml'
profile.parent.mkdir(parents=True, exist_ok=True)
profile.write_text(json.dumps([{'id': 'pwsh-sandbox', 'config': {'pwshPath': str(shell)}}]), encoding='utf-8')
(data / 'dsh/issue-config.json').write_text('{"enabled":false}', encoding='utf-8')
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}'
os.environ.pop('QT_QPA_PLATFORM', None)
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
state = {'phase': 'open', 'started': time.monotonic(), 'child': None}
def build(service):
window = TrialTaskCenterWindow(service)
window.resize(1380, 900)
def tick():
modal = QApplication.activeModalWidget()
if isinstance(modal, QMessageBox) and modal.windowTitle().startswith('DSH助手'):
button = modal.button(QMessageBox.StandardButton.No)
if button:
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
if state['phase'] == 'open':
QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton)
state['phase'] = 'starting'
elif state['phase'] == 'starting' and window._dsh_view is not None and window._dsh_view._started:
log = (output / 'driver.log').open('w', encoding='utf-8')
state['child'] = subprocess.Popen(['node', str(REPO / 'tools/verify_harness_samples_ui.mjs'),
str(output), str(args.port)], cwd=REPO, stdout=log, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
state['phase'] = 'running'
elif state['phase'] == 'running' and state['child'].poll() is not None:
window.grab().save(str(output / 'desktop-final.png'))
timer.stop()
state['phase'] = 'done'
window.close()
elif state['phase'] == 'starting' and time.monotonic()-state['started'] > 360:
(output / 'startup-error.txt').write_text(window._dsh_view.last_error if window._dsh_view else 'No view', encoding='utf-8')
timer.stop()
window.close()
timer = QTimer(window)
timer.setInterval(250)
timer.timeout.connect(tick)
timer.start()
return window
application._load_window = lambda: build
code = application.main(['--data-root', str(data)])
return code or (state['child'].returncode if state['child'] else 1)
if __name__ == '__main__':
raise SystemExit(main())
+48
View File
@@ -0,0 +1,48 @@
/** Local-only official-runtime comparator. No task plugin or host prompt injection. */
import {createRequire} from 'node:module';
import {mkdir, readFile, writeFile} from 'node:fs/promises';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
import {observeRuntime} from './acceptance_runtime_state.mjs';
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const load=name=>import(pathToFileURL(require.resolve(name)).href);
const [source,home,workspace,port='9241',mode='inspect']=process.argv.slice(2);
if(!source||!home||!workspace)throw Error('Usage: node tools/accept_native_runtime.mjs SOURCE_PROFILE ISOLATED_HOME WORKSPACE [PORT] [inspect|run]');
const {loadProfileDirectory,composeEntries}=await load('@deepseek-ai/dsh-app-boot');
const {runProfile,INSTALL_ANCHOR}=await load('@deepseek-ai/dsh/profile-boot');
const {createLaunchEnvironmentSnapshot}=await load('@deepseek-ai/dsh-launch-environment');
const installed=require('@deepseek-ai/dsh/package.json');
if(installed.version!=='0.2.1-rc.5')throw Error('Runtime version mismatch');
const original=loadProfileDirectory('paired-source',path.resolve(source),INSTALL_ANCHOR);
const effective=composeEntries([...original.layers.map(layer=>layer.patches),original.patches]);
// Copy effective routing/model/shell budgets, never credential values to reports.
const matched=new Set(['llm-pi-ai','llm-deepseek','agent-default-model','pwsh-sandbox','sandbox-policy','agent-loop','workspace-controller']);
const patches=effective.filter(row=>matched.has(row.id)).map(row=>structuredClone(row));
const upsert=(id,config)=>{const row=patches.find(r=>r.id===id);if(row)row.config={...row.config,...config};else patches.push({id,config});};
upsert('sandbox-policy',{workspaceRoot:path.resolve(workspace)});
upsert('agent-preset-registry',{default:'standard'});
upsert('web-runtime',{openBrowser:false,printUrl:false,surfaceContext:false});
upsert('ui-settings-general',{welcomeNoticeVersion:'2026-09-28.1'});
upsert('ui-settings-models',{credentialOnboarding:false});
patches.push(...['desktop-product-telemetry','product-analytics','session-telemetry-otel'].map(id=>({id,disabled:true})));
const directory=path.resolve(home,'profiles','accept-native');
await mkdir(directory,{recursive:true});await mkdir(path.resolve(workspace),{recursive:true});
await writeFile(path.join(directory,'package.json'),JSON.stringify({private:true,type:'module',dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app']}}}));
await writeFile(path.join(directory,'cordis.patch.yml'),JSON.stringify(patches));
process.env.DSH_HOME=path.resolve(home);process.env.DSH_TELEMETRY_DISABLED='1';
const profile=loadProfileDirectory('accept-native',directory,INSTALL_ANCHOR);
const rows=composeEntries([...profile.layers.map(layer=>layer.patches),profile.patches]);
if(rows.some(row=>row.disabled!==true&&(row.name==='@dx/dsh-task'||row.id==='dx-task')))throw Error('Native baseline contains host plugin');
console.log(JSON.stringify({runtime:installed.version,mode,hostPlugin:false,matched:patches.filter(row=>matched.has(row.id)).map(row=>row.id),
credentialPrerequisite:'Copy source Harness .credentials.yaml into isolated home when using saved refs; never print it',
goalCoverage:'Official standard preset only; compare artifacts separately from host goal lifecycle'}));
if(mode==='run'){
const {ctx,shutdown}=await runProfile({profile:'accept-native',resolvedProfile:{profile,installAnchor:INSTALL_ANCHOR},patchFiles:[],
args:['--no-open','--host','127.0.0.1','--port',port],environment:createLaunchEnvironmentSnapshot([{source:'process',values:process.env}])});
await ctx.loader.await();
await ctx.workspaceRegistry.create(path.resolve(workspace),'Paired acceptance');
observeRuntime(ctx);
console.log('NATIVE_READY '+JSON.stringify({url:ctx.connection.authenticatedUrl(`http://127.0.0.1:${ctx.webServer.port}/`)}));
process.on('SIGINT',()=>void shutdown.shutdown(0));
}
+2 -1
View File
@@ -173,7 +173,8 @@ def file_dialog(driver, path, *, save=False):
target = next((c for c in edits if c.element_info.automation_id in ('1001', '1148')), None)
if target is None:
target = next(c for c in edits if 'FileName' in c.element_info.automation_id)
target.set_edit_text(str(path))
target.iface_value.SetValue(str(path))
assert target.get_value() == str(path), 'Native filename input differs from the requested file'
button = next(c for c in dialog.descendants(control_type='Button')
if c.element_info.automation_id == '1')
# Native buttons own HWNDs, unlike Qt's lightweight children.
+166
View File
@@ -0,0 +1,166 @@
"""Paired isolated official/native and application-composed UI exploration."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from acceptance_workspace import create_workspace_root
import time
from urllib.parse import urlsplit
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--seed', type=int)
parser.add_argument('--count', type=int, default=20)
parser.add_argument('--arm', choices=('native', 'harness'))
parser.add_argument('--port', type=int, default=9251)
parser.add_argument('--prepare-only', action='store_true')
parser.add_argument('--purpose', choices=('exploration', 'holdout'), default='exploration')
parser.add_argument('--provider-config', type=Path, default=Path(os.environ['LOCALAPPDATA'])/'DxProductivity/trial-task-center/dsh')
args = parser.parse_args()
output = args.output.resolve(); output.mkdir(parents=True, exist_ok=True)
if args.arm:
return worker(args, output)
from random_acceptance_cases import generate
root = create_workspace_root(Path(os.environ['LOCALAPPDATA'])/'DxProductivity/acceptance-workspaces', 'paired-random-')
seed = args.seed
source_files = [REPO/'integration/dsh/start.mjs', REPO/'tools/random_acceptance_cases.py',
REPO/'tools/accept_native_runtime.mjs', REPO/'tools/accept_paired_samples.py',
REPO/'tools/verify_harness_samples_ui.mjs', REPO/'tools/harness_session_evidence.mjs',
REPO/'tools/accept_harness_runtime.mjs', REPO/'tools/acceptance_runtime_state.mjs',
REPO/'tools/acceptance_workspace.py',
REPO/'tools/dsh_skip_question.mjs', REPO/'tools/score_acceptance_semantics.py',
REPO/'tools/extract_acceptance_execution.mjs', REPO/'tools/summarize_paired_samples.mjs',
*sorted((REPO/'integration/dsh/task-plugin').rglob('*.mjs'))]
fingerprints = {str(p.relative_to(REPO)): hashlib.sha256(p.read_bytes()).hexdigest() for p in source_files}
for arm in ('native', 'harness'):
home = root/arm/'dsh/harness-home'
workspace = home/'workspace'
seed, cases = generate(workspace, seed, args.count)
destination = output/arm; destination.mkdir()
manifest = {'seed': str(seed), 'generation': 'stratified-random-v1', 'cases': cases,
'data': str(root/arm), 'workspace': str(workspace),
'runtime': arm, 'require_host_goal': False, 'case_budget_ms': 600000,
'driver_description':'Isolated Qt WebEngine + targeted CDP mouse/keyboard input',
'require_workspace_preflight': True,
'coverage': sorted({c['stratum'] for c in cases}), 'real_cad': False,
'git_head': subprocess.check_output(['git','rev-parse','HEAD'],cwd=REPO,text=True).strip(),
'source_patch_sha256': hashlib.sha256(subprocess.check_output(['git','diff','--binary','HEAD'],cwd=REPO)).hexdigest(),
'source_files': fingerprints, 'command': [sys.executable,*sys.argv],
'real_model': not args.prepare_only, 'purpose': args.purpose}
(destination/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps({'seed': seed, 'output': str(output), 'root': str(root)}),flush=True)
if args.prepare_only: return 0
statuses = {}
for i,arm in enumerate(('native','harness')):
command = [sys.executable,'-X','utf8',str(Path(__file__).resolve()),'--output',str(output),
'--arm',arm,'--port',str(args.port+i),'--provider-config',str(args.provider_config)]
with (output/f'{arm}-worker.log').open('w',encoding='utf-8') as log:
process = subprocess.Popen(command,cwd=REPO,stdout=log,stderr=subprocess.STDOUT)
print(json.dumps({'arm':arm,'worker_pid':process.pid}),flush=True)
statuses[arm] = process.wait()
(output/'exit-status.json').write_text(json.dumps(statuses),encoding='utf-8')
for arm in ('native','harness'):
subprocess.run(['node',str(REPO/'tools/extract_acceptance_execution.mjs'),str(output/arm)],cwd=REPO,check=True)
subprocess.run([sys.executable,'-X','utf8',str(REPO/'tools/score_acceptance_semantics.py'),str(output/arm)],cwd=REPO,check=True)
subprocess.run(['node',str(REPO/'tools/summarize_paired_samples.mjs'),str(output)],cwd=REPO,check=True)
return int(any(statuses.values()))
def worker(args, output):
from dx_productivity.dsh.native_runtime import launch_environment
from PySide6.QtCore import QTimer, QUrl
from PySide6.QtWidgets import QApplication
from PySide6.QtWebEngineWidgets import QWebEngineView
destination = output/args.arm
manifest = json.loads((destination/'manifest.json').read_text(encoding='utf-8'))
existing_report = destination/'report.json'
if existing_report.exists():
previous = json.loads(existing_report.read_text(encoding='utf-8'))
if previous.get('status') in ('passed', 'failed') and not manifest.get('resume_completed'):
return int(previous['status'] == 'failed')
# Retain startup failures when the same exploration arm is resumed.
for name in ('runtime-error.log','runtime.log','driver.log','processes.json'):
previous_log = destination/name
if previous_log.exists() and previous_log.stat().st_size:
suffix = 1
while (destination/f'{name}.attempt-{suffix}').exists(): suffix += 1
shutil.copy2(previous_log,destination/f'{name}.attempt-{suffix}')
data = Path(manifest['data']); home = data/'dsh/harness-home'
source_home = args.provider_config/'harness-home'
env = launch_environment(args.provider_config)
env.update(DX_DSH_HOME=str(home), DX_DSH_CONTEXT_FILE=str(data/'context.json'),
DX_DSH_PARENT_PIPE='1', DX_DSH_WORKSPACE=manifest['workspace'],
DX_ACCEPTANCE_STATE_FILE=str(destination/'runtime-state.json'), DX_ACCEPTANCE_PYTHON=sys.executable)
(data/'context.json').write_text(json.dumps({'task_id':'','revision':'paired-exploration','events':[]}),encoding='utf-8')
profile = home/'profiles/dx-task'; profile.mkdir(parents=True,exist_ok=True)
# Private user model references and local secrets remain under isolated home.
source_patch = source_home/'profiles/dx-task/cordis.patch.yml'
if source_patch.exists(): shutil.copy2(source_patch,profile/'cordis.patch.yml')
credential = source_home/'.credentials.yaml'
if credential.exists(): shutil.copy2(credential,home/'.credentials.yaml')
patch = profile/'cordis.patch.yml'
patch_script = "const fs=require('fs'),yaml=require('./integration/dsh/node_modules/js-yaml');const p=process.argv[1];let rows=fs.existsSync(p)?yaml.load(fs.readFileSync(p,'utf8')):[];rows=rows.filter(r=>!['pwsh-sandbox','workspace-controller'].includes(r.id));rows.push({id:'pwsh-sandbox',config:{pwshPath:process.argv[2]}},{id:'workspace-controller',config:{documentsDirectory:process.argv[3]}});fs.writeFileSync(p,JSON.stringify(rows));"
subprocess.run(['node','-e',patch_script,str(patch),str(Path(os.environ['SystemRoot'])/'System32/WindowsPowerShell/v1.0/powershell.exe'),str(home/'documents')],cwd=REPO,check=True,stdout=subprocess.DEVNULL)
# Generate application profile privately so native reads precisely its effective model config.
prepare = "import {prepareProfileDirectory} from './integration/dsh/start.mjs'; await prepareProfileDirectory(process.argv[1]);"
subprocess.run(['node','--input-type=module','-e',prepare,str(profile)],cwd=REPO,env=env,check=True,stdout=subprocess.DEVNULL)
if args.arm == 'native':
command=['node',str(REPO/'tools/accept_native_runtime.mjs'),str(profile),str(home),manifest['workspace'],str(args.port+100),'run']
marker='NATIVE_READY '
else:
command=['node',str(REPO/'tools/accept_harness_runtime.mjs')]; marker='DX_DSH_READY '
runtime = subprocess.Popen(command,cwd=REPO,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=(destination/'runtime-error.log').open('w',encoding='utf-8'),text=True,encoding='utf-8')
(destination/'processes.json').write_text(json.dumps({'runtime_pid':runtime.pid,'worker_pid':os.getpid()}),encoding='utf-8')
# Startup reads occur on a thread, keeping the Qt event loop responsive.
import threading
state={'url':None,'driver':None,'started':time.monotonic()}
def read_ready():
with (destination/'runtime.log').open('w',encoding='utf-8') as log:
for line in runtime.stdout:
if line.startswith(marker): state['url']=json.loads(line[len(marker):])['url']; log.write(marker+'[local authenticated URL redacted]\n')
else: log.write(line)
log.flush()
threading.Thread(target=read_ready,daemon=True).start()
os.environ['QTWEBENGINE_REMOTE_DEBUGGING']=f'127.0.0.1:{args.port}'
os.environ.pop('QT_QPA_PLATFORM',None)
app=QApplication([]); view=QWebEngineView(); view.resize(1380,900); view.show()
def tick():
if state['url'] and not state.get('loaded'):
url=urlsplit(state['url']); manifest['runtime_origin']=f'{url.scheme}://{url.netloc}'
(destination/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
view.load(QUrl(state['url'])); state['loaded']=True
log=(destination/'driver.log').open('w',encoding='utf-8')
state['driver']=subprocess.Popen(['node',str(REPO/'tools/verify_harness_samples_ui.mjs'),str(destination),str(args.port)],cwd=REPO,stdout=log,stderr=subprocess.STDOUT)
(destination/'processes.json').write_text(json.dumps({'runtime_pid':runtime.pid,'worker_pid':os.getpid(),'driver_pid':state['driver'].pid}),encoding='utf-8')
if state['driver'] and state['driver'].poll() is not None:
report_path=destination/'report.json'
if report_path.exists() and json.loads(report_path.read_text(encoding='utf-8')).get('status')=='observation_failed':
# Preserve the current live runtime/model after a permanent
# observer failure; never convert telemetry failure into abort.
if not state.get('observation_failed'):
print(json.dumps({'arm':args.arm,'status':'observation_failed','runtime_preserved':True,'runtime_pid':runtime.pid}),flush=True)
state['observation_failed']=True
return
timer.stop(); view.close(); app.quit()
elif runtime.poll() is not None or (not state['url'] and time.monotonic()-state['started']>180):
timer.stop(); view.close(); app.quit()
timer=QTimer(); timer.timeout.connect(tick); timer.start(250)
app.exec()
if runtime.poll() is None:
runtime.terminate()
try: runtime.wait(timeout=15)
except subprocess.TimeoutExpired: runtime.kill()
return state['driver'].returncode if state['driver'] else 1
if __name__=='__main__': raise SystemExit(main())
+978
View File
@@ -0,0 +1,978 @@
"""Seeded, disposable real-project acceptance; actual Qt mouse/keyboard UI only.
Prepare does not start CAD. Run requires the exclusive CAD slot. This deliberately
records a single engineering family; twenty tasks do not imply twenty designs.
"""
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime
import hashlib
import json
import os
from pathlib import Path
import random
import re
import secrets
import shutil
import sqlite3
import sys
import time
import traceback
def write(path, value):
path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
def fingerprint(directory):
return {p.relative_to(directory).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(directory.rglob('*')) if p.is_file()}
def has_nc_marker(value):
return '/' in value and re.search(r'(?:^|/)\s*NC\s*(?:$|/)', value, re.I) is not None
def code_fingerprint(directory):
"""Fingerprint source/assets without installed dependencies or bytecode caches."""
result = {}
for current, directories, files in os.walk(directory):
directories[:] = sorted(name for name in directories if name not in {'node_modules', '__pycache__', '.git'})
for name in sorted(files):
path = Path(current) / name
if path.suffix != '.pyc':
result[path.relative_to(directory).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
return result
def prepare(root, source, graph, target_parts, *, seed=None, count=20, cells=(), supplemental='', part_prefixes=('4100',)):
root, source = Path(root).resolve(), Path(source).resolve(strict=True)
if root.exists() or root.is_relative_to(source.parent) or source.is_relative_to(root):
raise ValueError('Output must be a new directory outside the original project ancestry')
if (count < 20 and not supplemental) or not target_parts:
raise ValueError('At least20 cases and compatible target parts required')
if supplemental == 'rule_mode' and (count != 1 or list(target_parts) != ['4100-CA0000-T0']):
raise ValueError('rule_mode requires count=1 and target 4100-CA0000-T0')
root.mkdir(parents=True)
system_seed = seed is None
seed = secrets.randbits(128) if system_seed else seed
write(root / 'seed.json', {'seed': seed, 'created_ns': time.time_ns(), 'system_seed': system_seed})
rng = random.Random(seed)
candidates = sorted((c for c in graph['components'].values()
if c['refdes'] and c['attributes'].get('Part Number', '').startswith(tuple(part_prefixes))),
key=lambda c: c['refdes'])
if supplemental in {'rule_mode', 'pon_root'}:
if count != 1:
raise ValueError('Root supplemental requires count=1')
part_counts = Counter(c['attributes'].get('Part Number', '').casefold() for c in graph['components'].values())
ref_counts = Counter(c['refdes'].casefold() for c in graph['components'].values() if c['refdes'])
source_uids = Counter(c.get('source_uid', uid) for uid,c in graph['components'].items())
unique_source = {id(c): source_uids[c.get('source_uid',uid)] == 1 for uid,c in graph['components'].items()}
candidates = [c for c in candidates if not c.get('instance_path') and not c.get('source_refdes') and not c.get('ambiguous_attributes')
and c['attributes']['Part Number'].startswith('4100-')
and c['attributes']['Part Number'].casefold() not in {p.casefold() for p in target_parts}
and part_counts[c['attributes']['Part Number'].casefold()] == 1
and ref_counts[c['refdes'].casefold()] == 1 and len(c['pins']) == 2 and unique_source[id(c)]]
if not candidates:
raise ValueError('Root supplemental needs a globally unique root resistor Part Number')
elif len(candidates) < 2:
raise ValueError('Need two authentic compatible source resistor references')
kinds = ([supplemental] * count if supplemental else
['normal'] * (count - 9) + ['already_target'] * 2 + ['unknown_ref'] * 2 + ['stale_old'] * 2 + ['invalid_part', 'corrupt_database', 'pause_resume'])
rng.shuffle(kinds)
cases = []
for index, kind in enumerate(kinds):
nested = rng.choice(('项目', 'nested/工程', 'ASCII/boards'))
directory = root / 'projects' / f'{index+1:02d}-{kind}-{rng.randrange(10000,99999)}' / nested
directory.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source.parent, directory)
project = directory / source.name
selected = rng.sample(candidates, 1 if kind in {'rule_mode','pon_root'} else rng.randint(1, 2))
requests = []
for comp in selected:
old = comp['attributes']['Part Number']
new = rng.choice(target_parts)
mode = rng.choice(('preserve', 'part_label', 'part_number', 'custom'))
request = {'refdes': comp['refdes'], 'old_part_number': old, 'new_part_number': new,
'value_mode': mode, 'custom_value': f'{rng.randrange(10000,99999)}Ω-验收',
'sync_nc': rng.choice((True, False)), 'enabled': True}
if kind == 'rule_mode':
request.update(value_mode='preserve', custom_value='', sync_nc=True)
elif kind == 'already_target':
request.update(old_part_number=new, new_part_number=old, value_mode='preserve')
elif kind == 'unknown_ref':
request['refdes'] = f'R_UNKNOWN_{rng.randrange(1000000)}'
elif kind == 'stale_old':
request['old_part_number'] = f'STALE-{rng.randrange(1000000)}'
elif kind == 'invalid_part':
request['new_part_number'] = f'NOT-IN-LIBRARY-{rng.randrange(1000000)}'
requests.append(request)
if kind == 'corrupt_database':
databases = [p for p in directory.rglob('*') if p.name == 'icdb.dat' and p.is_file()]
if len(databases) != 1:
raise ValueError('Expected one self-copied database to corrupt')
assert databases[0].resolve().is_relative_to((root / 'projects').resolve())
databases[0].write_bytes(b'RANDOM-ACCEPTANCE-CORRUPT-' + str(seed).encode())
cases.append({'id': index+1, 'kind': kind, 'project': str(project), 'requests': requests,
'target_cell': rng.choice(cells) if kind == 'valid_cell' and cells else '',
'fault': {'stage': 'native_replace', 'delay_seconds': rng.randint(3, 12)} if kind == 'force_stop' else None,
'input_hashes': fingerprint(directory)})
manifest = {'seed': seed, 'source': str(source), 'source_hashes': fingerprint(source.parent),
'family_limit': 'One ordinary authentic resistor engineering design; task semantics vary, project family does not.',
'target_parts': list(target_parts), 'part_prefixes': list(part_prefixes), 'available_cells': list(cells), 'cases': cases,
'source_code_hashes': code_fingerprint(Path(__file__).resolve().parents[1] / 'src'),
'integration_hashes': code_fingerprint(Path(__file__).resolve().parents[1] / 'integration'),
'code_fingerprint_exclusions': ['node_modules', '__pycache__', '.git', '*.pyc']}
write(root / 'manifest.json', manifest)
return manifest
def prepare_baseline(root):
from dx_productivity.trial_task_center.native_netlist import capture_project, export_netlist
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
result = export_netlist(capture_project(Path(manifest['source']), root / 'baseline-capture'), root / 'baseline-export')
if not result['complete']:
raise AssertionError(result)
match = re.search(r'^KEY CentralLibrary "([^"]+)"', Path(manifest['source']).read_text(encoding='utf-8'), re.M)
if match:
library = Path(match[1])
manifest['library'] = {'path': str(library), 'sha256': hashlib.sha256(library.read_bytes()).hexdigest(), 'bytes': library.stat().st_size}
manifest['baseline'] = str(root / 'baseline-export/graph.json')
write(root / 'manifest.json', manifest)
print(json.dumps({'baseline': result['status'], 'components': len(result['graph']['components'])}), flush=True)
def workbook(root, manifest):
from openpyxl import Workbook
headers = ['project_name', 'project_path', 'old_part_number', 'new_part_number', 'refdes',
'schematic_name', 'sheet_number', 'uid', 'enabled', 'custom_value', 'sync_nc', 'value_mode']
book = Workbook()
sheet = book.active
sheet.append(headers)
for case in manifest['cases']:
for request in case['requests']:
row = dict(request, project_name=Path(case['project']).stem, project_path=case['project'])
sheet.append([row.get(h, '') for h in headers])
book.save(root / 'random-bom.xlsx')
book.close()
def database(root, sql):
with sqlite3.connect((root / 'data/task-center.db').as_uri() + '?mode=ro', uri=True) as conn:
conn.row_factory = sqlite3.Row
return [dict(row) for row in conn.execute(sql)]
def import_timing(root):
lines = (root / 'data/logs/application.log').read_text(encoding='utf-8').splitlines()
starts, spans, import_started, import_seconds = {}, [], None, None
for line in lines:
match = re.search(r'operation_(start|complete)=(\w+) task_id=(\S*) at=(\S+)', line)
if not match:
continue
phase, operation, task_id, timestamp = match.groups()
stamp = datetime.fromisoformat(timestamp)
if operation == 'import_bom_drafts' and phase == 'start':
starts, spans, import_started = {}, [], stamp
if import_started is None:
continue
if operation == 'refresh_bound_project':
if phase == 'start':
starts[task_id] = stamp
elif task_id in starts:
spans.append((stamp-starts.pop(task_id)).total_seconds())
if operation == 'import_bom_drafts' and phase == 'complete':
import_seconds = (stamp-import_started).total_seconds()
import_started = None
result = {'import_total_seconds': import_seconds, 'metadata_refresh_count': len(spans),
'metadata_refresh_seconds_sum': sum(spans),
'note': 'Import total includes routing/metadata refresh and workbook I/O; it is not Excel parse time.'}
write(root / 'import-timing.json', result)
return result
def run_ui(root, *, pause=True, prepare_only=False):
"""Source-run visible windows; no service import/create/execute shortcut."""
from PySide6.QtCore import Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QDialogButtonBox, QFileDialog, QLineEdit, QMessageBox, QPushButton
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.ui import TrialTaskCenterWindow
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
pause = pause and len(manifest['cases']) > 1 and any(case['kind'] == 'pause_resume' for case in manifest['cases'])
assert fingerprint(Path(manifest['source']).parent) == manifest['source_hashes']
assert all(Path(c['project']).resolve().is_relative_to(root / 'projects') for c in manifest['cases'])
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs)
app = QApplication.instance() or QApplication([])
logging = configure_logging(root / 'data')
store = TaskStore(root / 'data/task-center.db')
service = TaskCenterService(store, logging, supervised=True)
window = TrialTaskCenterWindow(service)
window.resize(1450, 1000)
window.show()
stamp = str(time.time_ns())
history = root / 'ui-history'
history.mkdir(exist_ok=True)
prior = root / 'ui-report.json'
if prior.exists():
shutil.copyfile(prior, history / (stamp + '-prior.json'))
results = {'mode': 'source Qt QTest visible mouse/keyboard UI, real supervised Mentor', 'started_ns': time.time_ns(), 'steps': [], 'failures': []}
shots = root / 'screenshots' / stamp
shots.mkdir(parents=True, exist_ok=True)
def record(step, **details):
results['steps'].append(dict(step=step, ns=time.time_ns(), **details))
write(root / 'ui-report.json', results)
window.grab().save(str(shots / f'{len(results["steps"]):02d}-{step}.png'))
print(json.dumps(results['steps'][-1], ensure_ascii=False), flush=True)
def wait(check, timeout=1200):
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
app.processEvents()
if check():
return
QTest.qWait(100)
raise TimeoutError('UI condition exceeded deadline')
def click(widget):
assert widget.isEnabled(), widget.objectName()
QTest.mouseClick(widget, Qt.MouseButton.LeftButton)
def text(widget, value):
widget.setFocus()
QTest.keyClick(widget, Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier)
app.clipboard().setText(str(value))
QTest.keyClick(widget, Qt.Key.Key_V, Qt.KeyboardModifier.ControlModifier)
def directory_dialog():
dialog = app.activeModalWidget()
if dialog is None or dialog.windowTitle() != '从目录创建工程任务':
QTimer.singleShot(100, directory_dialog)
return
text(dialog.findChild(QLineEdit, 'taskDirectory'), root / 'projects')
click(dialog.findChild(QPushButton, 'readTaskProjects'))
def create():
button = dialog.findChild(QDialogButtonBox).button(QDialogButtonBox.StandardButton.Ok)
if not button.isEnabled():
QTimer.singleShot(100, create)
return
record('directory-scanned')
click(button)
QTimer.singleShot(100, create)
def choose_bom():
dialog = app.activeModalWidget()
if not isinstance(dialog, QFileDialog):
QTimer.singleShot(100, choose_bom)
return
edit = dialog.findChild(QLineEdit, 'fileNameEdit')
text(edit, root / 'random-bom.xlsx')
QTest.keyClick(edit, Qt.Key.Key_Return)
def add_cell_rule(request, cell):
# Real rule dialog: load actual library choices, navigate the dropdown.
bar = window.mapping_tabs.tabBar()
QTest.mouseClick(bar, Qt.MouseButton.LeftButton, pos=bar.tabRect(0).center())
def fill():
dialog = app.activeModalWidget()
if dialog is None or dialog.windowTitle() != '替换规则':
QTimer.singleShot(100, fill)
return
text(dialog.old_edit, request['old_part_number'])
text(dialog.new_edit, request['new_part_number'])
click(dialog.cell_load_button)
def select():
if not dialog.cell_load_button.isEnabled():
QTimer.singleShot(100, select)
return
combo = dialog.cell_combo
index = combo.findData(cell)
if index < 0:
record('cell-choice-unavailable', expected=cell, status=dialog.cell_status.text())
click(dialog.buttons.button(QDialogButtonBox.StandardButton.Cancel))
return
combo.setFocus()
QTest.keyClick(combo, Qt.Key.Key_Home)
for _ in range(index):
QTest.keyClick(combo, Qt.Key.Key_Down)
record('cell-rule-selected', cell=combo.currentData(), refdes=request['refdes'])
click(dialog.buttons.button(QDialogButtonBox.StandardButton.Ok))
QTimer.singleShot(100, select)
QTimer.singleShot(100, fill)
click(window.add_mapping_button)
wait(lambda: not window._workers)
assert any(row['target_cell'] == cell for row in database(root, 'select * from rules'))
QTest.mouseClick(bar, Qt.MouseButton.LeftButton, pos=bar.tabRect(1).center())
try:
record('opened')
if window.auto_intervention_check.isChecked():
click(window.auto_intervention_check)
record('automatic-ai-disabled-for-independent-ui-acceptance')
if not database(root, 'select * from tasks'):
QTimer.singleShot(100, directory_dialog)
click(window.task_list.new_button)
wait(lambda: len(database(root, 'select * from tasks')) == len(manifest['cases']))
record('tasks-created', count=len(manifest['cases']))
wait(lambda: window.task_list.list.count() == len(manifest['cases']))
first = window.task_list.list.item(0)
QTest.mouseClick(window.task_list.list.viewport(), Qt.MouseButton.LeftButton,
pos=window.task_list.list.visualItemRect(first).center())
wait(window.plan_panel.import_bom_button.isEnabled)
cell_cases = [case for case in manifest['cases'] if case['target_cell']]
if cell_cases:
assert len(manifest['cases']) == 1, 'Cell supplemental UI uses one standalone task'
unique_rules = {(r['old_part_number'], r['new_part_number']): r for r in cell_cases[0]['requests']}
for request in unique_rules.values():
add_cell_rule(request, cell_cases[0]['target_cell'])
QTimer.singleShot(100, choose_bom)
click(window.plan_panel.import_bom_button)
wait(lambda: window.plan_panel._active_bom_import is None and window.plan_panel.last_bom_report is not None)
record('bom-imported', report=window.plan_panel.report_text, timings=import_timing(root))
if prepare_only:
record('prepare-only-finished')
return results
results['execution_source_hashes'] = code_fingerprint(Path(__file__).resolve().parents[1] / 'src')
results['execution_integration_hashes'] = code_fingerprint(Path(__file__).resolve().parents[1] / 'integration')
# Execute performs the single actual Save -> range confirmation UI flow.
def confirm():
dialog = app.activeModalWidget()
if not isinstance(dialog, QMessageBox):
QTimer.singleShot(100, confirm)
return
record('execution-confirmation', title=dialog.windowTitle(), text=dialog.text())
yes = dialog.button(QMessageBox.StandardButton.Yes)
if yes is None:
raise AssertionError('Unexpected modal instead of execution confirmation')
click(yes)
QTimer.singleShot(100, confirm)
button = window.findChild(QPushButton, 'executeProjectTasks')
wait(button.isEnabled)
click(button)
wait(lambda: bool(list((root / 'data/task-queues').glob('*.json'))))
record('execution-started')
last = None
paused_once = False
resumed = False
saved_before_resume = None
fault = next((case['fault'] for case in manifest['cases'] if case.get('fault')), None)
fault_stage_seen = None
forced = recovered = False
deadline = time.monotonic()+14400
while time.monotonic() < deadline:
app.processEvents()
tasks = database(root, 'select task_id,name,status,error_id from tasks order by group_position')
status = [(t['task_id'], t['status']) for t in tasks]
if status != last:
record('task-state', tasks=tasks)
last = status
queues_live = [json.loads(p.read_text(encoding='utf-8')) for p in (root / 'data/task-queues').glob('*.json')]
has_pause_window = any(
any(e['state'] == 'completed' for e in q['entries'].values())
and any(e['state'] == 'running' for e in q['entries'].values())
for q in queues_live)
if fault and not forced:
frames = [json.loads(p.read_text(encoding='utf-8')) for p in (root / 'data/tasks').glob('*/quick-run/worker-progress.json')]
in_stage = any(frame.get('stage') == fault['stage'] for frame in frames)
if in_stage and fault_stage_seen is None:
fault_stage_seen = time.monotonic()
if (in_stage and fault_stage_seen is not None
and time.monotonic()-fault_stage_seen >= fault['delay_seconds']
and window.run_panel.force_stop_button.isEnabled()):
QTimer.singleShot(100, confirm)
click(window.run_panel.force_stop_button)
forced = True
results['fault_injected'] = {'trigger': fault, 'frames': frames}
record('real-ui-force-stop-requested', fault=fault)
if pause and not paused_once and has_pause_window:
stop = window.run_panel.stop_queue_button
if stop.isEnabled():
click(stop)
paused_once = True
record('pause-requested')
if not window._workers:
queues = [json.loads(p.read_text(encoding='utf-8')) for p in (root / 'data/task-queues').glob('*.json')]
record('queue-idle', queues=queues)
if forced and not recovered:
for dialog in app.topLevelWidgets():
if dialog is not window and dialog.isVisible() and '替换结果' in dialog.windowTitle():
QTest.keyClick(dialog, Qt.Key.Key_Escape)
if window.run_panel.recover_button.isEnabled():
QTimer.singleShot(100, confirm)
click(window.run_panel.recover_button)
recovered = True
record('real-ui-recovery-requested')
QTest.qWait(500)
continue
record('force-stop-requires-manual-verification', message=window.run_panel.operator_band.text())
if paused_once and not resumed and window._project_queues:
saved_before_resume = saved_uids(root)
# Close actual result dialog to expose the same batch resume button.
for dialog in app.topLevelWidgets():
if dialog is not window and dialog.isVisible() and '替换结果' in dialog.windowTitle():
QTest.keyClick(dialog, Qt.Key.Key_Escape)
wait(button.isEnabled, timeout=30)
QTimer.singleShot(100, confirm)
click(button)
resumed = True
record('resume-confirmed', saved_uids=saved_before_resume)
QTest.qWait(500)
continue
break
QTest.qWait(500)
else:
raise TimeoutError('Actual execution still active; preserve process for observation')
results['tasks'] = database(root, 'select * from tasks')
if fault:
results['force_stop_actual'] = forced
results['recovery_actual'] = recovered
if saved_before_resume:
after = saved_uids(root)
assert all(after.get(key) == count for key, count in saved_before_resume.items()), 'Saved UID replayed on resume'
results['resume_saved_uid_no_replay'] = True
results['finished_ns'] = time.time_ns()
record('run-finished')
except BaseException:
results['failures'].append(traceback.format_exc())
write(root / 'ui-report.json', results)
raise
finally:
write(root / 'ui-report.json', results)
write(history / (stamp + '.json'), results)
# Keep Qt alive until owned workers release resources; never kill on timeout.
return results
def saved_uids(root):
events = []
for path in (root / 'data/tasks').glob('*/events.jsonl'):
for line in path.read_text(encoding='utf-8').splitlines():
event = json.loads(line)
if event.get('operation') == 'quick_run_executed' and event.get('details', {}).get('state') == 'saved_ok':
events.append((path.parent.name, event))
if not events:
return {}
try:
operations = database(root, '''SELECT o.task_id,o.command_json,o.receipt_json
FROM execution_operations o JOIN execution_rounds r
ON r.task_id=o.task_id AND r.round_id=o.round_id''')
bindings = {}
for row in operations:
receipt = json.loads(row['receipt_json'] or '{}')
if receipt.get('native_state') == 'saved_ok' and receipt.get('job_id'):
key = (row['task_id'], receipt['job_id'])
bindings.setdefault(key, []).append((json.loads(row['command_json']), receipt))
counts = Counter()
for task_id, event in events:
job = event['details']['timing']['job_id']
if not job or event.get('task_id', task_id) != task_id:
raise ValueError('Saved event task/job identity is missing or inconsistent')
command, receipt = bindings[(task_id, job)][0]
if len(bindings[(task_id, job)]) != 1:
raise ValueError('Saved event job is bound to multiple operations')
for uid in _saved_operation_uids(root, task_id, command, receipt):
counts[task_id + ':' + uid] += 1
return dict(counts)
except (OSError, sqlite3.Error, KeyError, TypeError, ValueError, IndexError) as error:
raise ValueError('Acceptance evidence insufficient: saved event job/UID binding: ' + str(error)) from error
def _saved_operation_uids(root, task_id, command, receipt):
if command.get('target_scope') == 'targets':
selectors = [selector.split('\x1f') for selector in command['target_selectors'].split('\x1e')]
if any(len(fields) != 3 or not re.fullmatch(r'\$\d+I\d+', fields[0]) for fields in selectors):
raise ValueError('Frozen target selectors lack exact native UIDs')
uids = [fields[0] for fields in selectors]
if len(set(uids)) != len(uids):
raise ValueError('Duplicate frozen selector UID')
return uids
if command.get('target_scope', 'all') != 'all' or command.get('target_selectors'):
raise ValueError('Unsupported saved operation scope')
from dx_productivity.trial_task_center.native_helper import read_snapshot, require_resumable_transaction
files = {Path(item['path']).resolve(strict=True): item['sha256'] for item in receipt['proof']['files']}
uids = set()
for path in files:
if not path.name.endswith('.native.json'):
continue
snapshot = Path(str(path).removesuffix('.native.json'))
owner = (root / 'data/tasks' / task_id).resolve()
if (not path.is_relative_to(owner) or snapshot not in files
or any(hashlib.sha256(p.read_bytes()).hexdigest() != files[p] for p in (path, snapshot))):
raise ValueError('Native receipt snapshot proof is missing, foreign or changed')
report = json.loads(path.read_text(encoding='utf-8'))
attempt = report['batch_attempt']
metadata, records = read_snapshot(snapshot)
if (report.get('ok') is not True or report.get('stage') != 'native_replace_verified'
or attempt['task_id'] != task_id or attempt['job_id'] != receipt['job_id']
or Path(metadata[1]).resolve() != Path(command['project_path']).resolve()
or [part.casefold() for part in metadata[2:4]] != [command['old_part'].casefold(), command['new_part'].casefold()]
or metadata[4] != command['schematic_name'] + ':' + command['sheet_number']):
raise ValueError('Native receipt does not bind this saved rule operation')
binding = require_resumable_transaction(snapshot, report, metadata, records)
uids.update(binding['source_uids'])
if not uids:
raise ValueError('Saved rule operation lacks proven native UIDs')
return sorted(uids)
def raw_attributes(path):
"""Independent tiny ASCII attribute reader, deliberately outside graph compare."""
result, ref = {}, None
raw = path.read_bytes()
try:
text = raw.decode('utf-8')
except UnicodeDecodeError:
text = raw.decode('mbcs')
for line in text.splitlines():
match = re.match(r' Symbol .+\tref des ([^\t]*)\tpage ', line)
if match:
ref = match[1]
if ref:
if ref in result:
raise ValueError('Independent acceptance requires unique root references')
result[ref] = {}
elif ref and line.startswith('\tProp '):
for name in ('Part Number', 'Part Label', 'Cell Name', 'Value'):
prefix = '\tProp ' + name + ' '
if line.startswith(prefix):
if name in result[ref]:
raise ValueError('Ambiguous raw attribute')
result[ref][name] = line[len(prefix):]
return result
def raw_identity_attributes(path):
"""Independent ASCII property multisets, retaining every gate and instance."""
data=path.read_bytes()
try:
text=data.decode('utf-8')
except UnicodeDecodeError:
text=data.decode('mbcs')
records=[]
current=None
for line in text.splitlines():
match=re.match(r' Symbol (.+?)\tref des ([^\t]*)\tpage ',line)
if match:
current={'source_uid':match[1],'refdes':match[2],'instance_path':'','properties':[], 'symbol':''}
records.append(current)
elif line.startswith((' Net ','Block ')):
current=None
elif current is not None:
if line.startswith('\tPath '):
value=line[6:].strip()
current['instance_path']='' if value in {'','root'} else value
elif line.startswith('\tProp '):
current['properties'].append(line[6:])
elif line.startswith('\tSymbol name '):
current['symbol']=line[13:]
if not records:
raise ValueError('Independent raw identity report contains no symbols')
return records
def unselected_raw_identities(records, selected_root_uids):
return Counter((row['source_uid'],row['instance_path'],row['refdes'],row['symbol'],tuple(sorted(row['properties'])))
for row in records if row['instance_path'] or row['source_uid'] not in selected_root_uids)
def selected_root_attributes(records, selected_root_uids):
result={}
found=set()
for row in records:
if row['instance_path'] or row['source_uid'] not in selected_root_uids:
continue
if row['source_uid'] in found or not row['refdes'] or row['refdes'] in result:
raise ValueError('Selected root UID/reference is not unique in independent ASCII')
found.add(row['source_uid'])
attrs={}
for prop in row['properties']:
for name in ('Part Number','Part Label','Cell Name','Value'):
if prop.startswith(name+' '):
if name in attrs:
raise ValueError('Selected root has ambiguous raw attribute: '+name)
attrs[name]=prop[len(name)+1:]
result[row['refdes']]=attrs
if found != selected_root_uids:
raise ValueError('Selected root UID is absent from independent ASCII')
return result
def force_recovery_evidence(root, *, expected_stage='native_replace', ui_report=None):
path=root/(ui_report or 'packaged-ui-report.json')
if ui_report is not None:
assert path.resolve().is_relative_to(root.resolve()) and path.is_file()
if path.exists():
report=json.loads(path.read_text(encoding='utf-8'))
assert report['stage']=='execute' and report.get('passed') is True
assert report['mode'].startswith('frozen EXE external Windows UIA')
assert Path(report['root']).resolve()==root.resolve()
session=json.loads((root/'ui-session.json').read_text(encoding='utf-8'))
assert report['pid']==session['pid'] and report['exe_sha256']==session['exe_sha256']
assert Path(report['exe']).resolve()==Path(session['executable']).resolve()
assert hashlib.sha256(Path(report['exe']).read_bytes()).hexdigest()==report['exe_sha256']
steps=[step['step'] for step in report['steps']]
assert 'real-ui-force-confirmed' in steps and 'real-ui-recovery-finished' in steps
assert steps.index('real-ui-force-confirmed') < steps.index('real-ui-recovery-finished')
forced=next(step for step in report['steps'] if step['step']=='real-ui-force-confirmed')
active=[frame for frame in forced['frames'] if frame.get('stage')==expected_stage]
assert active and all(re.fullmatch('[0-9a-f]{32}',frame.get('token',''))
and frame.get('job_id') and type(frame.get('sequence')) is int and frame['sequence']>0 for frame in active)
else:
path=root/'ui-report.json'
report=json.loads(path.read_text(encoding='utf-8'))
assert report.get('force_stop_actual') and report.get('recovery_actual')
return {'force_stop_actual':True,'recovery_observed':True,'ui_evidence':str(path),
'ui_evidence_sha256':hashlib.sha256(path.read_bytes()).hexdigest()}
def native_value_observation(text, *, job, uid, old, new):
"""Read count-complete raw COM groups; never derive baseline from reopened Value."""
decode = lambda value: re.sub(r'%([0-9a-fA-F]{4})', lambda m: chr(int(m[1], 16)), value)
groups, current, previous_sequence = [], None, 0
for line in text.lstrip('\ufeff').splitlines():
fields = [decode(field) for field in line.split('\t')]
if fields[0] == 'O':
if current is not None or len(fields) != 7 or fields[1] != job:
raise ValueError('Legacy, incomplete or foreign observation group')
sequence = int(fields[5])
if (sequence <= previous_sequence or (previous_sequence and sequence != previous_sequence+1)
or not 0 <= float(fields[4].replace(',', '.')) < 86400
or fields[6] not in {'before_native', 'pre_restore', 'restoring', 'save_pending', 'saved_readback'}):
raise ValueError('Invalid observation sequence or time')
current = {'job': fields[1], 'uid': fields[2], 'stage': fields[3], 'sequence': sequence,
'window': fields[6], 'attributes': {}}
elif fields[0] == 'E':
if (current is None or len(fields) != 7 or fields[1] != current['uid']
or int(fields[2]) != len(current['attributes']) or fields[6] != 'unknown'
or fields[3].casefold() in current['attributes']):
raise ValueError('Invalid attribute identity, ordinal or duplicate name')
current['attributes'][fields[3].casefold()] = fields[5] or fields[4]
elif fields[0] == 'Z_OBS':
if (current is None or len(fields) != 7
or fields[1:4] != [current['job'], current['uid'], current['stage']]
or int(fields[4]) != current['sequence'] or int(fields[5]) != len(current['attributes'])
or fields[6] != current['window']):
raise ValueError('Observation completion identity/count mismatch')
current['count'] = int(fields[5])
groups.append(current)
previous_sequence = current['sequence']
current = None
else:
raise ValueError('Unknown observation record')
if current is not None:
raise ValueError('Observation group has no completion marker')
selected = [group for group in groups if group['uid'] == uid]
seen_old, candidate = False, None
for index, group in enumerate(selected):
part = group['attributes'].get('part number')
if part == old and candidate is None and group['window'] == 'before_native':
seen_old = True
elif part == new and candidate is None:
if not seen_old or group['window'] != 'pre_restore':
raise ValueError('First target observation is outside the native pre-restoration window')
if not any(g['window'] in {'restoring', 'save_pending', 'saved_readback'} for g in selected[index+1:]):
raise ValueError('Native observation has no later restoration/save boundary')
candidate = group
elif part not in {old, new} or (candidate is not None and part != new):
raise ValueError('Observation Part Number differs from bound transaction')
if candidate is None:
raise ValueError('Bound native intermediate observation is missing')
reopened = next((g for g in reversed(selected) if g['sequence'] > candidate['sequence']
and g['window'] == 'saved_readback'), None)
result = {'sequence': candidate['sequence'], 'count': candidate['count'], 'stage': candidate['stage'],
'window': candidate['window'],
'value': candidate['attributes'].get('value', ''), 'present': 'value' in candidate['attributes'],
'part_label': candidate['attributes'].get('part label'), 'uid': uid, 'job': job}
if reopened is not None:
result.update(reopened_present='value' in reopened['attributes'], reopened_value=reopened['attributes'].get('value', ''),
reopened_sequence=reopened['sequence'], reopened_count=reopened['count'])
return result
def bound_native_observation(root, task_id, uid, request):
work = root / 'data/tasks' / task_id / 'quick-run'
matches = []
for path in work.glob('snapshot-*.tsv.native.json'):
record = json.loads(path.read_text(encoding='utf-8'))
transaction, attempt = record.get('transaction', {}), record.get('batch_attempt', {})
if uid not in transaction.get('source_uids', ()):
continue
snapshot = Path(record['snapshot']).resolve(strict=True)
if (not snapshot.is_relative_to(work.resolve()) or not record.get('ok')
or record.get('stage') != 'native_replace_verified' or attempt.get('task_id') != task_id
or transaction.get('old_part_number') != request['old_part_number']
or transaction.get('new_part_number') != request['new_part_number']
or hashlib.sha256(snapshot.read_bytes()).hexdigest() != transaction.get('snapshot_sha256')
or not record.get('native_options', {}).get('1700', {}).get('checked')):
raise ValueError('Native intermediate transaction binding is invalid')
library_row = record.get('library_row', ())
if len(library_row) != 7 or library_row[1] != request['new_part_number']:
raise ValueError('Raw selected library row does not match target Part Number')
job = attempt['job_id']
observations = work / ('attribute-observations-' + job + '.tsv')
result = native_value_observation(observations.read_text(encoding='utf-8-sig'), job=job, uid=uid,
old=request['old_part_number'], new=request['new_part_number'])
result.update(raw_observation=str(observations), native_transaction=str(path),
observation_sha256=hashlib.sha256(observations.read_bytes()).hexdigest(),
transaction_sha256=hashlib.sha256(path.read_bytes()).hexdigest(), library_row=list(library_row))
matches.append(result)
if len(matches) != 1:
raise ValueError('Native intermediate transaction is absent or ambiguous')
return matches[0]
def rule_netlist_evidence(root, task, entry, case, before):
"""Require the application's frozen rule -> native UID -> whole-graph result."""
assert not task['target_plan_mode'] and not task['copy_part_number_to_value']
request, = case['requests']
uid, = [uid for uid, comp in before['components'].items() if comp['refdes'] == request['refdes']]
assert not before['components'][uid].get('instance_path')
assert before['components'][uid]['attributes']['Part Number'] == request['old_part_number']
path = Path(entry['netlist_verification']['report_path']).resolve(strict=True)
assert path.is_relative_to((root / 'data/tasks' / task['task_id'] / 'netlist-checks').resolve())
report = json.loads(path.read_text(encoding='utf-8'))
plan_path = path.with_name('plan.json')
plan = json.loads(plan_path.read_text(encoding='utf-8'))
assert plan['rows'] == [] and plan['copy_value'] is False
assert Path(plan['project_path']).resolve() == Path(case['project']).resolve()
assert plan['rules'] == [{'old_part': request['old_part_number'].casefold(),
'new_part': request['new_part_number'].casefold(), 'value_mode': 'preserve',
'custom_value': '', 'sync_nc': '1', 'target_cell': ''}]
assert report['status'] == 'verified' and report['verified'] is True
assert all(report[side]['status'] == 'success' and report[side]['complete'] is True for side in ('before', 'after'))
scope, = report['rule_scopes']
assert scope['source_uids'] == [uid] and scope['schematic_name'] and scope['sheet_number']
assert Path(scope['project_path']).resolve() == Path(case['project']).resolve()
assert scope['old_part'].casefold() == request['old_part_number'].casefold()
assert scope['new_part'].casefold() == request['new_part_number'].casefold()
assert set(report['expected_changes']) == {uid}
return {'bound_uid': uid, 'rule_scope': scope, 'verification_report': str(path),
'verification_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'frozen_plan': str(plan_path), 'plan_sha256': hashlib.sha256(plan_path.read_bytes()).hexdigest()}
def queue_entries(root, *, queue_id=None):
result = {}
directory = root / 'data/task-queues'
if queue_id is not None:
if not isinstance(queue_id, str) or not re.fullmatch('[0-9a-f]{32}', queue_id):
raise ValueError('Invalid explicit queue identity')
paths = [directory / (queue_id + '.json')]
else:
paths = directory.glob('*.json')
for path in paths:
queue = json.loads(path.read_text(encoding='utf-8'))
reports = queue.get('netlist_verification', {})
for task_id, entry in queue.get('entries', {}).items():
result[task_id] = dict(entry)
if task_id in reports:
result[task_id]['netlist_verification'] = reports[task_id]
return result
def verify(root, *, queue_id=None, force_ui_report=None):
"""Fresh native CLI exports, independent comparisons, no Mentor fallback."""
from dx_productivity.trial_task_center.native_netlist import capture_project, export_netlist
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
before = json.loads(Path(manifest['baseline']).read_text(encoding='utf-8'))
references=Counter(c['refdes'] for c in before['components'].values() if c['refdes'])
complex_graph=(any(count>1 for count in references.values())
or any(c.get('instance_path') or c.get('ambiguous_attributes') for c in before['components'].values()))
original_identities=raw_identity_attributes(Path(manifest['baseline']).with_name('effective.txt')) if complex_graph else None
original_raw = {} if complex_graph else raw_attributes(Path(manifest['baseline']).with_name('effective.txt'))
tasks = database(root, 'select * from tasks')
projects = database(root, 'select * from projects')
entries = queue_entries(root, queue_id=queue_id)
stamp = str(time.time_ns())
if (root / 'independent-report.json').exists():
archive = root / 'independent-report-history'
archive.mkdir(exist_ok=True)
shutil.copyfile(root / 'independent-report.json', archive / (stamp + '.json'))
report = {'reader': 'Fresh native ASCII+Keyin CLI export; independent raw attributes and pin/net comparison',
'started_ns': int(stamp), 'preserve_contract': 'Preserve native Replace Part result, not old component Value.',
'cases': [], 'passed': False}
for case in manifest['cases']:
project = Path(case['project'])
row = next(p for p in projects if Path(p['path']).resolve() == project.resolve())
task = next(t for t in tasks if t['task_id'] == row['task_id'])
entry = entries.get(task['task_id'], {})
item = {'id': case['id'], 'kind': case['kind'], 'task_id': task['task_id'], 'task_status': task['status'], 'queue_entry': entry, 'passed': False}
try:
if case['kind'] == 'rule_mode':
item['rule_mode_evidence'] = rule_netlist_evidence(root, task, entry, case, before)
if entry.get('state') in {None, 'pending', 'running'}:
raise AssertionError('Whole-flow task has not reached a terminal acceptance state; do not count it')
expected_negative = case['kind'] in {'unknown_ref', 'stale_old', 'invalid_part', 'corrupt_database'}
if case['kind'] == 'corrupt_database':
assert entry.get('state') == 'failed'
assert hashlib.sha256((project.parent / 'database/icdb.dat').read_bytes()).hexdigest() == case['input_hashes']['database/icdb.dat']
item.update(passed=True, unchanged_corrupt_database=True)
else:
start = time.monotonic()
destination = root / 'independent' / stamp / f'{case["id"]:02d}'
output = export_netlist(capture_project(project, destination / 'capture'), destination / 'export')
assert output['complete'], output.get('reason')
after = output['graph']
selected = {request['refdes']: request for request in case['requests']}
if complex_graph:
selected_uids={uid for uid,c in before['components'].items() if c['refdes'] in selected}
if not expected_negative and case['kind'] != 'already_target':
assert len(selected_uids)==len(selected) and all(not before['components'][uid].get('instance_path') for uid in selected_uids)
preserved=set() if expected_negative or case['kind']=='already_target' else selected_uids
raw_identities=raw_identity_attributes(destination/'export/effective.txt')
assert unselected_raw_identities(original_identities,preserved)==unselected_raw_identities(raw_identities,preserved), 'Unselected raw instance/gate/property multiset changed'
original_raw=selected_root_attributes(original_identities,selected_uids)
raw=selected_root_attributes(raw_identities,selected_uids)
else:
raw = raw_attributes(destination / 'export/effective.txt')
# Physical endpoints and every unselected component must stay identical.
assert before['nets'] == after['nets'], 'Physical net endpoints changed'
assert before['components'].keys() == after['components'].keys(), 'Symbol identity coverage changed'
checks = []
for uid, old in before['components'].items():
new = after['components'][uid]
assert old['pins'] == new['pins'], f'Pins changed: {uid}'
ref = old['refdes']
if expected_negative or case['kind'] == 'already_target' or ref not in selected:
assert old == new, f'Unintended symbol modification: {ref or uid}'
if ref and not complex_graph:
assert original_raw[ref] == raw[ref], f'Unintended raw attribute modification: {ref}'
continue
request = selected[ref]
attrs = raw[ref]
if case['kind'] == 'force_stop' and task['status'] != 'completed':
assert attrs.get('Part Number') in {request['old_part_number'], request['new_part_number']}
checks.append({'refdes': ref, 'observed': attrs, 'requires_verification': True})
continue
assert attrs['Part Number'] == request['new_part_number']
if case['target_cell']:
assert attrs.get('Cell Name') == case['target_cell'], (ref, attrs)
mode = request['value_mode']
native = None
if mode in {'preserve', 'part_label'}:
try:
native = bound_native_observation(root, task['task_id'], uid, request)
except (OSError, KeyError, ValueError) as error:
checks.append({'refdes': ref, 'part_number': attrs['Part Number'], 'value': attrs.get('Value'),
'mode': mode, 'value_check': 'native_' + mode + '_not_independently_proven',
'reason': str(error)})
continue
expected_value = {'custom': request['custom_value'], 'part_number': request['new_part_number'],
'part_label': native['part_label'] if native else None,
'preserve': native['value'] if native else None}[mode]
if mode == 'part_label':
assert attrs.get('Part Label') == native['part_label'] == native['library_row'][5]
expected_present = native['present'] if mode == 'preserve' else True
if request['sync_nc'] and has_nc_marker(original_raw[ref].get('Value', '')) and not has_nc_marker(expected_value or ''):
expected_value = expected_value.rstrip('/') + '/NC'
expected_present = True
assert attrs.get('Value', '') == expected_value, (ref, attrs, expected_value)
check = {'refdes': ref, 'part_number': attrs['Part Number'], 'value': attrs.get('Value'), 'mode': mode,
'value_check': 'fresh_ascii_text_matches_declared_policy'}
if native:
check['native_intermediate'] = native
if 'reopened_present' in native:
assert native['reopened_present'] == expected_present
assert native['reopened_value'] == expected_value
check['presence_check'] = 'count_complete_raw_reopened_COM_observation'
else:
check['presence_check'] = 'not_proven_by_ASCII_absent_empty_serialization'
checks.append(check)
if case['kind'] == 'force_stop':
item.update(force_recovery_evidence(root,expected_stage=case['fault']['stage'],ui_report=force_ui_report))
assert entry.get('state') in {'paused', 'blocked', 'failed','completed'}, entry
assert all(count == 1 for count in saved_uids(root).values()), 'Saved UID replayed after interruption'
item['unknown_outcome_not_claimed_success'] = task['status'] != 'completed'
else:
expected_state = 'failed' if expected_negative else 'skipped' if case['kind'] == 'already_target' else 'completed'
assert entry.get('state') == expected_state, (task, entry, expected_state)
item.update(passed=True, physical_nets_unchanged=True, unselected_unchanged=True,
raw_attribute_checks=checks, seconds=time.monotonic()-start)
if any(check.get('value_check', '').endswith('_not_independently_proven') for check in checks):
item.update(passed=False, structural_and_part_number_passed=True,
unverified_reason='Native preserve intermediate was not independently observed; old Value is not its contract.')
except Exception:
item['failure'] = traceback.format_exc()
report['cases'].append(item)
write(root / 'independent-report.json', report)
print(json.dumps(item, ensure_ascii=False), flush=True)
assert fingerprint(Path(manifest['source']).parent) == manifest['source_hashes']
if manifest.get('library'):
assert hashlib.sha256(Path(manifest['library']['path']).read_bytes()).hexdigest() == manifest['library']['sha256']
if manifest.get('origin') == 'user':
for name in ('source_workbook', 'working_workbook'):
assert hashlib.sha256(Path(manifest[name]['path']).read_bytes()).hexdigest() == manifest[name]['sha256']
if manifest.get('expected_no_cad'):
from accept_random_packaged_ui import verify_no_cad_fixture
report['no_op_validation'] = verify_no_cad_fixture(root, manifest)
resource_errors = []
for path in (root / 'data/batch-resources').glob('*/session.json'):
record = json.loads(path.read_text(encoding='utf-8'))
cleanup = {} if record.get('cleanup') is None else record['cleanup']
if record.get('state') != 'released' or not isinstance(cleanup, dict) or cleanup.get('errors'):
resource_errors.append({'path': str(path), 'record': record})
for path in (root / 'data/tasks').glob('*/quick-run-history/native-inventory-*/native-inventory.json'):
record = json.loads(path.read_text(encoding='utf-8'))
if record.get('backend') != 'native_cli' or record.get('state') == 'fallback':
resource_errors.append({'path': str(path), 'reason': 'Inventory fallback or wrong backend'})
if record.get('cleanup', {}).get('errors') or Path(record['workspace']).exists():
resource_errors.append({'path': str(path), 'reason': 'Inventory resources not released'})
observation_path = root / 'desktop-observation.json'
if observation_path.exists():
observation = json.loads(observation_path.read_text(encoding='utf-8'))
if (observation['observer_errors'] or observation['owned_cad_became_foreground']
or observation['owned_cad_on_input_desktop']
or not all(observation['cad_exit_confirmed'].values())
or not all(observation['desktop_absent'].values())):
resource_errors.append({'path': str(observation_path), 'reason': 'Independent desktop/process observation failed'})
report.update(passed=all(c['passed'] for c in report['cases']) and not resource_errors,
source_unchanged=True, library_unchanged=True, resource_errors=resource_errors)
if queue_id is not None:
report['verified_queue_id'] = queue_id
write(root / 'independent-report.json', report)
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--source', type=Path)
parser.add_argument('--graph', type=Path)
parser.add_argument('--target-part', action='append')
parser.add_argument('--part-prefix', action='append', default=[])
parser.add_argument('--cell', action='append', default=[])
parser.add_argument('--seed', type=int)
parser.add_argument('--count', type=int, default=20)
parser.add_argument('--supplemental', choices=('valid_cell', 'force_stop', 'rule_mode','pon_root'), default='')
parser.add_argument('--run-ui', action='store_true')
parser.add_argument('--ui-prepare-only', action='store_true')
parser.add_argument('--verify', action='store_true')
args = parser.parse_args()
if args.verify:
verify(args.root.resolve(strict=True))
elif args.run_ui:
root = args.root.resolve(strict=True)
if args.ui_prepare_only:
run_ui(root, prepare_only=True)
else:
from private_desktop_observer import PrivateDesktopObserver
with PrivateDesktopObserver(root):
run_ui(root)
else:
if not args.source or not args.graph or not args.target_part:
parser.error('Prepare needs --source, --graph and --target-part')
manifest = prepare(args.root, args.source, json.loads(args.graph.read_text(encoding='utf-8')),
args.target_part, seed=args.seed, count=args.count, cells=args.cell, supplemental=args.supplemental,
part_prefixes=args.part_prefix or ('4100',))
workbook(args.root.resolve(), manifest)
print(json.dumps({'root': str(args.root.resolve()), 'seed': manifest['seed'], 'count': len(manifest['cases'])}))
if __name__ == '__main__':
main()
+611
View File
@@ -0,0 +1,611 @@
"""External UIA acceptance of a frozen EXE against disposable seeded projects.
Prepare projects/workbook with accept_random_cad.py first. Import never clicks
Execute and requires no CAD slot. Execute requires --run-native; it uses actual
UI save/confirmation/pause/resume controls. SQLite observations are read-only.
"""
from __future__ import annotations
import argparse
import ctypes
from ctypes import wintypes
import hashlib
import json
import os
import re
from pathlib import Path
import subprocess
import time
import traceback
from accept_packaged_ui import database, file_dialog, wait, verify_observation
from accept_random_cad import fingerprint, saved_uids, write
from packaged_window_driver import WindowDriver
from private_desktop_observer import PrivateDesktopObserver
def validate_fixture(root):
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
projects = (root / 'projects').resolve(strict=True)
source = Path(manifest['source']).resolve(strict=True)
if projects.is_relative_to(source.parent) or source.is_relative_to(root):
raise ValueError('Disposable fixture must be separate from original project')
if fingerprint(source.parent) != manifest['source_hashes']:
raise ValueError('Original source fingerprint changed')
paths = [Path(case['project']).resolve(strict=True) for case in manifest['cases']]
if not paths or len(paths) != len(set(paths)) or any(not p.is_relative_to(projects) for p in paths):
raise ValueError('Every case must name a distinct disposable project')
if not (root / 'random-bom.xlsx').is_file():
raise ValueError('Prepared random BOM workbook missing')
return manifest
def process_image(pid):
import win32api
process = win32api.OpenProcess(0x1000, False, pid)
try:
query = ctypes.windll.kernel32.QueryFullProcessImageNameW
query.argtypes = (wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD))
query.restype = wintypes.BOOL
value, size = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768)
if not query(int(process), 0, value, ctypes.byref(size)):
raise ctypes.WinError()
return Path(value.value).resolve(strict=True)
finally:
process.Close()
def validate_session(root, pid, executable, sha256):
session = json.loads((root / 'ui-session.json').read_text(encoding='utf-8'))
if (session.get('pid') != pid or Path(session['executable']).resolve() != executable
or session.get('exe_sha256') != sha256):
raise ValueError('Attach requires the exact process/EXE hash recorded for this isolated root')
def queue_records(root):
return {p.name: json.loads(p.read_text(encoding='utf-8'))
for p in (root / 'data/task-queues').glob('*.json')}
def queue_bindings(queues):
return {name: {'task_ids': row['task_ids'], 'plan_hashes': row['plan_hashes']}
for name, row in queues.items()}
def pause_ready(queues):
# One actual queue must still have work beyond its currently running item.
# Never combine an old completed queue with a new single-item execution.
return any({'completed', 'running', 'pending'} <= {entry['state'] for entry in row['entries'].values()}
for row in queues.values())
def pause_evidence(root, task_ids):
"""Copy observations only; never create a worker control or acknowledgement."""
observations=[]
for task_id in task_ids:
work=root/'data/tasks'/task_id/'quick-run'
for path in [work/'worker-progress.json',*work.glob('startup-pause-*.json')]:
if path.exists():
data=path.read_bytes()
observations.append({'task_id':task_id,'path':str(path),
'sha256':hashlib.sha256(data).hexdigest(),'record':json.loads(data.decode('utf-8'))})
return observations
def resources_settled(root):
records = [(p, json.loads(p.read_text(encoding='utf-8')))
for pattern in ('*/supervisor.json', '*/session.json')
for p in (root / 'data/batch-resources').glob(pattern)]
for path, row in records:
if path.name == 'supervisor.json':
if row.get('state') != 'finished':
return False
else:
cleanup = row.get('cleanup') or {}
proof = row.get('release_proof') or {}
released = (cleanup.get('desktop_handle_closed') is True
and (cleanup.get('desktop_confirmation') or {}).get('released') is True
and not cleanup.get('errors'))
observed = (proof.get('generation') == row.get('generation')
and proof.get('processes_exited') is True and proof.get('desktop_released') is True)
if row.get('state') != 'released' or not (released or observed):
return False
return True
def control_enabled(driver, automation_id):
control = driver.find(automation_id=automation_id, optional=True)
return control is not None and control.is_enabled()
def confirm(driver, record, title='确认顺序执行本批任务'):
def confirmation():
acknowledge_error_modal(driver, record)
return next((w for w in driver.windows() if w.window_text() == title), None)
dialog = wait(confirmation, timeout=60)
text = [c.window_text() for c in dialog.descendants() if c.window_text()]
record('execution-confirmation', title=dialog.window_text(), text=text)
for label in ('Yes', '&Yes', '是(&Y)', '是'):
try:
yes = driver.find(label, kind='Button', window=dialog)
break
except LookupError:
pass
else:
raise LookupError('Expected explicit batch execution confirmation')
driver.click(yes)
def close_results(driver):
import win32con, win32gui
for dialog in driver.windows():
if '替换结果' in dialog.window_text():
win32gui.PostMessage(dialog.handle, win32con.WM_CLOSE, 0, 0)
def acknowledge_error_modal(driver, record, *, expected=()):
"""Capture and acknowledge only this process's disabled-owner error modal."""
import win32con, win32gui, win32process
for dialog in driver.windows():
title = dialog.window_text()
if title not in {'操作未完成', '错误', 'Error'}:
continue
owner = win32gui.GetWindow(dialog.handle, win32con.GW_OWNER)
# Qt UIA can report enabled=True while the native owner is disabled.
if (win32process.GetWindowThreadProcessId(dialog.handle)[1] != driver.pid
or not owner or owner != driver.main().handle
or win32process.GetWindowThreadProcessId(owner)[1] != driver.pid
or win32gui.IsWindowEnabled(owner)):
continue
text = [c.window_text() for c in dialog.descendants() if c.window_text()]
buttons = [c for c in dialog.descendants(control_type='Button')
if c.window_text() in {'OK', '&OK', '确定', '确定(&O)'} and c.is_enabled()]
if len(buttons) != 1:
raise AssertionError('Owned error modal has no unique OK; preserve it for inspection')
anticipated = any(message in '\n'.join(text) for message in expected)
# record() captures the actual owned window surfaces before acknowledging.
record('owned-error-modal', pid=driver.pid, hwnd=dialog.handle, title=title,
native_owner_hwnd=owner, native_owner_disabled=True,
text=text, expected_supplement=anticipated)
driver.click(buttons[0])
wait(lambda: not any(w.handle == dialog.handle for w in driver.windows()), timeout=15)
record('owned-error-modal-acknowledged', hwnd=dialog.handle, expected_supplement=anticipated)
if not anticipated:
raise AssertionError('Unexpected application error modal; stop UI writes, do not replay saved UIDs')
return True
return False
def wait_for_ui(driver, record, check, *, timeout):
def observed():
acknowledge_error_modal(driver,record)
return check()
return wait(observed,timeout=timeout)
def disable_automatic_intervention(driver,record):
acknowledge_error_modal(driver,record)
intervention=driver.find(automation_id='dshAutoIntervention')
if intervention.get_toggle_state():
driver.click(intervention)
wait_for_ui(driver,record,lambda:not driver.find(automation_id='dshAutoIntervention').get_toggle_state(),timeout=15)
record('automatic-intervention-disabled')
def add_rules(driver, root, manifest, record):
cases = [case for case in manifest['cases'] if case.get('target_cell') or case['kind'] == 'rule_mode']
if not cases:
return
assert len(manifest['cases']) == 1, 'Rule supplemental uses one standalone task'
driver.click(driver.find('本批料号规则', kind='TabItem'))
unique = {(r['old_part_number'], r['new_part_number']): r for r in cases[0]['requests']}
for request in unique.values():
driver.click(driver.find(automation_id='addMappingButton'))
dialog = wait_for_ui(driver,record,lambda: next((w for w in driver.windows() if w.window_text() == '替换规则'), None), timeout=20)
edits = sorted(dialog.descendants(control_type='Edit'), key=lambda c: c.rectangle().top)
assert len(edits) == 3, 'Unexpected real rule dialog layout; do not guess inputs'
driver.type_text(edits[0], request['old_part_number'])
driver.type_text(edits[1], request['new_part_number'])
cell = cases[0].get('target_cell', '')
if cell:
driver.click(driver.find(automation_id='loadTargetCells', window=dialog))
wait_for_ui(driver,record,lambda: driver.find(automation_id='loadTargetCells', window=dialog).is_enabled(), timeout=120)
combo = driver.find(automation_id='targetCellCombo', window=dialog)
combo.select(cell)
assert combo.selected_text() == cell
record('authentic-cell-selected', cell=cell, request=request)
if cases[0]['kind'] == 'rule_mode':
for label, expected in [('启用此规则', True), ('替换后写入自定义 Value', False),
('识别并同步原 Value 中的 /NC', True)]:
assert bool(driver.find(label, kind='CheckBox', window=dialog).get_toggle_state()) == expected
driver.click(driver.find('确定', kind='Button', window=dialog))
wait_for_ui(driver,record,lambda: any(row['old_part_number'] == request['old_part_number']
and row['new_part_number'] == request['new_part_number'] and row.get('target_cell', '') == cell
for row in database(root, 'select * from rules')), timeout=60)
if cases[0]['kind'] != 'rule_mode':
driver.click(driver.find('本批位号计划', kind='TabItem'))
def verify_rule_mode(root, case):
tasks = database(root, 'select * from tasks')
assert len(tasks) == 1 and not tasks[0]['target_plan_mode'], 'Rule task unexpectedly entered target-plan mode'
assert not tasks[0]['copy_part_number_to_value'], 'Rule task changed default preserve Value policy'
assert not database(root, 'select * from pending_bom') and not database(root, 'select * from target_plan')
request, = case['requests']
rule, = database(root, 'select * from rules')
assert rule['old_part_number'] == request['old_part_number'] and rule['new_part_number'] == request['new_part_number']
assert rule['enabled'] and rule['sync_nc'] and not rule['custom_value_enabled']
assert not rule['custom_value'] and not rule['target_cell']
assert request['value_mode'] == 'preserve' and request['sync_nc'] is True
return tasks
def verify_no_cad_fixture(root, manifest):
assert all(case['kind'] == 'already_target' for case in manifest['cases'])
observation = json.loads((root / 'desktop-observation.json').read_text(encoding='utf-8'))
assert not observation['sessions'], 'Already-target user validation unexpectedly started CAD'
assert not saved_uids(root), 'Already-target user validation unexpectedly saved a replacement'
entries = [entry for queue in queue_records(root).values() for entry in queue['entries'].values()]
assert entries and all(entry['state'] == 'skipped' for entry in entries)
projects = {Path(case['project']).resolve() for case in manifest['cases']}
inventories = [json.loads(path.read_text(encoding='utf-8')) for path in
(root / 'data/tasks').glob('*/quick-run-history/native-inventory-*/native-inventory.json')]
assert inventories, 'Already-target acceptance needs an actual native inventory read'
assert all(row['backend'] == 'native_cli' and row['state'] == 'ready' and row['source_hashes_unchanged']
and Path(row['project']).resolve() in projects and not Path(row['workspace']).exists()
and not row.get('cleanup', {}).get('errors') for row in inventories)
for row in inventories:
cleanup = row['cleanup']
assert cleanup['workers_closed'] is True and cleanup['desktop_created'] is False and cleanup['processes']
assert all(process['exit_code'] == 0 and process['job_active_processes'] == 0
and process['process_handle_closed'] is True and process['job_handle_closed'] is True
and process['unconfirmed_descendant_handles'] == 0 and not process['errors']
and not process['forced_termination'] for process in cleanup['processes'])
return {'outcome': 'already_target_no_op', 'replacement_performed': False,
'application_netlist_verification': 'not_required',
'inventory_reads': len(inventories), 'requested_projects': len(projects), 'saved_uid_count': 0}
def business_results(root):
return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in (root / 'data/batch-resources').glob('*/business-result.json')}
class ExternalDesktopHold:
"""One independently owned reference; never close the application's handle."""
def __init__(self, root):
self.root, self.handle, self.name, self.session = root, None, None, None
def acquire(self):
if self.handle is not None:
return False
for path in (self.root / 'data/batch-resources').glob('*/session.json'):
row = json.loads(path.read_text(encoding='utf-8'))
if row.get('state') != 'ready' or not row.get('cad_pid'):
continue
name = row.get('desktop', '')
if (not re.fullmatch('dx-[0-9a-f]{32}', name)
or row.get('session_id') != path.parent.name):
raise ValueError('Resource fixture requires exact journal desktop namespace')
import win32service
self.handle = win32service.OpenDesktop(name, 0, False, 1)
self.name, self.session = name, path
return True
return False
def blocked(self):
if self.handle is None:
return False
row = json.loads(self.session.read_text(encoding='utf-8'))
cleanup = row.get('cleanup') or {}
result = self.session.with_name('business-result.json')
return (result.exists() and json.loads(result.read_text(encoding='utf-8')).get('payload', {}).get('business_succeeded') is True
and cleanup.get('desktop_handle_closed') is True
and (cleanup.get('desktop_confirmation') or {}).get('released') is False)
def release(self):
if self.handle is not None:
self.handle.CloseDesktop()
self.handle = None
def import_fixture(driver, root, manifest, record):
acknowledge_error_modal(driver,record)
if not database(root, 'select * from tasks'):
driver.click(driver.find(automation_id='newTaskButton'))
dialog = wait_for_ui(driver,record,lambda: next((w for w in driver.windows()
if w.window_text() == '从目录创建工程任务'), None), timeout=20)
driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(root / 'projects'))
driver.click(driver.find(automation_id='readTaskProjects', window=dialog))
create = driver.find('创建任务', kind='Button', window=dialog)
wait_for_ui(driver,record,create.is_enabled, timeout=60)
record('directory-scanned', cases=len(manifest['cases']))
driver.click(create)
wait_for_ui(driver,record,lambda: len(database(root, 'select * from tasks')) == len(manifest['cases']), timeout=90)
observed = {Path(row['path']).resolve() for row in database(root, 'select path from projects')}
assert observed == {Path(c['project']).resolve() for c in manifest['cases']}
record('tasks-created', tasks=database(root, 'select * from tasks'))
if any(case['kind'] == 'rule_mode' for case in manifest['cases']):
assert len(manifest['cases']) == 1, 'Rule mode is a standalone supplemental'
if not database(root, 'select * from rules'):
add_rules(driver, root, manifest, record)
tasks = verify_rule_mode(root, manifest['cases'][0])
record('rule-mode-defaults-confirmed', tasks=tasks, rules=database(root, 'select * from rules'))
return
driver.click(driver.find('本批位号计划', kind='TabItem'))
button = driver.find(automation_id='importBomPlan')
wait_for_ui(driver,record,button.is_enabled, timeout=90)
existing = database(root, 'select * from pending_bom')
if existing or database(root, 'select * from target_plan'):
record('existing-ui-import-retained', drafts=existing)
return
add_rules(driver, root, manifest, record)
driver.click(button)
file_dialog(driver, root / 'random-bom.xlsx')
# Observe completed report through accessibility, never application objects.
wait_for_ui(driver,record,lambda: driver.find(automation_id='importBomPlan').is_enabled(), timeout=1200)
title = driver.find(automation_id='toggleBomReport').window_text()
record('excel-imported', report=title)
# Current candidates save source drafts immediately and defer native
# inventory until execution. Earlier candidates expose checked previews.
assert '待核验' in title or '未检查 0' in title, title
drafts = database(root, 'select * from pending_bom')
if drafts:
record('batch-source-drafts-saved-by-import', drafts=drafts)
return
record('before-batch-save', targets=database(root, 'select * from target_plan'))
driver.click(driver.find(automation_id='saveTargetPlan'))
wait_for_ui(driver,record,lambda: driver.find(automation_id='saveTargetPlan').is_enabled(), timeout=120)
drafts = database(root, 'select * from pending_bom')
targets = database(root, 'select * from target_plan')
assert drafts or targets, 'Real UI Save did not persist a plan'
record('batch-plan-saved', drafts=drafts, targets=targets)
def execute_fixture(driver, root, record, *, pause, fault=None, hold=None):
forced = recovered = False
def check_modal():
expected = []
if fault and forced and not recovered:
expected.append('操作已强制中断,结果待核验。')
if hold is not None and hold.name is not None:
expected.append('后台资源尚未确认释放,请使用“重新清理资源”后再开始下一批。')
acknowledge_error_modal(driver, record, expected=expected)
def ui_wait(check, *, timeout):
def observed():
check_modal()
return check()
return wait(observed, timeout=timeout)
check_modal()
intervention = driver.find(automation_id='dshAutoIntervention')
if intervention.get_toggle_state():
driver.click(intervention)
assert not intervention.get_toggle_state(), 'Automatic external intervention must be disabled'
record('automatic-intervention-disabled')
button = driver.find(automation_id='executeProjectTasks')
ui_wait(button.is_enabled, timeout=90)
previous = queue_records(root)
driver.click(button)
confirm(driver, record)
ui_wait(lambda: queue_records(root) != previous, timeout=120)
record('execution-started')
paused = resumed = False
before_resume = None
last = None
fault_seen = None
fault_binding = None
deadline = time.monotonic() + 14400
while time.monotonic() < deadline:
check_modal()
queues = queue_records(root)
if hold is not None:
if hold.acquire():
record('external-test-reference-opened', desktop=hold.name)
if hold.blocked():
before = business_results(root)
saved = saved_uids(root)
record('completed-business-desktop-still-present', desktop=hold.name, results=before)
hold.release()
close_results(driver)
cleanup = driver.find(automation_id='cleanupBatchResources')
ui_wait(cleanup.is_enabled, timeout=60)
driver.click(cleanup)
ui_wait(lambda: resources_settled(root)
and not control_enabled(driver, 'stopQueueButton'), timeout=180)
check_modal()
assert business_results(root) == before and saved_uids(root) == saved
record('resource-only-cleanup-confirmed-no-replay', results=before, queues=queue_records(root))
return
if fault and not forced:
frames = [json.loads(path.read_text(encoding='utf-8'))
for path in (root / 'data/tasks').glob('*/quick-run/worker-progress.json')
if time.time() - path.stat().st_mtime < 5]
active = [frame for frame in frames if frame.get('stage') == fault['stage']
and re.fullmatch('[0-9a-f]{32}', str(frame.get('token', '')))
and frame.get('job_id') and type(frame.get('sequence')) is int and frame['sequence'] > 0]
binding = [(frame['token'], frame['job_id']) for frame in active]
if not active:
fault_seen = fault_binding = None
elif fault_seen is None or binding != fault_binding:
fault_seen = time.monotonic()
fault_binding = binding
force = driver.find(automation_id='forceStopButton')
if (active and fault_seen is not None and time.monotonic() - fault_seen >= fault['delay_seconds']
and force.is_enabled()):
driver.click(force)
confirm(driver, record, '强制结束当前操作')
forced = True
record('real-ui-force-confirmed', frames=frames)
signature = json.dumps(queues, sort_keys=True)
if signature != last:
record('queue-state', queues=queues, tasks=database(root, 'select * from tasks'))
last = signature
running = any(entry['state'] == 'running' for q in queues.values() for entry in q['entries'].values())
stop = driver.find(automation_id='stopQueueButton', optional=True)
if pause and not paused and pause_ready(queues) and stop is not None and stop.is_enabled():
observed=pause_evidence(root,[task_id for q in queues.values() for task_id,entry in q['entries'].items()
if entry['state']=='running'])
driver.click(stop)
paused = True
record('pause-requested',observed_before_click=observed)
if not running and queues and resources_settled(root) and (stop is None or not stop.is_enabled()):
if fault and forced and not recovered:
close_results(driver)
recovery = driver.find(automation_id='recoverQuickRunButton')
ui_wait(recovery.is_enabled, timeout=60)
before = saved_uids(root)
before_supervisors = set((root / 'data/batch-resources').glob('*/supervisor.json'))
driver.click(recovery)
confirm(driver, record, '核验并恢复')
ui_wait(lambda: set((root / 'data/batch-resources').glob('*/supervisor.json')) != before_supervisors, timeout=60)
ui_wait(lambda: resources_settled(root) and not control_enabled(driver, 'stopQueueButton'), timeout=1200)
after = saved_uids(root)
assert all(after.get(key) == value for key, value in before.items())
recovered = True
record('real-ui-recovery-finished', saved_uids=after)
break
if any(entry['state']=='blocked' for q in queues.values() for entry in q['entries'].values()):
raise AssertionError('Queue stopped with blocked/uncertain entries; do not replay')
unfinished = any(entry['state'] in {'pending', 'paused'}
for q in queues.values() for entry in q['entries'].values())
if paused and not resumed and unfinished:
before_resume = saved_uids(root)
bindings = queue_bindings(queues)
paused_state = queue_records(root)
record('pause-settled-evidence',observations=pause_evidence(root,
[task_id for q in queues.values() for task_id in q['entries']]),saved_uids=before_resume)
# Close only result windows of this executable to expose resume.
close_results(driver)
ui_wait(lambda: driver.find(automation_id='executeProjectTasks').is_enabled(), timeout=60)
driver.click(driver.find(automation_id='executeProjectTasks'))
confirm(driver, record)
ui_wait(lambda: queue_records(root) != paused_state, timeout=120)
assert queue_bindings(queue_records(root)) == bindings, 'Resume changed queue/task/plan binding'
resumed = True
record('resume-confirmed', saved_uids=before_resume, queue_bindings=bindings)
time.sleep(1)
continue
if all(q.get('phase') == 'finished' for q in queues.values()):
break
if any(entry['state'] in {'blocked', 'paused'}
for q in queues.values() for entry in q['entries'].values()):
raise AssertionError('Queue stopped with blocked/uncertain entries; do not replay')
time.sleep(.5)
else:
raise TimeoutError('Execution deadline; preserve live owned application for inspection')
if pause:
assert paused and resumed, 'Pause/resume was not actually exercised'
if fault:
assert forced and recovered, 'Force/recovery was not actually exercised'
if hold is not None:
raise AssertionError('External resource reference did not reach the completed-business release boundary')
if before_resume is not None:
after = saved_uids(root)
assert all(after.get(key) == count for key, count in before_resume.items()), 'Saved UID replayed'
check_modal()
record('execution-finished', queues=queue_records(root), saved_uids=saved_uids(root))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--exe', type=Path, required=True)
parser.add_argument('--expected-sha256', help='Reject a rebuilt or unintended candidate before launch')
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--pid', type=int, help='Attach only to this exact executable process')
parser.add_argument('--stage', choices=('import', 'execute'), default='import')
parser.add_argument('--run-native', action='store_true')
parser.add_argument('--no-pause', action='store_true')
parser.add_argument('--resource-hold', action='store_true', help='Hold one test-owned desktop reference through completed business')
args = parser.parse_args()
if args.stage == 'execute' and not args.run_native:
parser.error('Execution requires --run-native and exclusive CAD slot')
root, executable = args.root.resolve(strict=True), args.exe.resolve(strict=True)
manifest = validate_fixture(root)
fault = next((case.get('fault') for case in manifest['cases'] if case.get('fault')), None)
rule_mode = any(case['kind'] == 'rule_mode' for case in manifest['cases'])
if rule_mode and (len(manifest['cases']) != 1 or args.resource_hold or fault):
parser.error('Rule mode requires one standalone supplemental without force/resource injection')
if (args.resource_hold or fault) and len(manifest['cases']) != 1:
parser.error('Fault/resource supplemental must use one standalone disposable case')
if args.resource_hold and (args.stage != 'execute' or fault):
parser.error('Resource hold requires execute and cannot combine with force fault')
if executable.suffix.lower() != '.exe':
parser.error('A frozen Windows executable is required')
if not args.pid and (root / 'data').exists():
parser.error('New launch requires a fresh data root; use --pid to continue owned UI')
stamp = str(time.time_ns())
report = {'mode': 'frozen EXE external Windows UIA; no source UI or service calls',
'stage': args.stage, 'exe': str(executable), 'exe_sha256': hashlib.sha256(executable.read_bytes()).hexdigest(),
'root': str(root), 'seed': manifest['seed'], 'started_ns': time.time_ns(), 'passed': False, 'steps': []}
if args.expected_sha256 and report['exe_sha256'] != args.expected_sha256.lower():
parser.error('Executable SHA256 does not match the admitted candidate')
process = None
log = (root / ('exe-' + stamp + '.log')).open('w', encoding='utf-8')
try:
if args.pid:
pid = args.pid
validate_session(root, pid, executable, report['exe_sha256'])
else:
command = [str(executable), '--data-root', str(root / 'data')]
temporary = root / 'process-temp'
temporary.mkdir(exist_ok=True)
environment = dict(os.environ, TEMP=str(temporary), TMP=str(temporary))
process = subprocess.Popen(command, cwd=executable.parent, env=environment,
stdout=log, stderr=subprocess.STDOUT)
pid = process.pid
report['command'] = command
report['process_temp'] = str(temporary)
assert process_image(pid) == executable
report['pid'] = pid
write(root / 'ui-session.json', {'pid': pid, 'executable': str(executable), 'exe_sha256': report['exe_sha256']})
driver = WindowDriver(pid, root / 'packaged-recording' / stamp)
def record(step, **details):
driver.record(step)
report['steps'].append({'step': step, 'ns': time.time_ns(), **details})
write(root / 'packaged-ui-report.json', report)
print(json.dumps({'step': step, 'ns': report['steps'][-1]['ns']}, ensure_ascii=False), flush=True)
record('frozen-executable-opened')
disable_automatic_intervention(driver,record)
hold = ExternalDesktopHold(root) if args.resource_hold else None
with PrivateDesktopObserver(root):
try:
if args.stage == 'import':
import_fixture(driver, root, manifest, record)
else:
if not args.pid:
import_fixture(driver, root, manifest, record)
if rule_mode:
verify_rule_mode(root, manifest['cases'][0])
execute_fixture(driver, root, record, pause=not args.no_pause and len(manifest['cases']) > 1
and not fault and hold is None and not rule_mode,
fault=fault, hold=hold)
finally:
if hold is not None:
hold.release()
if args.stage == 'import':
observation = json.loads((root / 'desktop-observation.json').read_text(encoding='utf-8'))
assert not observation['sessions'], 'Import unexpectedly opened Mentor'
assert not queue_records(root), 'Import must not execute any queue'
else:
verify_observation(root / 'desktop-observation.json', require_sessions=not manifest.get('expected_no_cad', False))
if manifest.get('expected_no_cad'):
record('no-cad-user-validation-confirmed', **verify_no_cad_fixture(root, manifest))
assert fingerprint(Path(manifest['source']).parent) == manifest['source_hashes']
assert hashlib.sha256(executable.read_bytes()).hexdigest() == report['exe_sha256']
report['original_source_unchanged'] = report['executable_unchanged'] = True
report['passed'] = True
except BaseException:
report['failure'] = traceback.format_exc()
raise
finally:
report['finished_ns'] = time.time_ns()
write(root / ('packaged-ui-report-' + stamp + '.json'), report)
write(root / 'packaged-ui-report.json', report)
log.close()
# Keep the exact app available for review/continuation; never kill it.
if __name__ == '__main__':
main()
+59
View File
@@ -0,0 +1,59 @@
/** Test-only observer of actual session cwd and resolved sandbox policy. */
import {writeFile,rename,mkdtemp,rm} from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
const normalized=value=>path.resolve(value).toLowerCase();
export function workspaceCandidates(state,previousIds,root){
const fresh=state.sessions.filter(session=>!previousIds.has(session.id));
if(fresh.length)return fresh;
return state.sessions.length===1&&normalized(state.sessions[0].cwd)===normalized(root)?state.sessions:[];
}
export function verifyWorkspaces(sessions,root){
assert.ok(sessions.length,'No actual active-session workspace proof');
for(const session of sessions){
assert.equal(normalized(session.cwd),normalized(root),'Active session cwd mismatch');
assert.equal(normalized(session.sandbox.workspaceRoot),normalized(root),'Resolved sandbox root mismatch');
assert.equal(session.sandbox.mode,'workspace-write');
}
}
export function observeRuntime(ctx){
const filename=process.env.DX_ACCEPTANCE_STATE_FILE;
if(!filename)return;
let pending=false;
const proofs=new Map();
const tick=async()=>{
if(pending)return;pending=true;
try{
const sessions=[];
for(const session of ctx.sessions.list()){
const cwd=ctx.workingDirectory.get(session),sandbox=ctx.sandboxPolicy.resolve({session});
if(!proofs.has(session.id)){
proofs.set(session.id,await verifyShell(ctx,cwd,sandbox).catch(error=>({passed:false,error:error.message})));
}
sessions.push({id:session.id,cwd,sandbox,shell_preflight:proofs.get(session.id)});
}
const value={at:new Date().toISOString(),sessions};
await writeFile(filename+'.tmp',JSON.stringify(value));await rename(filename+'.tmp',filename);
}finally{pending=false;}
};
const timer=setInterval(()=>void tick().catch(()=>{}),250);timer.unref();void tick();
}
/** No LLM call: exercise the same official executor with the actual session policy. */
export async function verifyShell(ctx,cwd,sandbox){
const python=process.env.DX_ACCEPTANCE_PYTHON;
assert.ok(python,'DX_ACCEPTANCE_PYTHON required for actual shell preflight');
assert.equal(sandbox.mode,'workspace-write');
const directory=await mkdtemp(path.join(cwd,'.acceptance-shell-'));
const quote=value=>"'"+value.replaceAll("'","''")+"'";
try{
const script=path.join(directory,'probe.py');
await writeFile(script,'import json\nprint(json.dumps({"shell_preflight":42}))\n');
const command=`$ErrorActionPreference='Stop'; & ${quote(python)} -c 'print(314159)'; if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}; & ${quote(python)} ${quote(script)}; if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}; $items=@(Get-ChildItem -LiteralPath ${quote(directory)}); if($items.Name -notcontains 'probe.py'){throw 'Missing probe.py'}; Write-Output 'LIST_OK'`;
const process=await ctx.shell.execute(ctx.shell.resolve({command,workdir:cwd,sandboxPolicy:sandbox,timeoutMs:30000}));
const result=await process.result();
const proof={exit_code:result.exitCode,stdout:result.stdout.text,stderr:result.stderr.text,sandbox:result.sandbox,
command,passed:result.exitCode===0&&!result.timedOut&&!result.aborted&&result.stdout.text.includes('314159')&&result.stdout.text.includes('"shell_preflight": 42')&&result.stdout.text.includes('LIST_OK')};
return proof;
}finally{await rm(directory,{recursive:true,force:true});}
}
+14
View File
@@ -0,0 +1,14 @@
"""Disposable acceptance roots that preserve the application's inherited ACL.
Python's Windows tempfile.mkdtemp uses mode 0700; its OWNER RIGHTS-only read
grant does not authorize the official Harness restricted shell token.
"""
from pathlib import Path
from uuid import uuid4
def create_workspace_root(parent: Path, prefix: str) -> Path:
parent.mkdir(parents=True, exist_ok=True)
root = parent / (prefix + uuid4().hex)
root.mkdir() # Default inherited ACL, not tempfile's private 0700 ACL.
return root.resolve()
+10 -24
View File
@@ -1,33 +1,19 @@
"""Render the editable SVG into the runtime PNG and Windows multi-size ICO."""
from io import BytesIO
"""Export the approved PNG master into application and documentation icons."""
from pathlib import Path
from PIL import Image
from PySide6.QtCore import QBuffer, QIODevice, Qt
from PySide6.QtGui import QImage, QPainter
from PySide6.QtSvg import QSvgRenderer
def main():
assets = Path(__file__).resolve().parents[1] / 'src/dx_productivity/trial_task_center/assets'
renderer = QSvgRenderer(str(assets / 'app.svg'))
if not renderer.isValid():
raise ValueError('Invalid application icon SVG')
canvas = QImage(512, 512, QImage.Format.Format_ARGB32)
canvas.fill(Qt.GlobalColor.transparent)
painter = QPainter(canvas)
try:
renderer.render(painter)
finally:
painter.end()
buffer = QBuffer()
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
if not canvas.save(buffer, 'PNG'):
raise OSError('Cannot render application icon')
payload = bytes(buffer.data())
(assets / 'app.png').write_bytes(payload)
with Image.open(BytesIO(payload)) as image:
image.save(assets / 'app.ico', sizes=[(n, n) for n in (16, 20, 24, 32, 40, 48, 64, 96, 128, 256)])
root = Path(__file__).resolve().parents[1]
assets = root / 'src/dx_productivity/trial_task_center/assets'
with Image.open(assets / 'app-master.png') as source:
image = source.convert('RGBA')
if image.size != (1024, 1024):
raise ValueError('Application icon master must be 1024x1024')
image.save(assets / 'app.png')
image.save(assets / 'app.ico', sizes=[(n, n) for n in (16, 20, 24, 32, 40, 48, 64, 96, 128, 256)])
image.save(root / 'docs/user/media/app-icon.png')
print(assets / 'app.ico')
+24
View File
@@ -0,0 +1,24 @@
/** Model-free behavioral regression through the installed official ACL runner. */
import {spawnSync} from 'node:child_process';
import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path';
const [root,python]=process.argv.slice(2);
const workspace=path.join(root,'workspace'),temp=path.join(root,'temp');
await mkdir(workspace,{recursive:true});await mkdir(temp,{recursive:true});
const script=path.join(workspace,'probe.py');
await writeFile(script,'import json\nprint(json.dumps({"probe":42}))\n');
const q=value=>"'"+value.replaceAll("'","''")+"'";
const commands={inline:`& ${q(python)} -c 'print(314159)'; exit $LASTEXITCODE`,
script:`& ${q(python)} ${q(script)}; exit $LASTEXITCODE`,
listing:`$ErrorActionPreference='Stop'; Get-ChildItem -LiteralPath ${q(workspace)} | ForEach-Object {$_.Name}`};
const results={root,workspace,commands};
for(const [name,command] of Object.entries(commands)){
const result=spawnSync(process.execPath,['integration/dsh/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/runner.js',
'--workspace',workspace,'--temp',temp,'--mode','workspace-write','--',
path.join(process.env.SystemRoot,'System32/WindowsPowerShell/v1.0/powershell.exe'),
'-NoLogo','-NoProfile','-NonInteractive','-Command',command],{encoding:'utf8',timeout:30000});
results[name]={exit_code:result.status,stdout:result.stdout,stderr:result.stderr,error:result.error?.message};
}
results.acl=spawnSync('icacls',[root],{encoding:'utf8'}).stdout;
results.user_sid=spawnSync('whoami',['/user'],{encoding:'utf8'}).stdout;
console.log(JSON.stringify(results));
+23
View File
@@ -0,0 +1,23 @@
/** Check actual shell file access separately from model behavior. */
import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {bootRuntime} from '../integration/dsh/start.mjs';
const base=process.argv.includes('--local-appdata')?path.join(process.env.LOCALAPPDATA,'DxProductivity/acceptance-shell'):os.tmpdir();
await mkdir(base,{recursive:true});
const root=await mkdtemp(path.join(base,'shell-check-'));
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
process.env.DX_DSH_HOME=path.join(root,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"","revision":"shell-check"}');
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'Shell check');
const {sessionId}=await ctx.sessionController.create({workspaceId:workspace.id});
const agent=ctx.agents.get(sessionId);
const filename=path.join(process.env.DX_DSH_WORKSPACE,'input.txt');
await writeFile(filename,'SHELL_FILE_READ_OK');
const result=await ctx.tools.execute({agent,callId:crypto.randomUUID(),name:'pwsh',
arguments:{description:'Read the owned shell verification file',command:`[System.IO.File]::ReadAllText('${filename.replaceAll("'","''")}')`},signal:AbortSignal.timeout(30000)});
console.log(JSON.stringify({root,result}));
}finally{await shutdown.shutdown(0);}
+20
View File
@@ -0,0 +1,20 @@
/** Model-free integration check of the runtime observer's official executor path. */
import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path';
import {bootRuntime} from '../integration/dsh/start.mjs';
import {verifyShell} from './acceptance_runtime_state.mjs';
const [root,python]=process.argv.slice(2);
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
process.env.DX_DSH_HOME=path.join(root,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
process.env.DX_ACCEPTANCE_PYTHON=python;
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"","revision":"shell-preflight"}');
const profile=path.join(process.env.DX_DSH_HOME,'profiles/dx-task');
await mkdir(profile,{recursive:true});
await writeFile(path.join(profile,'cordis.patch.yml'),JSON.stringify([{id:'pwsh-sandbox',config:{pwshPath:path.join(process.env.SystemRoot,'System32/WindowsPowerShell/v1.0/powershell.exe')}}]));
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const workspace=process.env.DX_DSH_WORKSPACE;
const proof=await verifyShell(ctx,workspace,ctx.sandboxPolicy.resolve());
console.log(JSON.stringify(proof));if(!proof.passed)process.exitCode=1;
}finally{await shutdown.shutdown(0);}
+14 -2
View File
@@ -1,14 +1,26 @@
/** Tiny CDP driver for the real Qt Chromium page; no browser mocks. */
import {writeFile} from 'node:fs/promises';
export async function connect(port=9226,{loading=false}={}) {
export async function awaitRuntimeOrigin(client,expected,{timeoutMs=60000,delayMs=100}={}){
const end=Date.now()+timeoutMs;
while(Date.now()<end){
const actual=await client.evaluate('location.origin');
if(actual===expected)return;
if(actual!=='null'&&actual!=='')throw Error(`CDP target belongs to another runtime: ${actual}`);
await new Promise(resolve=>setTimeout(resolve,delayMs));
}
throw Error('Owned runtime navigation did not commit before the setup deadline');
}
export async function connect(port=9226,{loading=false,expectedOrigin}={}) {
let target;
const deadline=Date.now()+60000;
while(Date.now()<deadline){
let targets;
try{targets=await fetch(`http://127.0.0.1:${port}/json`,{signal:AbortSignal.timeout(10000)}).then(r=>r.json());}
catch{await new Promise(resolve=>setTimeout(resolve,100));continue;}
target=targets.find(x=>x.type==='page'&&(loading?x.url?.startsWith('file:'):x.url?.startsWith('http://127.0.0.1:')));
target=targets.find(x=>x.type==='page'&&(loading?x.url?.startsWith('file:'):x.url?.startsWith('http://127.0.0.1:'))
&&(!expectedOrigin||new URL(x.url).origin===expectedOrigin));
if(target)break;
await new Promise(resolve=>setTimeout(resolve,100));
}
+31
View File
@@ -0,0 +1,31 @@
/** Record an acceptance interruption and skip clarification, never change OS rights. */
import {appendFile,readFile} from 'node:fs/promises';
import path from 'node:path';
import {connect} from './dsh_cdp.mjs';
export async function skipQuestion(c,output,id){
const selector=`[...document.querySelectorAll('button')].find(e=>e.innerText.trim()==='跳过'&&e.getBoundingClientRect().width>0)`;
if(!await c.evaluate(`!!(${selector})`))return false;
const text=await c.evaluate('document.body.innerText.slice(-4000)');
await appendFile(path.join(output,'interventions.jsonl'),JSON.stringify({id,at:new Date().toISOString(),
action:'skip-model-question',reason:'Inputs and task are complete; acceptance does not authorize OS permission changes',text})+'\n');
await c.click(selector);return true;
}
if(process.argv[1]?.endsWith('dsh_skip_question.mjs')){
const c=await connect(Number(process.argv[2]));
try{
const output=path.resolve(process.argv[3]);
do{
let report;
try{report=JSON.parse(await readFile(path.join(output,'report.json'),'utf8'));}
catch(error){
if(process.argv[4]!=='--watch'||!(error instanceof SyntaxError))throw error;
await new Promise(resolve=>setTimeout(resolve,100));continue;
}
if(report.status)break;
const id=report.samples.at(-1)?.id??process.argv[4];
if(await skipQuestion(c,output,id))console.log(JSON.stringify({id,skipped:true}));
if(process.argv[4]!=='--watch')break;
await new Promise(resolve=>setTimeout(resolve,1000));
}while(true);
}finally{c.close();}
}
+30
View File
@@ -0,0 +1,30 @@
/** Extract shell invocation receipts independently of the model's final claims. */
import {readFile,writeFile} from 'node:fs/promises';
import path from 'node:path';
import {readSession} from './harness_session_evidence.mjs';
export function executionReceipts(events){
const receipts=[];
for(const call of events.filter(event=>event.type==='tool/call'&&event.data.name==='pwsh')){
let args;try{args=JSON.parse(call.data.arguments);}catch{continue;}
const command=args.command??'';
if(!/\b(?:python[\d.]*|py)(?:\.exe)?\b[^\r\n]*fixed\.py/i.test(command))continue;
const result=events.find(event=>event.type==='tool/result'&&event.data.message?.toolCallId===call.data.callId);
const text=result?.data.message?.content?.filter(part=>part.type==='text').map(part=>part.text).join('\n')??'';
const job=events.find(event=>event.type==='job/settled'&&event.data.toolCall?.callId===call.data.callId);
const exit=job?.data.detail?.match(/exit code:\s*(-?\d+)/i)??text.match(/\[exit code:\s*(-?\d+)\]/i);
const values=[];
for(const match of text.split('[stderr]')[0].matchAll(/\{[^\r\n]*\}/g)){try{values.push(JSON.parse(match[0]));}catch{}}
receipts.push({call_id:call.data.callId,command,exit_code:exit?Number(exit[1]):null,
tool_error:result?.data.message?.isError??true,output_json:values});
}
return receipts;
}
if(process.argv[1]?.endsWith('extract_acceptance_execution.mjs')){
const output=path.resolve(process.argv[2]);
const report=JSON.parse(await readFile(path.join(output,'report.json'),'utf8'));
const samples=[];
for(const row of report.samples){
if(row.session_file)samples.push({id:row.id,receipts:executionReceipts(await readSession(row.session_file))});
}
await writeFile(path.join(output,'execution-evidence.json'),JSON.stringify({revision:'shell-receipt-v2-job-exit',samples},null,2));
}
+58
View File
@@ -0,0 +1,58 @@
import {readFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {zstdDecompressSync} from 'node:zlib';
function jsonlEvents(text){
// Writers may be between append chunks. Only newline-terminated records
// belong to the readable prefix; malformed complete records are corruption.
return text.split('\n').slice(0,-1).filter(line=>line.trim()).map(line=>JSON.parse(line));
}
export function decodeSession(bytes){
const events=[];
let offset=0;
while(offset<bytes.length){
let result;
result=zstdDecompressSync(bytes.subarray(offset),{info:true});
if(!result.engine.bytesWritten)break;
offset+=result.engine.bytesWritten;
events.push(...jsonlEvents(result.buffer.toString('utf8')));
}
return events;
}
export async function sessionFiles(home){
const root=path.join(home,'sessions'),files=[];
for(const workspace of await readdir(root).catch(()=>[])){
const directory=path.join(root,workspace);
for(const session of await readdir(directory))files.push(path.join(directory,session,'session.v4.jsonl.zstd'));
}
return files;
}
export async function readSession(filename){
const candidates=filename.endsWith('.zstd')?[filename,filename.slice(0,-5)]:[filename,filename+'.zstd'];
for(const candidate of candidates){
let bytes;
try{bytes=await readFile(candidate);}
catch(error){if(error.code==='ENOENT')continue;throw error;}
return candidate.endsWith('.zstd')?decodeSession(bytes):jsonlEvents(bytes.toString('utf8'));
}
// Directories precede lazy log materialization. Keep observing this turn.
return [];
}
export async function evidenceFor(home,prompt,filename){
let events;
if(filename)events=await readSession(filename);
else for(const candidate of await sessionFiles(home)){
const found=await readSession(candidate);
if(found.some(event=>event.type==='user/message'&&event.data.content?.some(part=>part.text===prompt))){
filename=candidate;events=found;break;
}
}
if(!events)return {complete:false};
const last=type=>events.findLast(event=>event.type===type);
const turnStart=last('turn/start'),turnEnd=last('turn/end');
const goal=last('goal/change')?.data.goal;
return {filename,events,goal,complete:!!turnEnd&&turnEnd.seq>turnStart.seq&&goal?.phase!=='active',reason:turnEnd?.data.reason};
}
+3 -1
View File
@@ -76,7 +76,7 @@ class WindowDriver:
time.sleep(.2)
raise TimeoutError('Application main window not found')
def find(self, text=None, *, kind=None, automation_id=None, window=None):
def find(self, text=None, *, kind=None, automation_id=None, window=None, optional=False):
root = window or self.main()
# Do not recursively enumerate virtual Qt table cells through UIA.
def walk(parent, depth=0):
@@ -94,6 +94,8 @@ class WindowDriver:
and (automation_id is None or c.element_info.automation_id == automation_id
or c.element_info.automation_id.endswith('.' + automation_id))
and c.is_visible()]
if not matches and optional:
return None
if len(matches) != 1:
raise LookupError(f'Expected one {text!r}/{automation_id!r}, got {len(matches)}')
return matches[0]
+14 -3
View File
@@ -39,7 +39,13 @@ class PrivateDesktopObserver:
import win32api, win32gui, win32process
import pywintypes
foreground = win32gui.GetForegroundWindow()
self.foreground_pids.add(win32process.GetWindowThreadProcessId(foreground)[1] if foreground else 0)
try:
foreground_pid = win32process.GetWindowThreadProcessId(foreground)[1] if foreground else 0
except pywintypes.error as error:
if error.winerror != 1400 or win32gui.IsWindow(foreground):
raise
foreground_pid = 0
self.foreground_pids.add(foreground_pid)
self.samples += 1
if (Path(__file__).resolve().parents[1] / 'README.md').read_bytes():
self.readable_samples += 1
@@ -70,8 +76,13 @@ class PrivateDesktopObserver:
if getattr(error, 'winerror', error.args[0]) != 87:
raise
def collect(handle, _):
if win32gui.GetClassName(handle).startswith('Afx:') and 'DxDesigner' in win32gui.GetWindowText(handle):
self.default_cad_pids.add(win32process.GetWindowThreadProcessId(handle)[1])
try:
if win32gui.GetClassName(handle).startswith('Afx:') and 'DxDesigner' in win32gui.GetWindowText(handle):
self.default_cad_pids.add(win32process.GetWindowThreadProcessId(handle)[1])
except pywintypes.error as error:
# EnumWindows does not keep the enumerated window alive during teardown.
if error.winerror != 1400 or win32gui.IsWindow(handle):
raise
win32gui.EnumWindows(collect, None)
def _watch(self):
+70
View File
@@ -0,0 +1,70 @@
"""Reproduce directory rename Win5/32 using only test-owned native handles."""
import argparse
import json
import os
from pathlib import Path
import sys
import time
import win32con
import win32file
import pywintypes
def probe(path, flags):
try:
handle = win32file.CreateFile(str(path), win32con.DELETE, 7, None, 3, flags, None)
except pywintypes.error as error:
return error.winerror
handle.Close()
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
args = parser.parse_args()
root = args.root.resolve()
root.mkdir(parents=True, exist_ok=False)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from dx_productivity.trial_task_center.path_access import _sharing_denial, internal_path
report = {'native_owned_handles_only': True, 'cases': []}
for kind in ('directory', 'child', 'nested-child'):
directory = internal_path(root / kind / ('long-' + 'a' * 90) / ('more-' + 'b' * 90))
directory.mkdir(parents=True)
child = directory / 'nested' / 'board.prj' if kind == 'nested-child' else directory / 'board.prj'
child.parent.mkdir(exist_ok=True)
child.write_text('disposable original bytes', encoding='utf-8')
held = directory if kind == 'directory' else child
flags = win32con.FILE_FLAG_BACKUP_SEMANTICS if kind == 'directory' else 0
handle = win32file.CreateFile(str(held), win32con.GENERIC_READ, 3, None, 3, flags, None)
destination = directory.with_name('published')
try:
try:
os.replace(directory, destination)
except OSError as error:
row = {'kind': kind, 'rename_winerror': error.winerror,
'directory_attributes': directory.lstat().st_file_attributes,
'parent_probe_flags0': probe(directory, 0),
'parent_probe_backup_semantics': probe(directory, win32con.FILE_FLAG_BACKUP_SEMANTICS),
'held_path_delete_probe': probe(held, flags),
'confirmed_sharing': _sharing_denial(error, directory)}
else:
raise AssertionError('Owned delete-sharing lock did not block rename')
finally:
handle.Close()
time.sleep(.05)
os.replace(directory, destination)
row['rename_after_release_succeeded'] = destination.is_dir()
report['cases'].append(row)
report['passed'] = all(row['rename_winerror'] == (32 if row['kind'] == 'directory' else 5)
and row['held_path_delete_probe'] == 32 and row['rename_after_release_succeeded']
for row in report['cases'])
(root / 'report.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps(report, indent=2))
if not report['passed']:
raise SystemExit(1)
if __name__ == '__main__':
main()
+157
View File
@@ -0,0 +1,157 @@
"""Seeded semantic file-task generator. Oracles are returned, never written to inputs."""
from __future__ import annotations
import csv
import hashlib
import io
import json
from pathlib import Path
import random
import secrets
STRATA = ('facts', 'unicode', 'totals', 'duplicates', 'comparison', 'missing-fields',
'mapping', 'nested', 'policy', 'logs', 'recursive', 'money', 'ambiguity',
'large-table', 'merge', 'missing-file', 'repair-json', 'goal',
'repair-run', 'conflicts')
def generate(workspace: Path, seed: int | None = None, count: int = 20):
if count < len(STRATA):
raise ValueError('At least 20 cases are required for stratified coverage')
seed = secrets.randbits(128) if seed is None else seed
rng = random.Random(seed)
cases = []
for index in range(count):
kind = STRATA[index % len(STRATA)]
n = rng.randint(7, 31)
values = [rng.randint(-50, 150) for _ in range(n)]
board = f'板-{rng.randrange(100000, 999999)}'
refs = sorted(rng.sample(range(1, 999), rng.randint(3, 9)))
old, new = f'OLD-{rng.randrange(999999)}', f'NEW-{rng.randrange(999999)}'
files, expected, goal = {}, {}, False
def js(name, value):
files[name] = json.dumps(value, ensure_ascii=False)
def table(name, rows):
stream = io.StringIO(newline='')
csv.writer(stream, lineterminator='\n').writerows(rows)
files[name] = stream.getvalue()
if kind == 'facts':
obj = {'project': board, 'references': [f'R{x}' for x in refs], 'new_part_number': new}
files['notes.txt'] = f'工程={board}\n位号={",".join(obj["references"])}\n新料号={new}\n'
request = '读取 notes.txt,result.json 写 project、references 数组、new_part_number。'
answer = obj
elif kind == 'unicode':
answer = f'{board} 电阻 Ω\n{new} 中文路径 ✓\n'
files['中文/说明.txt'] = answer
request = '把 中文/说明.txt 原样复制为 result.txt,保留换行。'
expected['result.txt'] = answer
elif kind == 'totals':
rows = [(rng.choice(('A', 'B', 'C', 'D')), rng.randint(1, 30)) for _ in values]
table('bom.csv', [('part', 'quantity'), *rows])
answer = {p: sum(q for part, q in rows if part == p) for p in sorted(set(p for p, _ in rows))}
answer['total'] = sum(q for _, q in rows)
request = '汇总 bom.csv,每个出现料号为键、数量为值,另加 total 总数量,保存 result.json。'
elif kind in ('duplicates', 'conflicts'):
rows = [(board, f'R{x}', old) for x in refs]
duplicate = rng.choice(refs)
rows += [(board, f'R{duplicate}', new), (board+'B', f'R{duplicate}', old)]
rng.shuffle(rows)
table('bom.csv', [('project', 'refdes', 'part'), *rows])
answer = {'duplicates': [{'project': board, 'refdes': f'R{duplicate}'}]}
request = '按 project+refdes 查 bom.csv 重复身份(包括料号冲突)。result.json 写 duplicates 数组,每项只有 project、refdes;不同工程不算重复。'
elif kind == 'comparison':
changed = set(rng.sample(refs, rng.randint(1, len(refs))))
table('before.csv', [('refdes', 'part'), *[(f'R{x}', old) for x in refs]])
table('after.csv', [('refdes', 'part'), *[(f'R{x}', new if x in changed else old) for x in refs]])
answer = {'changes': [{'refdes': f'R{x}', 'before': old, 'after': new} for x in refs if x in changed]}
request = '比较 before.csv 和 after.csv,result.json 写 changes 数组,每项 refdes、before、after,按位号数字升序。'
elif kind == 'missing-fields':
rows = [(f'R{x}', old, new) for x in refs]
bad = rng.sample(range(len(rows)), rng.randint(1, len(rows)))
for i in bad:
row = list(rows[i]); row[rng.randrange(3)] = ''; rows[i] = row
table('bom.csv', [('refdes', 'old', 'new'), *rows])
answer = {'invalid_rows': sorted(i+2 for i in bad)}
request = 'bom.csv 三列均必填,result.json 写 invalid_rows,Excel行号表头为1,升序。'
elif kind == 'mapping':
obj = {f'R{x}': rng.choice((old, 'KEEP')) for x in refs}
js('source.json', obj)
answer = {k: new if v == old else v for k, v in obj.items()}
request = f'把 source.json 中值 {old} 改为 {new},其余保留,另存 result.json。'
elif kind == 'nested':
depth = rng.randint(2, 6); obj = {'enabled': False, 'limit': n, 'note': board}
for _ in range(depth): obj = {'child': obj, 'keep': new}
js('config.json', obj)
answer = json.loads(files['config.json']); leaf = answer
for _ in range(depth): leaf = leaf['child']
leaf['enabled'] = True; leaf['limit'] = n*3
request = f'读取 config.json,沿 child 递归到叶子,只把 enabled 改 true,limit 改 {n*3},其余保留,另存 result.json。'
elif kind == 'policy':
default = rng.choice(('part_label', 'preserve'))
rows = [{'refdes': f'R{x}', 'mode': rng.choice(('inherit', 'preserve', 'custom')), 'custom': f'{rng.randint(1,999)}k'} for x in refs]
js('rows.json', rows)
answer = {r['refdes']: default if r['mode']=='inherit' else 'custom:'+r['custom'] if r['mode']=='custom' else 'preserve' for r in rows}
request = f'默认Value策略={default}。rows.json inherit用默认,preserve原样,custom写custom:对应custom值。result.json以位号作键。'
elif kind == 'logs':
error = rng.choice(('LIBRARY_NOT_FOUND', 'ACCESS_DENIED', 'INVALID_CELL'))
saved = rng.randrange(5)
files['run.log'] = f'INFO start\nERROR {error}\nERROR EXECUTION_ABORTED\nINFO saved={saved}\n'
answer = {'root_error': error, 'saved': saved, 'execution_succeeded': False}
request = 'run.log 第一条ERROR为根因。result.json写 root_error、saved 数字、execution_succeeded 布尔值。发生ERROR即失败。'
elif kind == 'recursive':
ids = [f'ID-{x}' for x in rng.sample(range(99999), n)]
for i, marker in enumerate(ids): files[f'd{i%3}/deep/{i}.txt'] = f'accept_id={marker}\n'
files['ignore.md'] = 'accept_id=IGNORE'
answer = {'ids': sorted(ids)}
request = '递归读取所有.txt的accept_id,按字符串升序,result.json写ids数组,忽略其他扩展名。'
elif kind == 'money':
rows = [(rng.randint(1, 20), rng.randint(1, 2000)) for _ in values]
table('prices.csv', [('qty', 'unit_price'), *[(q, f'{p//100}.{p%100:02d}') for q,p in rows]])
cents = sum(q*p for q,p in rows)
answer = {'total': f'{cents//100}.{cents%100:02d}', 'currency': 'CNY'}
request = 'prices.csv数量乘单价求和,result.json写total两位小数字符串、currency=CNY。'
elif kind == 'ambiguity':
candidates = rng.randint(2, 7)
js('catalog.json', [{'name': board, 'path': f'X:/{i}/{board}.prj'} for i in range(candidates)])
answer = {'status': 'ambiguous', 'candidate_count': candidates, 'selected_path': None}
request = f'工程名只有{board},catalog.json同名候选不唯一时不能任选;result.json写status=ambiguous、candidate_count、selected_path=null。'
elif kind == 'large-table':
values = [rng.randint(-10000, 10000) for _ in range(rng.randint(600, 1400))]
table('numbers.csv', [('value',), *[(v,) for v in values]])
answer = {'count': len(values), 'sum': sum(values), 'min': min(values), 'max': max(values)}
request = '实际读取numbers.csv全部数据,result.json写count、sum、min、max。'
elif kind == 'merge':
a = rng.sample(range(100), n); b = rng.sample(range(100), n)
js('a.json', a); js('b.json', b)
answer = {'values': sorted(set(a+b)), 'count': len(set(a+b))}
request = '合并a.json、b.json去重,result.json写values数字升序数组和count。'
elif kind == 'missing-file':
files['existing.txt'] = board
answer = {'status': 'missing', 'content': None}
request = f'尝试读取 missing-{n}.txt;不存在则result.json写status=missing、content=null,不编造。'
elif kind == 'repair-json':
files['broken.json'] = json.dumps({'refdes': f'R{refs[0]}', 'part': new})[:-1]+',}'
answer = {'refdes': f'R{refs[0]}', 'part': new}
request = 'broken.json尾随逗号非法,修正为标准JSON另存result.json,保留数据和原文件。'
elif kind == 'goal':
goal = True
for i,v in enumerate(values):
js(f'inputs/part-{i}.json', {'id': i, 'quantity': v})
expected[f'outputs/part-{i}.json'] = {'id': i, 'double_quantity': v*2}
answer = {'count': n, 'total_double_quantity': sum(values)*2}
request = '建立goal并完成:逐个读inputs全部JSON,各另存outputs同名文件,字段id和double_quantity(quantity乘2);result.json写count和total_double_quantity;核对所有产物后完成goal,不只给计划。'
else:
files['calculate.py'] = f'import json\nvalues={values!r}\nprint(json.dumps({{"sum":sum(values)+1,"count":len(values)}}))\n'
answer = {'sum': sum(values), 'count': n}
request = 'calculate.py求和多加1;保留原文件,修复另存fixed.py,实际运行并将JSON输出保存result.json。'
if kind != 'unicode': expected['result.json'] = answer
directory = workspace / f'{index+1:02d}-{kind}'
directory.mkdir(parents=True, exist_ok=False)
for name, content in files.items():
target = directory / name; target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content.encode('utf-8'))
cases.append({'id': directory.name, 'stratum': kind, 'directory': str(directory), 'request': request,
'goal': goal, 'expected': expected,
'parameters': {'row_count': n, 'board': board, 'references': refs, 'old': old, 'new': new},
'input_hashes': {name: hashlib.sha256(content.encode('utf-8')).hexdigest() for name,content in files.items()}})
return seed, cases
+98
View File
@@ -0,0 +1,98 @@
Frozen random acceptance
========================
`accept_random_packaged_ui.py` runs the actual EXE through external Windows UIA.
It imports no application service or source UI. Database access is SQLite
`mode=ro`; fixture files are generated separately before launching the EXE.
The admitted final candidate, original hashes and intended roots are in
`outputs/completion-validation-20261111/frozen-random-final-plan.json`. That file
is a plan, not evidence of an executed test. Wait for the exclusive CAD/UI slot.
Prepare the final fixture once, from the repository root (Python):
```python
import json, sys
from pathlib import Path
sys.path.insert(0, 'tools')
from accept_random_cad import prepare, workbook, fingerprint, write
p = json.loads(Path('outputs/completion-validation-20261111/frozen-random-final-plan.json').read_text(encoding='utf-8'))
assert fingerprint(Path(p['source']).parent) == p['source_hashes']
root = Path(p['root'])
m = prepare(root, Path(p['source']), json.loads(Path(p['graph']).read_text(encoding='utf-8')),
p['target_parts'], count=p['count'], cells=p['cells'])
# No seed argument: draw from system randomness after tools stabilize.
# Existing independent baseline belongs to the unchanged original source.
m['baseline'] = p['graph']
write(root / 'manifest.json', m)
workbook(root, m)
```
With the CAD/UI slot granted, launch/import/save/confirm/execute/pause/resume:
```powershell
python -X utf8 tools/accept_random_packaged_ui.py --exe outputs/completion-validation-20261111/app/DxPartReplace/DxPartReplace.exe --expected-sha256 0fb92b15ab57fa8765853ae63d0a7ef098280c21b40ec0e3768a726009e88015 --root outputs/completion-validation-20261111/frozen-random-final20 --stage execute --run-native
```
Then run independent native ASCII/Keyin verification, using the same slot:
```powershell
python -X utf8 tools/accept_random_cad.py --root outputs/completion-validation-20261111/frozen-random-final20 --verify
```
The driver leaves its exact app process available for review. It never kills an
app after a timeout. Continue only with that root's recorded `--pid`; attachment
requires its existing process/EXE/hash binding. `--stage import` creates tasks
and imports source drafts without executing a queue. Current candidate import
persists `pending_bom` drafts immediately and defers CAD checks to execution.
Evidence: timestamped `packaged-ui-report-*.json` (including failures), EXE log,
`ui-session.json`, `packaged-recording/*/frame-*.png`, actual queue/resource
journals, desktop observation and independent report. A passed import report
does not prove execution, pause/resume, or independent schematic correctness.
Supplemental controls implemented, awaiting an exclusive real CAD/UI slot:
* Valid Cell: generator's `--supplemental valid_cell --count 1`; driver clicks
the real rule dialog and loads/selects an authentic library Cell.
* Force: generator's `--supplemental force_stop --count 1`; driver observes the
worker stage, then click `forceStopButton`, confirm `强制结束当前操作`, and
perform `recoverQuickRunButton` / `核验并恢复`. Never edit worker progress.
* Resource: standalone fixture plus `--resource-hold`; test-owned external
desktop reference only; after completed saved
business, release that actor and click `cleanupBatchResources`. Preserve
failure/success history and prove saved results were not executed again.
* PON: prepare a separate pristine PON family/graph with authentic compatible
`--part-prefix` and target parts. Normal directory/import/execution controls
reuse this driver; no ordinary-family outcomes imply PON acceptance.
Review record
-------------
Normal completion requires queue phase `finished`, no running entries, settled
supervisor journals, positive desktop/process release evidence, and a disabled
UI stop control. Execute may legitimately be disabled after success. Independent
schematic verification remains mandatory.
Pause is clicked only while a real entry runs after at least one completed entry.
Resume waits for pending/paused entries and settled resources, uses the actual
UI confirmation, and asserts unchanged queue filename, ordered task IDs and plan
hashes. Previously saved UID event counts must remain unchanged.
Blocked/uncertain entries stop the normal driver. It never clears uncertainty,
edits the DB, fabricates progress, retries failed work, or kills an app on timeout.
Only the explicit force supplemental clicks force/recovery. Resource cleanup
compares saved business-result hashes and saved UID counts before/after, without
clicking Execute again. Missing real fault triggers fail acceptance.
The existing data-root option and process-local TEMP/TMP isolate the real EXE.
Windows process image and expected EXE SHA256 establish identity. Attachment
requires the isolated root's recorded PID/EXE/hash binding. Only UIA changes app
state; original source fingerprints are checked before/after. Independent native
observation checks CAD exit, desktop disappearance, foreground/input isolation
and responsiveness. There is no source Qt window, service shortcut, DB mutation
or simulated worker.
Verified scope: clean import-only on the old candidate. Supplemental and final
candidate execution await actual runs; their implementation is not proof of CAD
behavior.
+91
View File
@@ -0,0 +1,91 @@
"""Independent prompt-contract scoring; original UI report is never modified."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
REVISION = 'prompt-contract-v2-execution'
# These instructions require preserving every original field, or changing only named fields.
EXCLUSIVE = frozenset({'mapping', 'nested', 'repair-json'})
# These instructions explicitly request sorted arrays. Other arrays require exact membership/count.
ORDERED = frozenset({'comparison', 'missing-fields', 'recursive', 'merge'})
def reject_non_json_constant(value):
raise ValueError(f'Non-standard JSON constant: {value}')
def matches(actual, expected, *, exclusive=False, ordered=False):
if isinstance(expected, dict):
return (isinstance(actual, dict) and
(not exclusive or actual.keys() == expected.keys()) and
all(key in actual and matches(actual[key], value, exclusive=exclusive, ordered=ordered)
for key, value in expected.items()))
if isinstance(expected, list):
if not isinstance(actual, list) or len(actual) != len(expected): return False
if ordered:
return all(matches(a,b,exclusive=exclusive,ordered=ordered) for a,b in zip(actual,expected))
assignments={}
def assign(index,seen):
for i,candidate in enumerate(actual):
if i in seen or not matches(candidate,expected[index],exclusive=exclusive,ordered=ordered): continue
seen.add(i)
if i not in assignments or assign(assignments[i],seen):
assignments[i]=index; return True
return False
return all(assign(index,set()) for index in range(len(expected)))
# JSON booleans must never compare equal to integer quantities.
if isinstance(actual,bool) != isinstance(expected,bool): return False
return actual == expected and (actual is not None or expected is None)
def score(output):
manifest = json.loads((output/'manifest.json').read_text(encoding='utf-8'))
report = json.loads((output/'report.json').read_text(encoding='utf-8'))
original = {row['id']:row for row in report['samples']}
receipt_path=output/'execution-evidence.json'
receipts=json.loads(receipt_path.read_text(encoding='utf-8')) if receipt_path.exists() else {'samples':[]}
rows=[]
for case in manifest['cases']:
checks=[]; directory=Path(case['directory']); stratum=case['stratum']
for filename,expected in case['expected'].items():
try:
data=(directory/filename).read_bytes()
actual=data.decode('utf-8') if isinstance(expected,str) else json.loads(data.decode('utf-8-sig'),parse_constant=reject_non_json_constant)
passed=matches(actual,expected,exclusive=stratum in EXCLUSIVE,ordered=stratum in ORDERED)
checks.append({'file':filename,'passed':passed})
except (OSError,ValueError,UnicodeError) as error:
checks.append({'file':filename,'passed':False,'error':str(error)})
for filename,digest in case['input_hashes'].items():
try: passed=hashlib.sha256((directory/filename).read_bytes()).hexdigest()==digest
except OSError: passed=False
checks.append({'original':filename,'passed':passed})
previous=original.get(case['id'],{})
if stratum=='repair-run':
evidence=next((row for row in receipts['samples'] if row['id']==case['id']),{'receipts':[]})
expected=case['expected']['result.json']
executed=any(receipt['exit_code']==0 and not receipt['tool_error'] and
any(matches(value,expected) for value in receipt['output_json']) for receipt in evidence['receipts'])
checks.append({'requirement':'actual fixed.py execution with successful JSON stdout','passed':executed})
checks.append({'file':'fixed.py','passed':(directory/'fixed.py').is_file()})
turn_complete=previous.get('turn_end',{}).get('kind')=='completed'
status = ('not-run' if not previous else 'running' if previous.get('status')=='running'
else 'passed' if turn_complete and all(c['passed'] for c in checks) else 'failed')
rows.append({'id':case['id'],'strict_original_status':previous.get('status','not-run'),
'semantic_status':status,
'exclusive_schema':stratum in EXCLUSIVE,'ordered_lists':stratum in ORDERED,
'turn_complete':turn_complete,'checks':checks})
result={'oracle_revision':REVISION,'oracle_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'seed':manifest['seed'],'samples':rows,'passed':sum(r['semantic_status']=='passed' for r in rows),
'failed':sum(r['semantic_status']=='failed' for r in rows),
'pending':sum(r['semantic_status'] in ('running','not-run') for r in rows),
'limits':['Artifact and source-integrity scoring; tool execution claims require session review']}
(output/'semantic-score.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
return result
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('output',type=Path)
result=score(parser.parse_args().output.resolve())
print(json.dumps({k:result[k] for k in ('oracle_revision','passed','failed')}))
+67
View File
@@ -0,0 +1,67 @@
/** Audit persisted native sessions and publish a compact human-readable result. */
import {readFile,writeFile,copyFile,mkdir} from 'node:fs/promises';
import path from 'node:path';
import {evidenceFor} from './harness_session_evidence.mjs';
const output=path.resolve(process.argv[2]??'outputs/harness-acceptance-20');
const manifest=JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8'));
const report=JSON.parse(await readFile(path.join(output,'report.json'),'utf8'));
const audit={git_head:report.git_head,real_model:report.real_model,real_cad:false,model:null,samples:[]};
for(const row of report.samples){
const sample=manifest.cases.find(value=>value.id===row.id);
const native=await evidenceFor(path.join(manifest.data,'dsh/harness-home'),row.prompt,row.session_file);
const events=native.events??[];
const results=events.filter(event=>event.type==='tool/result');
const failed=results.filter(event=>event.data.message?.isError||event.data.message?.content?.some(part=>
part.type==='text'&&(/\[exit code: [1-9]\d*\]/.test(part.text)||/\[sandbox: file access denied/.test(part.text))));
const usages=events.filter(event=>event.type==='assistant/message'&&event.data.usage).map(event=>event.data.usage);
const model=events.findLast(event=>event.type==='assistant/message')?.data.message.source;
audit.model??=model?.model;
const entry={id:row.id,status:row.status,seconds:row.seconds,session_id:events[0]?.id,
native_turn_completed:native.complete,goal:native.goal??null,tool_calls:events.filter(event=>event.type==='tool/call').length,
failed_tool_calls:failed.length,approval_interactions:row.confirmations?.length??0,
input_tokens:usages.reduce((total,usage)=>total+(usage.inputTokens??0),0),
output_tokens:usages.reduce((total,usage)=>total+(usage.outputTokens??0),0),
checks:row.checks??[],error:row.error??null};
if(row.id==='02-unicode'&&row.status==='passed'){
const source=await readFile(path.join(sample.directory,'中文目录/说明.txt'));
const copied=await readFile(path.join(sample.directory,'result.txt'));
entry.byte_copy_verified=source.equals(copied);
if(!entry.byte_copy_verified)entry.status='failed';
}
if(row.id==='20-repair-and-run'){
const calls=new Map(events.filter(event=>event.type==='tool/call').map(event=>[event.data.callId,event.data]));
entry.execution_verified=results.some(event=>{
const call=calls.get(event.data.message?.toolCallId);
const text=event.data.message?.content?.filter(part=>part.type==='text').map(part=>part.text).join('\n')??'';
return call?.name==='pwsh'&&call.arguments.includes('fixed.py')&&!/\[exit code: [1-9]\d*\]/.test(text)
&&/"sum"\s*:\s*12/.test(text)&&/"count"\s*:\s*3/.test(text);
});
if(row.status==='passed'&&!entry.execution_verified)entry.status='failed';
}
audit.samples.push(entry);
const destination=path.join(output,'evidence',row.id);
await mkdir(destination,{recursive:true});
if(native.filename)await copyFile(native.filename,path.join(destination,'native-session.jsonl.zstd'));
for(const filename of Object.keys(sample.expected)){
const target=path.join(destination,'artifacts',filename);
await mkdir(path.dirname(target),{recursive:true});
await copyFile(path.join(sample.directory,filename),target).catch(()=>{});
}
}
audit.completed=audit.samples.filter(row=>row.status!=='running').length;
audit.passed=audit.samples.filter(row=>row.status==='passed').length;
audit.failed=audit.samples.filter(row=>row.status==='failed').length;
audit.total=manifest.cases.length;
await writeFile(path.join(output,'audit.json'),JSON.stringify(audit,null,2));
const lines=[`# Harness 本地点击验收`, '',
`代码基线:${audit.git_head}。模型:${audit.model??'unknown'}。真实模型、真实界面;未执行真实 CAD。`, '',
`已结束 ${audit.completed}/${audit.total},产物检查通过 ${audit.passed},未通过 ${audit.failed}。`, '',
'权限确认中的操作系统权限修复不属于样本任务,验收者选择拒绝,记录交互次数;模型可继续使用已可用的文件能力完成目标。', '',
'| 样本 | 产物检查 | 原生回合结束 | 耗时秒 | 工具调用 | 失败调用 | 权限交互 |',
'| --- | --- | --- | ---: | ---: | ---: | ---: |',
...audit.samples.map(row=>`| ${row.id} | ${row.status} | ${row.native_turn_completed} | ${row.seconds??''} | ${row.tool_calls} | ${row.failed_tool_calls} | ${row.approval_interactions} |`), '',
'“产物检查通过”表示磁盘产物与预设答案一致,原文件哈希保留;不等于已经完成人工回复质量评分,也不代表优于旧版本。',
'各样本截图、回复、产物和原生压缩会话均保留在本目录。'];
await writeFile(path.join(output,'验收报告.md'),lines.join('\n'));
console.log(JSON.stringify({completed:audit.completed,total:audit.total,passed:audit.passed,failed:audit.failed,model:audit.model}));
+67
View File
@@ -0,0 +1,67 @@
/** Independent paired report aggregation; preserves every failure and original report. */
import {readFile,writeFile} from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {readSession} from './harness_session_evidence.mjs';
const output=path.resolve(process.argv[2]);
const tools=path.dirname(fileURLToPath(import.meta.url));
const manifests=Object.fromEntries(await Promise.all(['native','harness'].map(async arm=>
[arm,JSON.parse(await readFile(path.join(output,arm,'manifest.json'),'utf8'))])));
assert.equal(manifests.native.purpose,manifests.harness.purpose,'Paired manifest purposes differ');
assert.ok(['exploration','holdout'].includes(manifests.native.purpose),'Missing or unsupported manifest purpose');
const arms={};
for(const arm of ['native','harness']){
const manifest=manifests[arm];
if(!process.argv.includes('--summary-only')){
execFileSync(process.execPath,[path.join(tools,'extract_acceptance_execution.mjs'),path.join(output,arm)]);
execFileSync(manifest.command[0],['-X','utf8',path.join(tools,'score_acceptance_semantics.py'),path.join(output,arm)]);
}
const report=JSON.parse(await readFile(path.join(output,arm,'report.json'),'utf8'));
const semantic=JSON.parse(await readFile(path.join(output,arm,'semantic-score.json'),'utf8'));
const interventions=(await readFile(path.join(output,arm,'interventions.jsonl'),'utf8').catch(()=>''))
.split('\n').filter(Boolean).map(line=>JSON.parse(line));
const rows=[];
for(const row of report.samples){
const events=row.session_file?await readSession(row.session_file):[];
rows.push({id:row.id,status:row.status,seconds:row.seconds,error:row.error,
checks:row.checks,tool_calls:row.tool_calls?.length??0,confirmations:row.confirmations?.length??0,
model_routes:events.filter(e=>e.type==='request/context').map(e=>e.data),
usage:events.filter(e=>e.data?.usage).map(e=>e.data.usage),
goal:row.goal,turn_end:row.turn_end,session_file:row.session_file});
rows.at(-1).interventions=interventions.filter(event=>event.id===row.id);
rows.at(-1).semantic=semantic.samples.find(sample=>sample.id===row.id);
rows.at(-1).tokens=Object.fromEntries(['inputTokens','outputTokens','totalTokens'].map(key=>
[key,rows.at(-1).usage.reduce((sum,usage)=>sum+(usage[key]??0),0)]));
}
arms[arm]={manifest,rows,semantic};
}
assert.equal(arms.native.manifest.seed,arms.harness.manifest.seed);
for(const [i,a]of arms.native.manifest.cases.entries()){
const b=arms.harness.manifest.cases[i];
assert.equal(a.request,b.request);assert.deepEqual(a.input_hashes,b.input_hashes);assert.deepEqual(a.expected,b.expected);
}
const summary={seed:arms.native.manifest.seed,real_model:true,real_cad:false,purpose:manifests.native.purpose,
matched_inputs:true,case_budget_ms:arms.native.manifest.case_budget_ms,
source_files:arms.native.manifest.source_files,
measurement_limits:['Session assistant-message token receipts exclude unreported background/title requests',
'Shared host load varied; elapsed times are exploratory, not a controlled performance benchmark',
'Windows shell ACL denials are environmental failures and are preserved'],arms:{}};
summary.workspace_layouts=Object.fromEntries(['native','harness'].map(arm=>[arm,
path.relative(path.join(arms[arm].manifest.data,'dsh/harness-home'),arms[arm].manifest.workspace)]));
summary.workspace_layouts_matched=summary.workspace_layouts.native===summary.workspace_layouts.harness;
if(!summary.workspace_layouts_matched)summary.measurement_limits.push('Exploration workspace layouts differ; use a fresh matched-layout holdout for benchmark conclusions');
for(const [arm,{manifest,rows,semantic}]of Object.entries(arms))summary.arms[arm]={runtime:manifest.runtime,
semantic_passed:semantic.passed,semantic_failed:semantic.failed,oracle_revision:semantic.oracle_revision,oracle_sha256:semantic.oracle_sha256,
completed:rows.filter(r=>r.status!=='running').length,passed:rows.filter(r=>r.status==='passed').length,
failed:rows.filter(r=>r.status==='failed').length,seconds:rows.reduce((s,r)=>s+(r.seconds??0),0),
tool_calls:rows.reduce((s,r)=>s+r.tool_calls,0),confirmations:rows.reduce((s,r)=>s+r.confirmations,0),
question_interruptions:rows.reduce((s,r)=>s+r.interventions.length,0),
tokens:Object.fromEntries(['inputTokens','outputTokens','totalTokens'].map(key=>[key,rows.reduce((s,r)=>s+r.tokens[key],0)])),
coverage:manifest.coverage,samples:rows};
const routes=arm=>[...new Set(arms[arm].rows.flatMap(row=>row.model_routes.map(route=>JSON.stringify({provider:route.provider,model:route.model}))))].sort();
summary.model_routes={native:routes('native'),harness:routes('harness')};
summary.model_routes_matched=JSON.stringify(routes('native'))===JSON.stringify(routes('harness'));
await writeFile(path.join(output,'paired-summary.json'),JSON.stringify(summary,null,2));
console.log(JSON.stringify(Object.fromEntries(Object.entries(summary.arms).map(([k,v])=>[k,{passed:v.passed,failed:v.failed,seconds:v.seconds,tool_calls:v.tool_calls}]))));
+52 -23
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {createRequire} from 'node:module';
import {pathToFileURL} from 'node:url';
import {bootRuntime} from '../integration/dsh/start.mjs';
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const {zipSync,strToU8}=require('fflate');
@@ -17,12 +18,12 @@ const archive=path.join(source,'资料.zip');
await writeFile(archive,zipSync({'子目录/说明.txt':strToU8('DSH_ZIP_CONTENT_中文'),'binary.bin':new Uint8Array([0,1,2,255])}));
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const names=ctx.tools.schemas().map(x=>x.name);
for(const name of ['read','read_image','glob','grep','working_directory','extract_zip'])
assert.ok(names.includes(name),'Missing file capability: '+name);
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'File fixture');
const {sessionId}=await ctx.sessionController.create({workspaceId:workspace.id,agentPreset:'dx-task'});
const agent=ctx.agents.get(sessionId);
const names=ctx.tools.schemas(agent).map(x=>x.name);
for(const name of ['read','read_image','write','edit','glob','grep','working_directory','extract_zip'])
assert.ok(names.includes(name),'Missing file capability: '+name);
const call=async(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent,signal:AbortSignal.timeout(20000)});
const ok=async(name,args)=>{
const result=await call(name,args);assert.equal(result.isError,false,name+': '+JSON.stringify(result));return result;
@@ -49,27 +50,55 @@ try{
await writeFile(path.join(source,'corrupt.zip'),corrupt);
assert.equal((await call('extract_zip',{file_path:'corrupt.zip'})).isError,true,'CRC mismatch must not report successful extraction');
assert.equal(await readFile(path.join(source,'说明.txt'),'utf8'),'DSH_FILE_CONTENT_中文\n');
const {LlmAdapter}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href);
let resolveChecked,rejectChecked;
const checked=new Promise((resolve,reject)=>{resolveChecked=resolve;rejectChecked=reject;});
const callsById=new Map(),diagnosticResults=[];
let incidentSession;
ctx.on('session/event',(session,event)=>{
if(event.type==='tool/call')callsById.set(event.data.callId,event.data.name);
if(event.type!=='tool/result'||!callsById.has(event.data.message.toolCallId))return;
incidentSession=session.id;
diagnosticResults.push({name:callsById.get(event.data.message.toolCallId),...event.data.message});
if(diagnosticResults.length===3){
try{
assert.equal(diagnosticResults[0].isError,false);
assert.match(JSON.stringify(diagnosticResults[0].content),new RegExp('a'.repeat(24)));
for(const denied of diagnosticResults.slice(1)){
assert.equal(denied.isError,true);
assert.match(JSON.stringify(denied.content),/Automatic incident sessions/);
}
resolveChecked();
}catch(error){rejectChecked(error);}
}
});
let response=0;
class DiagnosticFixture extends LlmAdapter{
providerInfo(provider){return {id:provider,name:'Owned diagnostic fixture'};}
async listModels(provider){return [{provider,id:'fixture',name:'Fixture'}];}
async *stream(options){
const checks=[['dx_task_snapshot',{}],['read',{file_path:path.join(source,'说明.txt')}],['extract_zip',{file_path:archive}]];
const tool=options.purpose==='session-title'?null:checks[response++];
if(tool){
const block={type:'tool-call',id:crypto.randomUUID(),name:tool[0],arguments:JSON.stringify(tool[1])};
yield {type:'block-start',index:0,blockType:'tool-call'};
yield {type:'block-end',index:0,block};
yield {type:'finish',reason:{kind:'tool-calls'}};
return;
}
yield {type:'block-start',index:0,blockType:'text'};
yield {type:'block-end',index:0,block:{type:'text',text:'Controlled diagnosis. No engineering changes. {"action":"none"}'}};
yield {type:'finish',reason:{kind:'stop'}};
}
}
ctx.llm.registerAdapter(['files-fixture'],new DiagnosticFixture());
await ctx.agentDefaultModel.saveSelection({provider:'files-fixture',model:'fixture'});
ctx.emit('dx/diagnose-request',{request_id:'files-incident-probe',incident_id:'a'.repeat(24),phase:'diagnose',
snapshot:{task_id:'files-fixture'},evidence:'Owned fixture; no model is configured.'});
let incident;
const deadline=Date.now()+20000;
while(Date.now()<deadline){
incident=ctx.agents.list().find(value=>value.id!==agent.id);
if(incident)break;
await new Promise(resolve=>setTimeout(resolve,50));
}
assert.ok(incident,'automatic incident session must be created');
let marked=false;
while(Date.now()<deadline){
const snapshot=await ctx.tools.execute({name:'dx_task_snapshot',arguments:{},callId:crypto.randomUUID(),agent:incident,signal:AbortSignal.timeout(2000)});
if(snapshot.value?.revision==='a'.repeat(24)){marked=true;break;}
await new Promise(resolve=>setTimeout(resolve,50));
}
assert.ok(marked,'incident snapshot must be bound before checking admission');
for(const [name,args] of [['read',{file_path:path.join(source,'说明.txt')}],['extract_zip',{file_path:archive}]]){
const denied=await ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:incident,signal:AbortSignal.timeout(2000)});
assert.equal(denied.isError,true,'automatic incident must not inherit interactive file access');
}
snapshot:{task_id:'files-fixture'},evidence:'Owned fixture with a controlled adapter.'});
let timer;
try{await Promise.race([checked,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Diagnostic admission check timed out')),120000);})]);}
finally{clearTimeout(timer);}
await ctx.agents.get(incidentSession).whenIdle();
const report={status:'passed',realHarness:true,read:true,folderSearch:true,workingDirectory:true,
zipTextAndBinary:true,repeatedExtractionNoOverwrite:true,zipTraversalRejected:true,invalidZipRejected:true,corruptZipRejected:true,
automaticSessionIsolation:true};
+83
View File
@@ -0,0 +1,83 @@
/** Compare the embedded assistant with the installed official Standard preset. */
import assert from 'node:assert/strict';
import {mkdir,mkdtemp,writeFile,readFile} from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {createRequire} from 'node:module';
import {pathToFileURL} from 'node:url';
import {bootRuntime} from '../integration/dsh/start.mjs';
const output=path.resolve('build/dsh-native-capabilities');
await mkdir(output,{recursive:true});
const root=await mkdtemp(path.join(os.tmpdir(),'dsh-native-capabilities-'));
for(const key of ['DSH_API_KEY','DSH_API_BASE','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key];
process.env.DX_DSH_HOME=path.join(root,'home');
process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'capabilities',revision:'native'}));
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
const presets=await ctx.agentPresets.list();
const standard=presets.find(p=>p.id==='standard');
assert.ok(standard&&!standard.broken,'Official Standard must be available: '+JSON.stringify(presets));
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'Native capabilities');
const create=async agentPreset=>{
const {sessionId}=await ctx.sessionController.create({workspaceId:workspace.id,agentPreset});
return ctx.agents.get(sessionId);
};
const native=await create('standard'),embedded=await create('dx-task');
const names=agent=>ctx.tools.schemas(agent).map(t=>t.name).sort();
assert.deepEqual(names(embedded),names(native),'Existing dx-task sessions must retain the full native tool catalog');
for(const tool of ['read','write','edit','pwsh','get_goal','create_goal','update_goal','todo_write','subagent'])
assert.ok(names(embedded).includes(tool),'Missing native capability: '+tool);
const call=(name,args)=>ctx.tools.execute({name,arguments:args,callId:crypto.randomUUID(),agent:embedded,signal:AbortSignal.timeout(20000)});
const filename=path.join(process.env.DX_DSH_WORKSPACE,'native-write.txt');
const written=await call('write',{file_path:filename,content:'native file operations'});
assert.equal(written.isError,false,JSON.stringify(written));
assert.equal(await readFile(filename,'utf8'),'native file operations');
const shell=await call('pwsh',{description:'Verify the native PowerShell execution path',command:"'NATIVE_HARNESS_SHELL_OK'"});
assert.equal(shell.isError,false,JSON.stringify(shell));
assert.match(JSON.stringify(shell),/NATIVE_HARNESS_SHELL_OK/);
assert.ok(ctx.get('goals'),'Native goal service must be mounted');
assert.ok(ctx.agentPresets.serviceFor(embedded,'compaction'),'Native automatic compaction must be mounted');
const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url));
const {LlmAdapter}=await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-llm')).href);
let responses=0;
class GoalFixture extends LlmAdapter{
providerInfo(provider){return {id:provider,name:'Native goal verification'};}
async listModels(provider){return [{provider,id:'fixture',name:'Fixture',reasoning:{efforts:[{id:'high',name:'High'}]}}];}
async resolveModel(provider,id){return {provider,id,name:'Fixture',reasoning:{efforts:[{id:'high',name:'High'}]}};}
async *stream(options){
responses++;
assert.equal(options.reasoningEffort,'high','Native selected reasoning must reach the adapter');
const goal=ctx.goals.get(embedded);
const tool=responses===1?{name:'create_goal',arguments:{objective:'Complete a controlled multi-round task',max_goal_rounds:3}}
:goal?.roundsStarted>0&&goal.phase==='active'?{name:'update_goal',arguments:{goal_id:goal.id,revision:goal.revision,action:'complete'}}:null;
if(tool){
const block={type:'tool-call',id:crypto.randomUUID(),name:tool.name,arguments:JSON.stringify(tool.arguments)};
yield {type:'block-start',index:0,blockType:'tool-call'};
yield {type:'block-end',index:0,block};
}else{
yield {type:'block-start',index:0,blockType:'text'};
yield {type:'block-end',index:0,block:{type:'text',text:'Controlled round completed.'}};
}
yield {type:'usage',usage:{inputTokens:12,outputTokens:4,totalTokens:16}};
yield {type:'finish',reason:{kind:tool?'tool-calls':'stop'}};
}
}
const release=ctx.llm.registerAdapter(['native-goal-fixture'],new GoalFixture());
await ctx.sessionController.selectModel({sessionId:embedded.id,provider:'native-goal-fixture',model:'fixture',reasoningEffort:'high'});
await ctx.sessionController.commands.prompt({sessionId:embedded.id,requestId:crypto.randomUUID(),mode:'queue',
content:[{type:'text',text:'Create a goal and continue autonomously until the controlled task completes.'}]},{kind:'user',rpcId:crypto.randomUUID()});
const deadline=Date.now()+120000;
while(ctx.goals.get(embedded)?.phase!=='complete'&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,20));
await embedded.whenIdle();
const goal=ctx.goals.get(embedded);
assert.equal(goal?.phase,'complete',JSON.stringify({goal,responses,events:embedded.session.snapshotEvents().slice(-8)}));
assert.ok(goal.roundsStarted>0,'A goal must continue without a second human prompt');
release();
const report={status:'passed',presets:presets.map(p=>p.id),tools:names(embedded),nativeParity:true,fileWrite:true,shell:true,
goalCompleted:true,autonomousRounds:goal.roundsStarted,reasoningEffort:'high',responses};
await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));
await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
console.log(JSON.stringify(report));
}finally{await shutdown.shutdown(0);}
+22 -3
View File
@@ -2,7 +2,7 @@
import assert from 'node:assert/strict';
import {mkdtemp,mkdir,readFile,writeFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {bootRuntime,overlay,prepareProfileDirectory,TASK_TOOLS,FILE_TOOLS} from '../integration/dsh/start.mjs';
import {bootRuntime,overlay,prepareProfileDirectory,TASK_TOOLS} from '../integration/dsh/start.mjs';
const output=path.resolve('build/dsh-profile-settings-verification');
await mkdir(output,{recursive:true});
@@ -21,7 +21,10 @@ await prepareProfileDirectory(dir);await prepareProfileDirectory(dir);
assert.equal(await readFile(patch,'utf8'),original,'application preparation must not rewrite a native user layer');
const legacyDir=path.join(base,'legacy');
await mkdir(legacyDir,{recursive:true});
const old=JSON.stringify([...overlay(),...profile],null,2);
const legacy=overlay();
legacy.find(row=>row.insert?.some(entry=>entry.id==='dx-task')).insert.push(
{id:'preset-dx-task',name:'@deepseek-ai/dsh-agent-preset',config:{id:'dx-task',plugins:[]}});
const old=JSON.stringify([...legacy,...profile],null,2);
await writeFile(path.join(legacyDir,'cordis.patch.yml'),old);
await prepareProfileDirectory(legacyDir);
const migrated=await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8');
@@ -31,10 +34,26 @@ assert.equal(backups.length,1);
assert.equal(await readFile(path.join(legacyDir,backups[0]),'utf8'),old);
await prepareProfileDirectory(legacyDir);
assert.equal(await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8'),migrated);
// Native model edits must survive the application's next startup.
Object.assign(process.env,{DSH_API_BASE:'http://127.0.0.1:1/v1',DSH_API_KEY:'owned-fixture',DSH_MODEL:'native-reasoning'});
const metadataDir=path.join(base,'model-metadata');
await prepareProfileDirectory(metadataDir);
const metadataPatch=path.join(metadataDir,'cordis.patch.yml');
const modelRows=JSON.parse(await readFile(metadataPatch,'utf8'));
const model=modelRows.find(row=>row.id==='llm-pi-ai').config.providers.dx.models[0];
Object.assign(model,{contextWindow:262144,reasoningEfforts:{low:'low',medium:'medium',high:'high'}});
modelRows.push({id:'agent-default-model',config:{provider:'dx',model:'native-reasoning',reasoningEffort:'high'}});
await writeFile(metadataPatch,JSON.stringify(modelRows));
await prepareProfileDirectory(metadataDir);
const preserved=JSON.parse(await readFile(metadataPatch,'utf8'));
assert.deepEqual(preserved.find(row=>row.id==='llm-pi-ai').config.providers.dx.models[0],model);
assert.equal(preserved.find(row=>row.id==='agent-default-model').config.reasoningEffort,'high');
for(const key of ['DSH_API_BASE','DSH_API_KEY','DSH_MODEL'])delete process.env[key];
const {ctx,shutdown}=await bootRuntime({announce:false});
try{
assert.deepEqual((await ctx.llm.listModels('profile-fixture')).map(x=>x.id),['persisted-fixture-model']);
assert.equal(ctx.tools.schemas().length,TASK_TOOLS.length+FILE_TOOLS.length);
assert.ok(TASK_TOOLS.every(name=>ctx.tools.schemas().some(tool=>tool.name===name)));
assert.ok((await ctx.agentPresets.list()).some(preset=>preset.id==='standard'&&!preset.broken));
console.log(JSON.stringify({status:'passed',nativeSettingsPreserved:true,actualProviderRestored:true,
legacyMigrationPreservedModels:true,byteBackup:true,modelRequests:0}));
}finally{await shutdown.shutdown(0);}
+8 -8
View File
@@ -4,7 +4,7 @@ import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
import {createRequire} from 'node:module';
import {bootRuntime,TASK_TOOLS,FILE_TOOLS} from '../integration/dsh/start.mjs';
import {bootRuntime,TASK_TOOLS} from '../integration/dsh/start.mjs';
const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const output=path.join(repo,'build/dsh-native-cli-verification');
@@ -18,10 +18,10 @@ const report={};
try {
const schemas=ctx.tools.schemas();
report.tools=schemas.map(x=>x.name);
assert.deepEqual([...report.tools].sort(),[...TASK_TOOLS,...FILE_TOOLS].sort());
assert.ok(TASK_TOOLS.every(name=>report.tools.includes(name)));
const presets=await ctx.agentPresets.list();
report.presets=presets.map(x=>x.id);
assert.deepEqual(report.presets,['dx-task']);
for(const preset of ['standard','minimal','cordis','ptc','dx-task'])assert.ok(report.presets.includes(preset));
if(process.env.DSH_MODEL) {
report.configuredModels=(await ctx.llm.listModels('dx')).map(model=>model.id);
assert.ok(report.configuredModels.includes(process.env.DSH_MODEL));
@@ -47,11 +47,11 @@ try {
let bodyRan=false;
const release=ctx.tools.register(defineTool({name:'forbidden_probe',description:'Never executes',parameters:{},
output:{schema:{type:'boolean'},render:()=>[{type:'text',text:'probe'}]},execute:async()=>{bodyRan=true;return true;}}));
const denial=await ctx.tools.execute({callId:'verify-denial',name:'forbidden_probe',arguments:{},signal:new AbortController().signal});
const extension=await ctx.tools.execute({callId:'verify-extension',name:'forbidden_probe',arguments:{},signal:new AbortController().signal});
release();
assert.equal(denial.isError,true);
assert.equal(bodyRan,false);
report.forbiddenToolDenied=true;
assert.equal(extension.isError,false);
assert.equal(bodyRan,true);
report.nativeExtensionsAllowed=true;
const base=`http://127.0.0.1:${ctx.webServer.port}`;
const unauth=await fetch(base+'/dx/context');
assert.equal(unauth.status,401);
@@ -71,7 +71,7 @@ try {
report.authenticatedContextRead=true;
assert.ok((await fetch(base+'/dx/workspace',{headers:auth}).then(r=>r.json())).workspace_id);
const usage=await fetch(base+'/dx/runtime',{headers:auth}).then(r=>r.json());
assert.equal(usage.settings.response_timeout_seconds,90);
assert.equal(usage.settings.response_timeout_seconds,0);
assert.equal((await fetch(base+'/dx/operations',{method:'POST',headers:{...auth,'Content-Type':'application/json'},
body:JSON.stringify({revision:'stale',spec:{operation:'history'}})})).status,409);
report.operationsStaleAdmissionDenied=true;
+11
View File
@@ -15,6 +15,17 @@ async function wait(expression,timeout=30000){
}
try{
await wait(`!!document.querySelector('[contenteditable="true"]')`,50000);
const workspaceIndex=process.argv.indexOf('--workspace-root');
if(workspaceIndex>=0){
const directory=path.resolve(process.argv[workspaceIndex+1]);
await c.click(`document.querySelector('button[aria-label="添加工作区"]')`);
// The parent driver handles the real Win32 folder chooser.
await wait(`!!document.querySelector('button[aria-label="在“${path.basename(directory)}”中新建会话"]')`,60000);
await wait(`!document.querySelector('[role="dialog"]')&&!!document.querySelector('[contenteditable="true"]')`);
await c.screenshot(path.join(output,'working-folder-workspace.png'));
report.workspace_directory=directory;
report.checks.push('selected real engineering folder as Harness workspace through directory picker mouse and keyboard');
}
await c.click(`document.querySelector('[contenteditable="true"]')`);
const prompt='帮我建个换料任务,名字叫“DSH对话换料验收”,备注写“真实对话验收”。把 OLD123 换成 NEW456,料号也复制到 Value。工程目录我来选,先别开始替换。建好后告诉我数量和任务编号。';
report.prompt=prompt;
+22 -3
View File
@@ -30,10 +30,29 @@ await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'usage-f
const restored={id:'restored-session',session:{snapshotEvents:()=>historicalEvents}};
agents.set(restored.id,restored);
const runtime=await registerRuntimeUsage(fixture,{admit:()=>true});
assert.deepEqual(runtime.snapshot().settings,{response_timeout_seconds:0,model_context_limit:0});
assert.equal(runtime.snapshot().context_limit_mode,'native_model');
// Deep reasoning can exceed 90 seconds without the observer cancelling it.
const longRequest=Object.freeze({sessionId:restored.id,signal:new AbortController().signal});
mock.timers.enable({apis:['setTimeout','Date']});
let finished=false;
const longResponse=(async()=>{
for await(const chunk of listeners.get('llm/stream')(longRequest,async function*(){
await new Promise(resolve=>setTimeout(resolve,120000));
yield {type:'finish',reason:{kind:'stop'}};
})){}
finished=true;
})();
mock.timers.tick(90001);await Promise.resolve();
assert.equal(finished,false);
assert.equal(runtime.snapshot().sessions[0].status,'generating');
mock.timers.tick(30000);await longResponse;
assert.equal(runtime.snapshot().sessions[0].status,'completed');
mock.timers.reset();
let restoredRow=runtime.snapshot().sessions.find(row=>row.session_id===restored.id);
assert.equal(restoredRow.input_tokens,36);assert.equal(restoredRow.output_tokens,12);
assert.equal(restoredRow.cached_tokens,24);assert.equal(restoredRow.total_tokens,72);
assert.equal(restoredRow.usage_complete,false);assert.equal(restoredRow.response_count,4);
assert.equal(restoredRow.usage_complete,false);assert.equal(restoredRow.response_count,5);
assert.equal(restoredRow.elapsed_seconds,null);
assert.ok(!JSON.stringify(restoredRow).includes('PRIVATE_HISTORY_TEXT'));
// Re-announcement and a fresh response must not recharge historical events.
@@ -66,7 +85,7 @@ await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'usage-f
assert.equal(runtime.snapshot().sessions[0].status,'error');
await Promise.all([runtime.configure({response_timeout_seconds:120}),runtime.configure({model_context_limit:8000})]);
assert.deepEqual(runtime.snapshot().settings,{response_timeout_seconds:120,model_context_limit:8000});
await runtime.configure({response_timeout_seconds:90,model_context_limit:16000});
await runtime.configure({response_timeout_seconds:0,model_context_limit:0});
runtime.dispose();assert.equal(listeners.size,0);
}
if(process.argv.includes('--unit-only')){console.log('usage lifecycle boundary checks passed');process.exit(0);}
@@ -88,7 +107,7 @@ try{
const headers={Cookie:cookie,'Content-Type':'application/json'};
const get=async()=>{const response=await fetch(base+'/dx/runtime',{headers});assert.equal(response.status,200);return response.json();};
const control=body=>fetch(base+'/dx/runtime/control',{method:'POST',headers,body:JSON.stringify(body)});
assert.equal((await get()).settings.response_timeout_seconds,90);
assert.equal((await get()).settings.response_timeout_seconds,0);
for(const body of [{action:'configure',response_timeout_seconds:14},
{action:'configure',response_timeout_seconds:true},{action:'configure',model_context_limit:128001},
{action:'configure',model_context_limit:3000,secret:'rejected'},
+145
View File
@@ -0,0 +1,145 @@
/** Human-like inputs to the real UI, followed by independent artifact checks. */
import assert from 'node:assert/strict';
import {readFile,writeFile,mkdir} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import path from 'node:path';
import {connect,awaitRuntimeOrigin} from './dsh_cdp.mjs';
import {evidenceFor} from './harness_session_evidence.mjs';
import {skipQuestion} from './dsh_skip_question.mjs';
import {workspaceCandidates,verifyWorkspaces} from './acceptance_runtime_state.mjs';
const output=path.resolve(process.argv[2]);
const manifest=JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8'));
const c=await connect(Number(process.argv[3]),{expectedOrigin:manifest.runtime_origin});
if(manifest.runtime_origin)await awaitRuntimeOrigin(c,manifest.runtime_origin);
let report={git_head:manifest.git_head,source_patch_sha256:manifest.source_patch_sha256,
seed:manifest.seed,generation:manifest.generation,coverage:manifest.coverage,runtime:manifest.runtime,
driver:manifest.driver_description??'Qt mouse navigation + CDP mouse/keyboard Input',real_model:true,real_cad:false,samples:[]};
if(manifest.resume_completed){
const previous=JSON.parse(await readFile(path.join(output,'report.json'),'utf8'));
report.samples=previous.samples.filter(row=>row.turn_end||row.prompt);
}
const persist=()=>writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2));
const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].filter(e=>e.getBoundingClientRect().width>0)`;
const composer=`(${visible('[contenteditable="true"]')})[0]`;
const replies=`[...document.querySelectorAll('[data-chat-group-part="response"]')].map(e=>e.innerText).join(String.fromCharCode(10))`;
const stop=`(${visible('button[aria-label="停止生成"]')}).length>0`;
async function wait(expression,timeout=30000){
const end=Date.now()+timeout;
while(Date.now()<end){if(await c.evaluate(expression))return;await new Promise(resolve=>setTimeout(resolve,200));}
throw Error('UI timeout: '+expression);
}
async function send(prompt){
await c.click(composer);
await c.call('Input.insertText',{text:prompt});
await wait(`${composer}?.textContent.includes(${JSON.stringify(prompt)})`);
const button=`(${visible('button[aria-label="发送消息"]')})[0]`;
await wait(`!!${button}&&!${button}.disabled`);
await c.click(button);
await wait(`!${composer}?.textContent.includes(${JSON.stringify(prompt)})&&document.body.innerText.includes(${JSON.stringify(prompt)})`);
}
async function validate(sample){
const checks=[];
for(const [filename,expected] of Object.entries(sample.expected)){
try{
const text=await readFile(path.join(sample.directory,filename),'utf8');
const actual=typeof expected==='string'?text:JSON.parse(text.replace(/^\uFEFF/,''));
assert.deepEqual(actual,expected);
checks.push({file:filename,passed:true});
}catch(error){checks.push({file:filename,passed:false,error:error.message});}
}
for(const [filename,digest] of Object.entries(sample.input_hashes)){
try{
const actual=createHash('sha256').update(await readFile(path.join(sample.directory,filename))).digest('hex');
assert.equal(actual,digest);checks.push({original:filename,passed:true});
}catch(error){checks.push({original:filename,passed:false,error:error.message});}
}
return checks;
}
try{
await wait(`!!${composer}`,60000);
for(const sample of manifest.cases){
if(report.samples.some(row=>row.id===sample.id))continue;
const row={id:sample.id,status:'running',started_at:new Date().toISOString(),prompt:null};
report.samples.push(row);await persist();
const started=Date.now();
try{
const newChat=`(${visible('button[aria-label="新建会话"]')}).at(-1)`;
await wait(`!!${newChat}`);
const previousSessionIds=new Set(manifest.require_workspace_preflight
?JSON.parse(await readFile(path.join(output,'runtime-state.json'),'utf8')).sessions.map(session=>session.id):[]);
await c.click(newChat);
await wait(`!!${composer}&&(${replies}).length===0`);
if(manifest.require_workspace_preflight){
let state,candidates=[];
const until=Date.now()+15000;
while(Date.now()<until){
state=JSON.parse(await readFile(path.join(output,'runtime-state.json'),'utf8'));
candidates=workspaceCandidates(state,previousSessionIds,manifest.workspace);
if(candidates.length)break;
await new Promise(resolve=>setTimeout(resolve,200));
}
verifyWorkspaces(candidates,manifest.workspace);
row.workspace_preflight={...state,verified_session_ids:candidates.map(session=>session.id)};
assert.ok(candidates.every(session=>session.shell_preflight?.passed),'Actual official shell preflight failed: '+JSON.stringify(candidates.map(session=>session.shell_preflight)));
}
const prompt=`这是本地验收任务,工作目录:${sample.directory}。所有输入都在这个目录,生成文件也放在这个目录。请实际完成操作,保留原始输入文件。\n${sample.request}\n完成后简要说明实际结果和产物路径;不能完成时明确说明原因。`;
row.prompt=prompt;await persist();
await send(prompt);
// Durable turn events decide completion. Tool-only or delayed-rendering
// responses need not expose text/a visible stop button within 60 seconds.
const deadline=Date.now()+(manifest.case_budget_ms??(sample.goal?600000:240000));
let sessionFile;
while(Date.now()<deadline){
const state=await c.evaluate(`({stopped:!(${stop}),reply:${replies},text:document.body.innerText})`);
const decline=`(${visible('button')}).find(e=>e.textContent.trim()==='拒绝')`;
const approval=await c.evaluate(`!!(${visible('button')}).find(e=>e.textContent.trim()==='允许一次')`);
if(approval){
(row.confirmations??=[]).push({decision:'deny',reason:'No OS permission changes are part of these file tasks',text:state.text.slice(-7000)});
await c.screenshot(path.join(output,sample.id+'-approval-'+row.confirmations.length+'.png'));
await c.click(decline);
}
await skipQuestion(c,output,sample.id);
const evidence=await evidenceFor(path.join(manifest.data,'dsh/harness-home'),prompt,sessionFile);
sessionFile=evidence.filename;
if(evidence.complete){
row.reply=state.reply;row.session_file=sessionFile;row.turn_end=evidence.reason;
row.goal=evidence.goal;
row.usage_events=evidence.events.filter(event=>event.data?.usage).map(event=>({seq:event.seq,type:event.type,usage:event.data.usage}));
row.model_routes=evidence.events.filter(event=>event.type==='request/context').map(event=>event.data);
row.event_count=evidence.events.length;
row.tool_calls=evidence.events.filter(event=>event.type==='tool/call').map(event=>({name:event.data.name,arguments:event.data.arguments}));
break;
}
await new Promise(resolve=>setTimeout(resolve,600));
}
if(row.reply===undefined)throw Error('Model task did not finish within the acceptance observation window');
row.checks=await validate(sample);
row.status=row.checks.every(check=>check.passed)?'passed':'failed';
if(row.turn_end?.kind!=='completed')row.status='failed';
if(sample.goal&&manifest.require_host_goal!==false&&row.goal?.phase!=='complete')row.status='failed';
await c.screenshot(path.join(output,sample.id+'.png'));
await writeFile(path.join(output,sample.id+'-reply.txt'),row.reply);
}catch(error){
if(!row.prompt){
report.samples.pop();report.status='setup_failed';report.setup_error=error.message;
report.setup_evidence=row.workspace_preflight;await persist();throw error;
}
row.status='failed';row.error=error.message;
row.reply=await c.evaluate(replies).catch(()=>null);
await c.screenshot(path.join(output,sample.id+'-failure.png')).catch(()=>{});
// An observer failure must never advance into another sample and abort
// the current model turn. Preserve it separately from semantic failures.
row.status='observation_failed';report.status='observation_failed';
report.observation_error=error.message;await persist();throw error;
}
row.seconds=Math.round((Date.now()-started)/10)/100;
await persist();console.log(JSON.stringify({id:row.id,status:row.status,seconds:row.seconds,error:row.error}));
}
report.passed=report.samples.filter(row=>row.status==='passed').length;
report.failed=report.samples.length-report.passed;
report.status=report.failed?'failed':'passed';
process.exitCode=report.failed?1:0;
await persist();
console.log(JSON.stringify({status:report.status,passed:report.passed,failed:report.failed}));
}finally{c.close();}