Repository navigation
Expand file tree
/
Copy pathblackwall
More file actions
executable file
·528 lines (485 loc) · 29.1 KB
/
Copy pathblackwall
File metadata and controls
executable file
·528 lines (485 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#!/usr/bin/env python3
"""Run pinned G2 emulator scenarios using a Docker asset volume."""
import argparse
import copy
import hashlib
import http.server
import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
import sys
import tempfile
from datetime import datetime
from uuid import uuid4
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / 'tools'))
from run_original_boot_screen import checked_asset
from volume_storage import IMAGE, extract_volume, import_volume, pinned_inputs, select_profile, volume_name
DEFAULT_VOLUME = 'blackwall-assets'
SCENARIOS = {
'normal': 'Stock 2.4 bootloader -> main -> virtual touch and screen',
'unknown-boot-marker': 'Expected rejection at the virtual boot metadata boundary',
'post-screen-touch': 'Untouched stock baseline, matched no-input control, and post-screen virtual touch',
'imu-stock': 'Fresh stock boot, naturally ready IMU FIFO input, and matched no-input control',
}
def show_assets(profile):
print('Docker image:', profile['image_id'])
for group in ('assets', 'components'):
for name, spec in profile[group].items():
print(f"{group}/{name}: {spec['path']} sha256={spec['sha256']}")
def apply_images(workspace, profile, boot, main):
for key, override in (('boot', boot), ('main', main)):
if override:
spec = profile['assets'][key]
source = checked_asset(workspace, spec, override)
target = workspace / spec['path']
if source != target:
shutil.copyfile(source, target)
def setup(args):
source = args.source.expanduser().resolve()
profile_file = select_profile(source, args.profile)
if not profile_file:
raise ValueError('Selected profile was not found in the supplied source directory')
profile, entries = pinned_inputs(source, profile_file, args.boot_image, args.main_image)
import_volume(args.volume, entries)
print('Created Docker volume:', args.volume)
show_assets(profile)
return 0
def inspect_volume(args):
with tempfile.TemporaryDirectory(prefix='blackwall-inspect-') as folder:
root = Path(folder)
profile_file = extract_volume(args.volume, root)
profile = json.loads(profile_file.read_text())
apply_images(root, profile, args.boot_image, args.main_image)
pinned_inputs(root, profile_file)
print('Verified Docker volume:', args.volume)
show_assets(profile)
try:
validate_post_screen_source(profile, root)
except
8000
ValueError:
print('Stock comparison scenarios: unavailable for this profile; see docs/architecture/docker-volume-workflow.md')
else:
print('Stock comparison scenarios: compatible (post-screen-touch, imu-stock)')
return 0
def report(args):
if args.scenario == 'post-screen-touch' and (args.capture or args.scenario_file):
raise ValueError('post-screen-touch requires a fresh pinned volume, not --capture or --scenario-file')
if args.scenario == 'imu-stock' and (args.capture or args.scenario_file):
raise ValueError('imu-stock requires a fresh pinned volume, not --capture or --scenario-file')
if args.capture and (args.scenario or args.scenario_file or args.boot_image or args.main_image):
raise ValueError('--capture cannot be combined with a new scenario or firmware input')
if args.scenario and args.scenario_file:
raise ValueError('--scenario and --scenario-file cannot be combined')
if not 1 <= args.port <= 65535:
raise ValueError('--port must be 1..65535')
if args.scenario == 'imu-stock':
from imu_stock_scenario import require_private_workspace_owner_support
require_private_workspace_owner_support()
output = args.output.expanduser().resolve() if args.output else Path(tempfile.gettempdir()) / ('blackwall-report-' + datetime.now().strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:8])
if output.exists() or output.is_relative_to(ROOT):
raise ValueError('Output must be a new directory outside the repository')
output.mkdir(mode=0o700, parents=True)
if args.scenario == 'imu-stock':
try:
profile_file = extract_volume(args.volume, output)
profile = json.loads(profile_file.read_text())
apply_images(output, profile, args.boot_image, args.main_image)
pinned_inputs(output, profile_file)
from run_original_boot_screen import write_json
write_json(profile_file, profile)
validate_post_screen_source(profile, output)
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError,
KeyError, TypeError, AttributeError):
shutil.rmtree(output)
raise
status = run_imu_stock_report(output, profile_file)
if status == 0 and args.serve:
serve_report(output / 'run' / 'report', args.port)
return status
if args.scenario == 'post-screen-touch' and not args.capture:
try:
profile_file = extract_volume(args.volume, output)
profile = json.loads(profile_file.read_text())
apply_images(output, profile, args.boot_image, args.main_image)
pinned_inputs(output, profile_file)
from run_original_boot_screen import write_json
write_json(profile_file, profile)
validate_post_screen_source(profile, output)
from run_original_boot_screen import effective_stock_profile
profile_file = effective_stock_profile(profile, output) or profile_file
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError,
KeyError, TypeError, AttributeError):
shutil.rmtree(output)
raise
return run_post_screen_report(args, output, profile_file)
command = [sys.executable, '-B', str(ROOT / 'tools/blackwall_report.py'), '--workspace', str(output), '--output', str(output / 'run')]
try:
if args.capture:
command += ['--capture', str(args.capture.expanduser().resolve())]
else:
profile_file = extract_volume(args.volume, output)
profile = json.loads(profile_file.read_text())
apply_images(output, profile, args.boot_image, args.main_image)
pinned_inputs(output, profile_file)
if args.scenario in (None, 'normal') and not args.scenario_file:
from run_original_boot_screen import effective_stock_profile
profile_file = effective_stock_profile(profile, output) or profile_file
command += ['--profile', str(profile_file), '--scenario', args.scenario or 'normal']
if args.scenario_file:
command += ['--scenario-file', str(args.scenario_file.expanduser().resolve())]
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
# The output was created by this invocation and no emulator run has started.
shutil.rmtree(output)
raise
print('Output:', output, flush=True)
result = subprocess.run(command, cwd=ROOT)
page = output / 'run/report/index.html'
if page.is_file():
print('\nReport:', page, flush=True)
if args.serve:
serve_report(page.parent, args.port)
return result.returncode
def serve_report(directory, port):
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *a, **kw):
super().__init__(*a, directory=str(directory), **kw)
try:
server = http.server.ThreadingHTTPServer(('127.0.0.1', port), Handler)
except OSError as exc:
raise ValueError('Could not start local server: ' + str(exc)) from exc
print(f'Open http://127.0.0.1:{port}/ (Ctrl-C to stop)', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
def validate_post_screen_source(profile, workspace):
"""Check all source pins and runner basenames before any emulator starts."""
from run_original_boot_screen import PROFILE, PINNED_IMAGES, checked_asset, validate_profile
from volume_storage import INITIAL_MEMORY
validate_profile(profile)
canonical = json.loads(PROFILE.read_text())
# Docker volume paths may differ, but every other canonical profile field is pinned.
canonical = copy.deepcopy(canonical)
for key in ('boot', 'main', 'sram', 'itcm'):
canonical['assets'][key]['path'] = profile['assets'][key]['path']
if profile != canonical:
raise ValueError('Comparison scenarios require the canonical stock24 profile and component pins. Create a new volume with the current stock profile; see docs/architecture/docker-volume-workflow.md')
if profile['assets']['main']['path'].split('/')[-1] != 'main.bin':
8000
raise ValueError('Pinned runner requires main.bin in the reference directory')
for key, basename in (('sram', 'sram-fill.bin'), ('itcm', 'itcm-fill.bin')):
if profile['assets'][key]['path'].split('/')[-1] != basename:
raise ValueError('Pinned runner requires ' + basename + ' in the reference directory')
pins = {**PINNED_IMAGES, **{key: dict(bytes=value[0], sha256=value[1]) for key, value in INITIAL_MEMORY.items()}}
for key in ('boot', 'main', 'sram', 'itcm'):
path = checked_asset(workspace, profile['assets'][key])
pin = pins[key]
if path.stat().st_size != pin['bytes'] or hashlib.sha256(path.read_bytes()).hexdigest() != pin['sha256']:
raise ValueError('Post-screen scenario source asset failed its hash/size pin: ' + key)
return True
def run_post_screen_report(args, workspace, profile_file):
"""Run the untouched baseline and paired variants, then securely render evidence."""
from run_original_boot_screen import derive, run as run_boot
from probe_post_screen_touch import audit_pair, execute_pair
from post_screen_report import render_post_screen_report
baseline = workspace / 'run' / 'baseline'
pair = workspace / 'run' / 'pair'
report_dir = workspace / 'run' / 'report'
baseline.parent.mkdir(mode=0o700, parents=True)
derive(profile_file, workspace, baseline, 'normal')
if not run_boot(baseline):
raise RuntimeError('Untouched stock baseline failed; private evidence was preserved')
pair.mkdir(mode=0o700)
execute_pair(pair, profile_file, workspace)
paired = audit_pair(pair, baseline)
(pair / 'post-screen-touch-audit.json').write_text(json.dumps(paired, indent=2) + '\n')
if paired.get('passed') is not True:
raise ValueError('Post-screen paired audit failed; private evidence was preserved')
from run_original_boot_screen import audit as audit_boot
baseline_audit = workspace / 'run' / 'baseline-independent-audit'
baseline_result = audit_boot(baseline, baseline_audit)
if baseline_result.get('passed') is not True:
raise ValueError('Untouched stock baseline independent audit failed; private evidence was preserved')
touch_audit = workspace / 'run' / 'touch-independent-audit'
touch_capture_audit = audit_boot(pair / 'touch', touch_audit)
if touch_capture_audit.get('passed') is not True:
raise ValueError('Touch boot independent audit failed; private evidence was preserved')
model = render_post_screen_report(pair / 'touch', touch_audit, report_dir, paired)
print('Output:', workspace, flush=True)
print('Report:', report_dir / 'index.html', flush=True)
print('Nearest / final changed pixels:', model['touch_comparison']['different_pixels'],
'/', model['touch_comparison']['final_different_pixels'], flush=True)
if args.serve:
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *a, **kw):
super().__init__(*a, directory=str(report_dir), **kw)
server = http.server.ThreadingHTTPServer(('127.0.0.1', args.port), Handler)
try:
print(f'Open http://127.0.0.1:{args.port}/ (Ctrl-C to stop)', flush=True)
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
return 0
def run_imu_stock_report(workspace, profile_file):
"""Run both fresh original-boot lanes; retain every failed live capture."""
from imu_stock_scenario import execute, audit_pair
pair = workspace / 'run' / 'pair'
pair.mkdir(mode=0o700, parents=True)
input_result = execute(profile_file, workspace, pair / 'input', 'input')
if input_result.get('passed') is not True:
raise ValueError('Stock IMU input lane did not pass; first evidence was preserved')
control_result = execute(profile_file, workspace, pair / 'control', 'control')
if control_result.get('passed') is not True:
raise ValueError('Stock IMU control lane did not pass; pair evidence was preserved')
paired = audit_pair(pair / 'input' / 'capture', pair / 'control' / 'capture', pair / 'independent-audit',
workspace=workspace)
if paired.get('passed') is not True:
raise ValueError('Independent stock IMU paired audit failed; pair evidence was preserved')
report = workspace / 'run' / 'report'
report.mkdir(mode=0o700)
checks = paired['checks']
rows = ''.join('<tr><th>' + key.replace('_', ' ') + '</th><td>' + ('PASS' if value else 'FAIL') + '</td></tr>'
for key, value in checks.items())
evidence = paired['input']['evidence']
before, after = evidence['before'], evidence['after']
document = '''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; connect-src 'none'; object-src 'none">
<title>Stock IMU scenario</title><style>body{font:16px system-ui;max-width:850px;margin:3rem auto;padding:0 1rem;color:#17212b}table{border-collapse:collapse;width:100%}th,td{padding:.55rem;border-bottom:1px solid #ccd3da;text-align:left}th{text-transform:capitalize}.pass{color:#116b3a}.note{color:#4a5866}</style></head><body>
<h1>Stock IMU natural-consumption scenario</h1><p class="pass">Independent paired audit passed.</p>
<p>Fresh stock 2.4 bootloader reset through the first complete virtual screen. Natural gate and FIFO readiness were checked again before any IMU enqueue in both lanes. The input lane enqueued ten 32-byte packets. The control lane enqueued none. Both observed twenty 5 ms slices.</p>
<h2>Input lane evidence</h2><ul><li>Pre-input gate: ''' + str(before['gate']) + '''; FIFO ready: ''' + str(before['ready']) + '''; frame size: ''' + str(before['frame_bytes']) + ''' bytes; watermark: ''' + str(before['watermark']) + '''.</li>
<li>Pre-input ring header: ''' + ', '.join(map(str,before['ring'])) + '''.</li><li>FIFO consumed: ''' + str(after['consumed']-before['consumed']) + ''' packets; remaining: ''' + str(after['packets']) + '''; GPIO38 rising edges: ''' + str(after['gpio_edges']-before['gpio_edges']) + '''.</li>
<li>Virtual observation window: 100 ms; CPU and memory policy faults: 0; GPU rejections: ''' + str(after['gpu_rejections']) + '''.</li></ul>
<h2>Paired checks</h2><table><tbody>''' + rows + '''</tbody></table>
<p class="note">This is bounded virtual evidence for one stock 2.4 profile. It does not validate physical sensor timing, numerical sensor-fusion accuracy, or a physical device. Firmware and raw captures are retained privately alongside this report and are not embedded here.</p></body></html>'''
(report / 'index.html').write_text(document)
(report / 'paired-summary.json').write_text(json.dumps(dict(passed=True, execution_passed=paired['execution_passed'],
checks=checks, input_gate=before['gate'], input_ring=before['ring'],
input_consumed=after['consumed']-before['consumed'], control_consumed=paired['control']['evidence']['after']['consumed']-paired['control']['evidence']['before']['consumed'],
faults=0), indent=2) + '\n')
print('Output:', workspace, flush=True)
print('Report:', report / 'index.html', flush=True)
return 0
MAX_IMU_CAPTURE_FILE_BYTES = 64 * 1024 * 1024
MAX_IMU_CAPTURE_TOTAL_BYTES = 512 * 1024 * 1024
def _validate_imu_capture_tree(capture):
"""Reject links, special files, and unreasonable input sizes before auditing."""
capture = Path(capture)
root_stat = capture.lstat()
if stat.S_ISLNK(root_stat.st_mode) or not stat.S_ISDIR(root_stat.st_mode):
raise ValueError('Each IMU lane must contain a real capture directory')
total = 0
def walk_error(error):
raise ValueError('Could not inspect every IMU capture file safely') from error
for directory, dirnames, filenames in os.walk(capture, followlinks=False, >
base = Path(directory)
for name in dirnames:
child = base / name
mode = child.lstat().st_mode
if stat.S_ISLNK(mode) or not stat.S_ISDIR(mode):
raise ValueError('IMU captures cannot contain symlinks or special files')
for name in filenames:
child = base / name
metadata = child.lstat()
if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
raise ValueError('IMU captures can contain regular files only; symlinks and special files are rejected')
if metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES:
raise ValueError('IMU capture file exceeds the 64 MiB size limit')
total += metadata.st_size
return total
def _validate_imu_capture_reference(capture, name):
"""Ensure manifest-derived filenames stay inside a captured lane."""
relative = Path(name) if isinstance(name, str) else None
if (relative is None or not name or not relative.parts or relative.is_absolute()
or '..' in relative.parts):
raise ValueError('IMU capture manifest contains an unsafe relative file reference')
current = capture
for index, part in enumerate(relative.parts):
current = current / part
metadata = current.lstat()
if stat.S_ISLNK(metadata.st_mode):
raise ValueError('IMU capture manifest cannot reference symlinks')
if index < len(relative.parts) - 1:
if not stat.S_ISDIR(metadata.st_mode):
raise ValueError('IMU capture manifest reference has a non-directory parent')
elif not stat.S_ISREG(metadata.st_mode):
raise ValueError('IMU capture manifest must reference regular files')
elif metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES:
raise ValueError('IMU capture manifest references a file above the 64 MiB size limit')
def _validate_imu_manifest_references(capture, workspace):
"""Bound files opened through saved manifests to the private run workspace."""
import run_original_boot_screen as boot
try:
manifest = json.loads((capture / 'manifest.json').read_text())
boot.validate_profile(manifest['profile'])
assets = manifest['assets']
if not isinstance(assets, dict) or set(assets) != set(manifest['profile']['assets']):
raise ValueError('IMU manifest asset set differs from its reviewed profile')
for spec in assets.values():
raw_path = spec['path']
if not isinstance(raw_path, str):
raise ValueError('IMU manifest asset path must be text')
path = Path(raw_path).expanduser()
if (not path.is_absolute() or '..' in path.parts
or not path.is_relative_to(workspace)):
raise ValueError('IMU manifest assets must stay inside the private run workspace')
current = path
while current != workspace:
metadata = current.lstat()
if stat.S_ISLNK(metadata.st_mode):
raise ValueError('IMU manifest assets cannot traverse symlinks')
if current == path:
if not stat.S_ISREG(metadata.st_mode):
raise ValueError('IMU manifest assets must be regular files')
if metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES:
raise ValueError('IMU manifest asset exceeds the 64 MiB size limit')
elif not stat.S_ISDIR(metadata.st_mode):
raise ValueError('IMU manifest asset parent must be a real directory')
current = current.parent
components = manifest['components']
if not isinstance(components, dict) or set(components) != set(manifest['profile']['components']):
raise ValueError('IMU manifest component set differs from its reviewed profile')
for name in components:
_validate_imu_capture_reference(capture, name)
host_sources = manifest['host_sources']
expected_sources = {'runner-source.py', 'execute-source.py', 'process-source.py'}
if not isinstance(host_sources, dict) or set(host_sources) != expected_sources:
raise ValueError('IMU manifest host-source set is invalid')
for name in host_sources:
_validate_imu_capture_reference(capture, name)
artifact_manifest = capture / 'artifacts.json'
if artifact_manifest.exists():
artifacts = json.loads(artifact_manifest.read_text())
if not isinstance(artifacts, dict):
raise ValueError('IMU artifact manifest must be an object')
for name in artifacts:
_validate_imu_capture_reference(capture, name)
except (KeyError, TypeError, OSError, json.JSONDecodeError) as error:
raise ValueError('Could not validate all IMU manifest file references safely') from error
def audit_imu_stock_pair(pair, output):
"""Re-audit an existing private pair without launching the emulator."""
from imu_stock_scenario import audit_pair, private_report_workspace
supplied_pair = Path(pair).expanduser().absolute()
if supplied_pair.is_symlink():
raise ValueError('Pair directory cannot be a symlink')
pair = private_report_workspace(supplied_pair)
workspace = private_report_workspace(pair.parent.parent)
captures = (pair / 'input' / 'capture', pair / 'control' / 'capture')
total = 0
for lane, capture in zip(('input', 'control'), captures):
lane_dir = pair / lane
lane_mode = lane_dir.lstat().st_mode
if stat.S_ISLNK(lane_mode) or not stat.S_ISDIR(lane_mode):
raise ValueError('Each IMU lane must be a real directory')
if not capture.is_relative_to(pair):
raise ValueError('Both captures must be inside the pair directory')
total += _validate_imu_capture_tree(capture)
_validate_imu_manifest_references(capture, workspace)
if total > MAX_IMU_CAPTURE_TOTAL_BYTES:
raise ValueError('IMU pair exceeds the 512 MiB combined size limit')
supplied_output = Path(output).expanduser().absolute()
if supplied_output.is_symlink() or supplied_output.exists() or supplied_output.parent.resolve() != pair:
raise ValueError('Use a new output directory directly inside the pair directory')
result = audit_pair(captures[0], captures[1], supplied_output, workspace=pair)
if result.get('passed') is not True:
print('Stock IMU pair audit failed; the audit JSON was preserved.', file=sys.stderr)
return 1
print('Audit:', supplied_output / 'imu-paired-audit.json', flush=True)
return 0
def main(argv=None):
parser = argparse.ArgumentParser(prog='blackwall', description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('scenarios', help='List built-in scenarios')
environment = sub.add_parser('environment', help='Check Docker and a local container without firmware')
environment.add_argument('--renode-image', help='Optional full local sha256 image ID; non-default images are unreviewed')
assets = sub.add_parser('assets', help='Show required input hashes')
assets.add_argument('--source', type=Path, help='Source directory containing a pinned profile')
assets.add_argument('--profile', choices=['auto', 'imu', 'detailed', 'timed', 'stock'], default='auto')
faceclaw = sub.add_parser('faceclaw38', help='Run the reviewed Faceclaw 38 main-reset-to-frame profile')
faceclaw_input = faceclaw.add_mutually_exclusive_group(required=True)
faceclaw_input.add_argument('--main-image', type=Path, help='Pinned Faceclaw 38 main firmware image')
faceclaw_input.add_argument('--capture', type=Path, help='Audit a saved private Faceclaw 38 capture without rerunning')
faceclaw.add_argument('--output', type=Path, required=True, help='New private output directory outside the repository')
frame_report = sub.add_parser('frame-report', help='Render a retained frame scenario in the workbench dashboard')
frame_report.add_argument('--capture', type=Path, required=True, help='Private frame scenario output directory')
frame_report.add_argument('--output', type=Path, required=True, help='New private report directory')
post_report = sub.add_parser('post-screen-report', help='Audit a paired post-screen touch experiment and render its report')
post_report.add_argument('--pair', type=Path, required=True, help='Private paired experiment directory')
post_report.add_argument('--baseline', type=Path, required=True, help='Untouched private stock boot capture')
post_report.add_argument('--output', type=Path, required=True, help='New private report directory')
imu_audit = sub.add_parser('imu-stock-audit', help='Re-audit a saved private stock IMU pair without rerunning')
imu_audit.add_argument('--pair', type=Path, required=True, help='Existing private pair directory containing input/capture and control/capture')
imu_audit.add_argument('--output', type=Path, required=True, help='New private audit directory directly inside the pair')
init = sub.add_parser('setup', help='Import verified inputs into a new Docker volume')
init.add_argument('--source', type=Path, required=True, help='Directory containing pinned model and snapshot inputs')
init.add_argument('--profile', choices=['auto', 'imu', 'detailed', 'timed', 'stock'], default='auto')
init.add_argument('--boot-image', type=Path)
init.add_argument('--main-image', type=Path)
init.add_argument('--volume', default=DEFAULT_VOLUME)
doctor = sub.add_parser('doctor', help='Verify the Docker volume and pinned assets')
doctor.add_argument('--volume', default=DEFAULT_VOLUME)
doctor.add_argument('--boot-image', type=Path)
doctor.add_argument('--main-image', type=Path)
run = sub.add_parser('report', help='Run or audit a scenario and generate its HTML report')
run.add_argument('--volume', default=DEFAULT_VOLUME)
run.add_argument('--scenario', choices=SCENARIOS)
run.add_argument('--scenario-file', type=Path)
run.add_argument('--capture', type=Path)
run.add_argument('--boot-image', type=Path)
run.add_argument('--main-image', type=Path)
run.add_argument('--output', type=Path, help='New output directory outside the repository')
run.add_argument('--serve', action='store_true')
run.add_argument('--port', type=int, default=8765)
args = parser.parse_args(argv)
try:
if args.command == 'scenarios':
for name, description in SCENARIOS.items():
print(f'{name:22} {description}')
return 0
if args.command == 'environment':
from environment_diagnostics import diagnose
result = diagnose(args.renode_image)
print(json.dumps(result, indent=2))
return 0 if result['status'] == 'ready' else 1
if args.command == 'assets':
profile_file = select_profile(args.source or ROOT, args.profile)
if not profile_file:
raise ValueError('Selected profile is not available')
show_assets(json.loads(profile_file.read_text()))
return 0
if args.command == 'faceclaw38':
from faceclaw_main import audit_report, run as run_faceclaw
report_path = (audit_report(args.capture, args.output) if args.capture
else run_faceclaw(args.main_image, args.output))
print('Report:', report_path, flush=True)
return 0
if args.command == 'frame-report':
from frame_workbench import build
print('Report:', build(args.capture, args.output), flush=True)
return 0
if args.command == 'post-screen-report':
from post_screen_report import generate
model = generate(args.pair, args.baseline, args.output)
print('Report:', args.output / 'index.html', flush=True)
print('Nearest / final changed pixels:', model['touch_comparison']['different_pixels'],
'/', model['touch_comparison']['final_different_pixels'], flush=True)
return 0
if args.command == 'imu-stock-audit':
return audit_imu_stock_pair(args.pair, args.output)
volume_name(args.volume)
if args.command == 'setup':
return setup(args)
if args.command == 'doctor':
return inspect_volume(args)
return report(args)
except (ValueError, OSError, RuntimeError, subprocess.SubprocessError) as exc:
33A4
print('Blackwall:', exc, file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())