Selaa lähdekoodia

Reuse RTL evidence only after complete content and toolchain validation

codex 2 kuukautta sitten
vanhempi
commit
d6b6dbbf4a
3 muutettua tiedostoa jossa 257 lisäystä ja 36 poistoa
  1. 1 0
      config/current-product-tests.json
  2. 86 0
      tests/unit/test_rtl_result_reuse.py
  3. 170 36
      tools/fw_cli.py

+ 1 - 0
config/current-product-tests.json

@@ -9,6 +9,7 @@
     "tests/unit/test_fw_6400_v1_entrypoint.py",
     "tests/unit/test_td_reaudit.py",
     "tests/unit/test_source_package_closure.py",
+    "tests/unit/test_rtl_result_reuse.py",
     "tests/unit/test_package_archive_v2.py",
     "tests/unit/test_6400_canonical_packages.py",
     "tests/unit/test_gui_build_identity.py",

+ 86 - 0
tests/unit/test_rtl_result_reuse.py

@@ -0,0 +1,86 @@
+from copy import deepcopy
+from pathlib import Path
+import json
+import pytest
+from tools import fw_cli as fw
+
+@pytest.fixture
+def cached(tmp_path):
+    root=tmp_path/'old';root.mkdir()
+    plan={'schema':'prod2u-rtl-input-closure-v1','inputs':{'fixture':{'source.v':'c'*64}},
+          'tools':{'iverilog':{'sha256':'d'*64},'vvp':{'sha256':'e'*64}},
+          'test_configuration':{'fixture':['tb']},
+          'steps':[{'name':'tb-compile','command':['iverilog','-o','{run_root}/tb.vvp','source.v'],'marker':None,'binary':'tb.vvp'},
+                   {'name':'tb','command':['vvp','{run_root}/tb.vvp'],'marker':'tb PASS','binary':None}]}
+    rows=[]
+    for step in plan['steps']:
+        command=fw._render_command(step,root);log=root/(step['name']+'.log')
+        log.write_text(json.dumps(command)+'\n'+(step['marker'] or 'compiled')+'\n')
+        rows.append({'name':step['name'],'command':command,'required_marker':step['marker'],
+                     'status':'PASS','exit_code':0,'log':log.name,'log_sha256':fw._file_hash(log)})
+    (root/'tb.vvp').write_bytes(b'unit cache fixture')
+    result={'schema':'prod2u-rtl-regression-v2','status':'PASS','complete':True,'expected_check_count':2,
+            'plan':plan,'cache_key':fw._json_hash(plan),'inputs':plan['inputs'],'native_run_root':str(root),
+            'source':{'commit':'a'*40,'tree':'b'*40},'commit':'a'*40,'tree':'b'*40,'results':rows,
+            'artifacts':{'tb.vvp':fw._file_hash(root/'tb.vvp')}}
+    path=root/'RESULT.json';path.write_text(json.dumps(result))
+    return path,plan,result
+
+def test_valid_cache_preserves_native_commands_and_copies_verified_bytes(cached):
+    path,plan,_=cached
+    result,copies,original=fw.validate_rtl_cache(path,plan)
+    assert copies['tb.vvp']==b'unit cache fixture'
+    assert result['results'][0]['command'][2].startswith(str(path.parent))
+    assert original==path.read_bytes()
+
+@pytest.mark.parametrize('change',['source','tool','command','test_list'])
+def test_changed_content_closure_is_rejected(cached,change):
+    path,plan,_=cached;wanted=deepcopy(plan)
+    if change=='source':wanted['inputs']['fixture']['source.v']='f'*64
+    elif change=='tool':wanted['tools']['vvp']['sha256']='f'*64
+    elif change=='command':wanted['steps'][1]['command'].append('+different_seed')
+    else:wanted['test_configuration']['fixture'].append('another_tb')
+    with pytest.raises(ValueError,match='closure differs'):fw.validate_rtl_cache(path,wanted)
+
+@pytest.mark.parametrize('change',['running','failed','partial','empty','missing_result','wrong_command','wrong_marker','source_identity','missing_binary'])
+def test_partial_or_inconsistent_receipt_is_rejected(cached,change):
+    path,plan,result=cached
+    if change=='running':result['status']='RUNNING'
+    elif change=='failed':result['status']='FAIL'
+    elif change=='partial':result['complete']=False
+    elif change=='empty':result['results']=[];result['expected_check_count']=0
+    elif change=='missing_result':result['results'].pop()
+    elif change=='wrong_command':result['results'][0]['command'][0]='true'
+    elif change=='wrong_marker':result['results'][1]['required_marker']=None
+    elif change=='source_identity':result['source']['commit']='unknown'
+    else:result['artifacts']={}
+    path.write_text(json.dumps(result))
+    with pytest.raises(ValueError,match='RTL_REUSE_REJECTED'):fw.validate_rtl_cache(path,plan)
+
+@pytest.mark.parametrize('name',['tb.log','tb.vvp'])
+def test_changed_native_bytes_are_rejected(cached,name):
+    path,plan,_=cached;(path.parent/name).write_bytes(b'changed')
+    with pytest.raises(ValueError,match='hash mismatch'):fw.validate_rtl_cache(path,plan)
+
+def test_missing_pass_marker_is_rejected_even_if_receipt_hash_was_updated(cached):
+    path,plan,result=cached
+    log=path.parent/'tb.log';log.write_text(json.dumps(result['results'][1]['command'])+'\nno result\n')
+    result['results'][1]['log_sha256']=fw._file_hash(log);path.write_text(json.dumps(result))
+    with pytest.raises(ValueError,match='marker mismatch'):fw.validate_rtl_cache(path,plan)
+
+def test_readme_and_unit_list_are_not_part_of_rtl_configuration(tmp_path,monkeypatch):
+    monkeypatch.setattr(fw,'ROOT',tmp_path);monkeypatch.setattr(fw,'_generator_dependencies',lambda:set())
+    registry={'targets':{'fixture':{'project_id':'fixture','project_config':'products/fixture/project.json'}}}
+    monkeypatch.setattr(fw,'load_registry',lambda _:registry)
+    for name,data in {'products/fixture/source-closure.json':json.dumps({'sources':['src/top.v'],'top_module':'top'}),
+                      'products/fixture/project.json':'{}','src/top.v':'module top;endmodule',
+                      'tests/sim/tb.v':'module tb;endmodule','tools/fw_cli.py':'runner',
+                      'projects/registry.json':json.dumps(registry),'README.md':'old',
+                      'config/current-product-tests.json':'old unit list'}.items():
+        path=tmp_path/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_text(data)
+    tools={'iverilog':{'library_root':'/fixture/lib'}}
+    before=fw.rtl_plan(['fixture'],{'fixture':['tb']},tools)
+    (tmp_path/'README.md').write_text('new docs');(tmp_path/'config/current-product-tests.json').write_text('new Python test list')
+    assert before==fw.rtl_plan(['fixture'],{'fixture':['tb']},tools)
+    (tmp_path/'src/top.v').write_text('changed RTL')
+    assert before!=fw.rtl_plan(['fixture'],{'fixture':['tb']},tools)

+ 170 - 36
tools/fw_cli.py

@@ -4,11 +4,13 @@
 from __future__ import annotations
 
 import argparse
+import ast
 import hashlib
 import json
 import os
 import re
 import signal
+import shutil
 import subprocess
 import sys
 import tempfile
@@ -102,7 +104,8 @@ def cmd_test(args: argparse.Namespace) -> int:
     unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0
     receipt['unit']={'command':command,'exit_code':unit_code,'tests':unit_count,'skipped':unit_skipped,'status':'PASS' if unit_pass else 'FAIL','log':str(log_path),'log_sha256':hashlib.sha256(log_path.read_bytes()).hexdigest()}
     print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True)
-    rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',timeout=args.timeout))
+    rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',
+        timeout=args.timeout,reuse_rtl=getattr(args,'reuse_rtl',None)))
     receipt['rtl_result']=str(out/'rtl/RESULT.json');receipt['complete']=True
     receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL'
     receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
@@ -116,6 +119,140 @@ def cmd_package(args: argparse.Namespace) -> int:
     return package_main(args.package_args)
 
 
+def _file_hash(path):
+    with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
+
+def _json_hash(value):
+    return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
+
+def _generator_dependencies():
+    pending=['tools/generate_target.py','tools/generate_6400_manual.py','tools/generate_mrdimm_params.py',
+             'tools/generate_mrdimm_adc.py','tools/target_registry.py','tools/fw_targets.py']
+    found=set()
+    while pending:
+        name=pending.pop()
+        if name in found:continue
+        found.add(name)
+        for node in ast.walk(ast.parse((ROOT/name).read_text(encoding='utf-8-sig'))):
+            modules=[a.name for a in node.names] if isinstance(node,ast.Import) else (
+                [node.module,*[node.module+'.'+a.name for a in node.names]] if isinstance(node,ast.ImportFrom) and node.module else [])
+            for module in modules:
+                path=module.replace('.','/')+'.py'
+                if module.startswith('tools.') and (ROOT/path).is_file():pending.append(path)
+    return found
+
+def rtl_plan(products,tests,tools):
+    registry=load_registry(ROOT)
+    inputs={};steps=[]
+    generator_files=_generator_dependencies()
+    for product in products:
+        manifest_path='products/'+product+'/source-closure.json'
+        manifest=json.loads((ROOT/manifest_path).read_text(encoding='utf-8'))
+        sources=manifest['sources']
+        target=next(row for row in registry['targets'].values() if row['project_id']==product)
+        paths=set(sources)|generator_files|{manifest_path,'tools/fw_cli.py','projects/registry.json'}
+        paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT/'contracts').glob('*') if p.suffix in ('.json','.yaml'))
+        for key in ('project_config','adc','sdc'):
+            if target.get(key):paths.add(target[key])
+        projects=[target['project_config']];seen_projects=set()
+        while projects:
+            name=projects.pop()
+            if name in seen_projects:continue
+            seen_projects.add(name);paths.add(name)
+            configuration=json.loads((ROOT/name).read_text(encoding='utf-8'))
+            if configuration.get('inherits'):projects.append(configuration['inherits'])
+            for key in ('board_evidence','constraints','source_closure'):
+                value=configuration.get(key)
+                if isinstance(value,str) and (ROOT/value).is_file():paths.add(value)
+        if product=='mrdimm-chamber':paths.add('config/pin_inventory.prod2u_door_temp_v1_2.json')
+        paths.update('tests/sim/'+name+'.v' for name in tests[product])
+        if product=='6400-front-rear':paths.add('src/modules/double_bank_target_store.v')
+        pending=list(paths)
+        while pending:
+            name=pending.pop()
+            if Path(name).suffix not in ('.v','.sv','.vh'):continue
+            for include in re.findall(chr(96)+r'include\s+"([^"]+)"',(ROOT/name).read_text(encoding='utf-8')):
+                path=include if (ROOT/include).is_file() else (Path(name).parent/include).as_posix()
+                if path not in paths:paths.add(path);pending.append(path)
+        inputs[product]={name:_file_hash(ROOT/name) for name in sorted(paths)}
+        source_args=[name for name in sources if name.endswith('.v')]
+        for top,behavior in [(manifest['top_module'],False),*((name,True) for name in tests[product])]:
+            if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',top):raise ValueError('invalid regression top')
+            binary='{run_root}/'+top+'.vvp'
+            command=['iverilog','-g2012','-Wall','-I.','-B',tools['iverilog']['library_root'],'-s',top,'-o',binary,*source_args]
+            if behavior:
+                command.append('tests/sim/'+top+'.v')
+                if top=='prod2u_6400_uart_e2e_tb':command.append('src/modules/double_bank_target_store.v')
+            steps.append({'name':top+'-compile','command':command,'marker':None,'binary':top+'.vvp'})
+            if behavior:steps.append({'name':top,'command':['vvp',binary,'+ARTIFACT_DIR={run_root}'],'marker':top+' PASS','binary':None})
+    if len({x['name'] for x in steps})!=len(steps):raise ValueError('duplicate regression output names')
+    return {'schema':'prod2u-rtl-input-closure-v1','inputs':inputs,'tools':tools,
+            'test_configuration':{p:tests[p] for p in products},'steps':steps}
+
+def _render_command(step,run_root):
+    return [arg.replace('{run_root}',str(run_root)) for arg in step['command']]
+
+def validate_rtl_cache(path,plan):
+    path=Path(path).resolve();receipt_bytes=path.read_bytes();cached=json.loads(receipt_bytes)
+    if cached.get('schema')!='prod2u-rtl-regression-v2' or cached.get('status')!='PASS' or cached.get('complete') is not True:
+        raise ValueError('RTL_REUSE_REJECTED: only complete v2 PASS receipts can be reused')
+    key=_json_hash(plan)
+    if cached.get('cache_key')!=key or cached.get('plan')!=plan:
+        raise ValueError('RTL_REUSE_REJECTED: input/tool/command closure differs')
+    if not plan['steps'] or cached.get('inputs')!=plan['inputs']:
+        raise ValueError('RTL_REUSE_REJECTED: empty or inconsistent input evidence')
+    origin=cached.get('source',{})
+    if any(not re.fullmatch('[0-9a-f]{40}',str(origin.get(k,''))) or origin.get(k)!=cached.get(k) for k in ('commit','tree')):
+        raise ValueError('RTL_REUSE_REJECTED: source identity missing or inconsistent')
+    rows=cached.get('results',[])
+    if len(rows)!=len(plan['steps']) or cached.get('expected_check_count')!=len(rows):
+        raise ValueError('RTL_REUSE_REJECTED: missing checks')
+    native_root=cached.get('native_run_root')
+    if not native_root or not Path(native_root).is_absolute():raise ValueError('RTL_REUSE_REJECTED: native command root missing')
+    copies={}
+    for expected,row in zip(plan['steps'],rows):
+        command=_render_command(expected,native_root)
+        name=expected['name']+'.log'
+        if (row.get('name')!=expected['name'] or row.get('command')!=command or row.get('required_marker')!=expected['marker']
+            or row.get('status')!='PASS' or row.get('exit_code')!=0 or row.get('log')!=name):
+            raise ValueError('RTL_REUSE_REJECTED: result/command mismatch')
+        data=(path.parent/name).read_bytes()
+        if hashlib.sha256(data).hexdigest()!=row.get('log_sha256'):raise ValueError('RTL_REUSE_REJECTED: log hash mismatch')
+        text=data.decode('utf-8',errors='replace')
+        lines=text.splitlines()
+        if not lines or json.loads(lines[0])!=command or (expected['marker'] and expected['marker'] not in text):
+            raise ValueError('RTL_REUSE_REJECTED: native log/marker mismatch')
+        copies[name]=data
+    artifacts=cached.get('artifacts',{})
+    required={step['binary'] for step in plan['steps'] if step['binary']}
+    if not required<=set(artifacts):raise ValueError('RTL_REUSE_REJECTED: compiled binaries missing')
+    for name,expected_hash in artifacts.items():
+        if not re.fullmatch(r'[A-Za-z0-9_.-]+\.(vvp|hex)',name):
+            raise ValueError('RTL_REUSE_REJECTED: invalid artifact name')
+        data=(path.parent/name).read_bytes()
+        if not data or hashlib.sha256(data).hexdigest()!=expected_hash:raise ValueError('RTL_REUSE_REJECTED: artifact hash mismatch')
+        copies[name]=data
+    return cached,copies,receipt_bytes
+
+def _rtl_tools():
+    result={}
+    driver=Path(shutil.which('iverilog') or '')
+    requested=os.environ.get('PROD2U_IVERILOG_LIBDIR')
+    candidates=[Path(requested)] if requested else [driver.parent.parent/'lib/ivl',*sorted(Path('/usr/lib').glob('*/ivl'))]
+    library=next((p.resolve() for p in candidates if (p/'ivl').is_file() and (p/'ivlpp').is_file()),None)
+    if library is None:raise ValueError('Icarus backend directory unavailable; set PROD2U_IVERILOG_LIBDIR')
+    for tool in ('iverilog','vvp'):
+        path=Path(shutil.which(tool) or '')
+        if not path.is_file():raise ValueError('RTL tool missing: '+tool)
+        version=subprocess.check_output([tool,*(['-B',str(library)] if tool=='iverilog' else []),'-V'],stderr=subprocess.STDOUT)
+        result[tool]={'path':str(path.resolve()),'sha256':_file_hash(path),'version':version.decode(errors='replace').splitlines()[0],
+                      'version_output_sha256':hashlib.sha256(version).hexdigest()}
+    result['iverilog']['library_root']=str(library)
+    result['iverilog']['library_files']={p.relative_to(library).as_posix():_file_hash(p) for p in sorted(library.rglob('*')) if p.is_file()}
+    import yaml
+    result['python']=sys.version;result['PyYAML']=yaml.__version__
+    return result
+
 def cmd_diagnose(args: argparse.Namespace) -> int:
     """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
     if sys.platform != "linux":
@@ -123,7 +260,6 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
     out = args.run_root.resolve()
     if out == ROOT or ROOT in out.parents:
         return _die("--run-root must be outside the source checkout")
-    out.mkdir(parents=True, exist_ok=False)
     products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,)
     test_manifest_path=ROOT/'config/current-product-tests.json'
     test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8'))
@@ -132,15 +268,30 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
     tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()}
     if any(not tests[p] for p in products):
         return _die('empty current product test set')
-    receipt = {"scope": "migration-diagnostic-only", "run_id": out.name,
-               "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
-               "expected_check_count": sum(1 + 2 * len(tests[p]) for p in products)}
+    for product in products:_generate_one(product,check=True)
+    plan=rtl_plan(products,tests,_rtl_tools())
     identity=source_identity(ROOT)
+    reuse=getattr(args,'reuse_rtl',None)
+    if reuse:
+        cached,copies,receipt_bytes=validate_rtl_cache(reuse,plan)
+        out.mkdir(parents=True,exist_ok=False)
+        for name,data in copies.items():(out/name).write_bytes(data)
+        receipt={**cached,'run_id':out.name,'source':identity,'commit':identity['commit'],'tree':identity['tree'],
+                 'execution':'reused','reuse':{'receipt':str(Path(reuse).resolve()),'sha256':hashlib.sha256(receipt_bytes).hexdigest(),
+                                             'source':cached['source'],'scope':'copied verified native evidence; no RTL command rerun'}}
+        (out/'REUSED-RECEIPT.json').write_bytes(receipt_bytes)
+        (out/'RESULT.json').write_text(json.dumps(receipt,indent=2)+'\n',encoding='utf-8')
+        print('RTL evidence reused after exact closure/log/artifact checks: '+str(reuse),flush=True)
+        return 0
+    out.mkdir(parents=True,exist_ok=False)
+    receipt = {"schema":"prod2u-rtl-regression-v2","scope": "migration-diagnostic-only", "run_id": out.name,
+               "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
+               "expected_check_count":len(plan['steps']),"plan":plan,"cache_key":_json_hash(plan),
+               "native_run_root":str(out),"execution":"fresh"}
     receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity
-    for tool, flag in (("iverilog", "-V"), ("vvp", "-V")):
-        receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0]
+    for tool in ('iverilog','vvp'):receipt[tool]=plan['tools'][tool]['version']
 
-    def execute(name: str, command: list[str], marker: str | None = None) -> bool:
+    def execute(name: str, command: list[str], marker: str | None = None,binary=None) -> bool:
         log_path = out / (name + ".log")
         with log_path.open("w", encoding="utf-8") as log:
             log.write(json.dumps(command) + "\n"); log.flush()
@@ -150,7 +301,7 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
             except subprocess.TimeoutExpired:
                 os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
         observed = log_path.read_text(errors="replace")
-        passed = code == 0 and (marker is None or marker in observed)
+        passed = code == 0 and (marker is None or marker in observed) and (not binary or ((out/binary).is_file() and (out/binary).stat().st_size>0))
         receipt["results"].append({"name": name, "command": command, "exit_code": code,
             "status": "PASS" if passed else "FAIL", "required_marker": marker,
             "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
@@ -160,34 +311,15 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
         print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
         return passed
 
-    for product in products:
-        manifest_path = ROOT / "products" / product / "source-closure.json"
-        manifest = json.loads(manifest_path.read_text())
-        sources = manifest["sources"]
-        benches = tests[product]
-        contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"]
-        input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches])
-        input_paths.add(manifest_path.relative_to(ROOT).as_posix())
-        # Include transitive generated headers imported by the mailbox.
-        input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh"))
-        input_paths.add("tools/fw_cli.py")
-        input_paths.add("config/current-product-tests.json")
-        input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "tests/sim").glob("*.vh"))
-        if product == "6400-front-rear":
-            input_paths.add("src/modules/double_bank_target_store.v")
-        receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)}
-        source_args = [p for p in sources if p.endswith(".v")]
-        for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]:
-            binary = out / (top + ".vvp")
-            argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args]
-            if behavior:
-                argv.append(f"tests/sim/{top}.v")
-                if top == "prod2u_6400_uart_e2e_tb":
-                    argv.append("src/modules/double_bank_target_store.v")
-            if execute(top + "-compile", argv) and behavior:
-                execute(top, ["vvp", str(binary), "+ARTIFACT_DIR=" + str(out)], top + " PASS")
+    receipt['inputs']=plan['inputs']
+    compile_pass={}
+    for step in plan['steps']:
+        if step['binary']:
+            compile_pass[step['name'].removesuffix('-compile')]=execute(step['name'],_render_command(step,out),None,step['binary'])
+        elif compile_pass.get(step['name']):
+            execute(step['name'],_render_command(step,out),step['marker'])
     receipt["complete"] = True
-    receipt["artifacts"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in out.glob("*.hex")}
+    receipt["artifacts"] = {p.name: _file_hash(p) for p in out.iterdir() if p.suffix in (".hex",".vvp")}
     receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all(
         item["status"] == "PASS" for item in receipt["results"]) else "FAIL"
     (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
@@ -205,10 +337,12 @@ def main(argv: list[str] | None = None) -> int:
     tes.add_argument("target")
     tes.add_argument("--run-root",type=Path)
     tes.add_argument("--timeout",type=int,default=180)
+    tes.add_argument("--reuse-rtl",type=Path,help="reuse only matching complete RTL evidence; Python tests still run")
     diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
     diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber"))
     diag.add_argument("--run-root", type=Path, required=True)
     diag.add_argument("--timeout", type=int, default=60)
+    diag.add_argument("--reuse-rtl",type=Path,help="verified v2 RTL receipt; mismatches reject instead of silently rerunning")
     bld = sub.add_parser("build")
     bld.add_argument("target")
     bld.add_argument("--run-root",type=Path)