From 9d85f50ef6a59f3467f34bc45d947cb892b569bb Mon Sep 17 00:00:00 2001 From: YAAASSS <43731142+YAAASSS@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:07:50 +0100 Subject: [PATCH] Run verified prepared experiment dossiers through the installed SDK and CLI --- .github/workflows/firmware.yml | 6 ++ README.md | 4 + docs/development-status.md | 15 +++ docs/run-experiment.md | 100 +++++++++++++++++++ examples/developer_kit/START_HERE.md | 2 + src/opensmell/cli.py | 42 ++++++++ src/opensmell/experimental/experiment_run.py | 96 ++++++++++++++++++ tests/test_experiment_run.py | 96 ++++++++++++++++++ tools/build_developer_kit.py | 1 + tools/verify_installed_experiment_run.py | 88 ++++++++++++++++ 10 files changed, 450 insertions(+) create mode 100644 docs/run-experiment.md create mode 100644 src/opensmell/experimental/experiment_run.py create mode 100644 tests/test_experiment_run.py create mode 100644 tools/verify_installed_experiment_run.py diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index 4f63d2f..a1b6c01 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -23,6 +23,7 @@ on: - "tools/verify_installed_firmware_lifecycle.py" - "tools/verify_installed_sequence.py" - "tools/verify_installed_serial_sequence.py" + - "tools/verify_installed_experiment_run.py" - "tools/verify_installed_core_plan.py" - "examples/sequence/**" - "examples/firmware_lifecycle/**" @@ -52,6 +53,7 @@ on: - "tools/verify_installed_firmware_lifecycle.py" - "tools/verify_installed_sequence.py" - "tools/verify_installed_serial_sequence.py" + - "tools/verify_installed_experiment_run.py" - "tools/verify_installed_core_plan.py" - "examples/sequence/**" - "examples/firmware_lifecycle/**" @@ -129,6 +131,10 @@ jobs: if: runner.os == 'Linux' run: python -m tools.verify_installed_serial_sequence dist/opensmell-0.1.0-py3-none-any.whl --host /tmp/opensmell-lifecycle-host --dry-host /tmp/opensmell-dry-load-host --output dist/lifecycle-proof/serial-sequence + - name: Verify installed relocated experiment dossier on native software + if: runner.os == 'Linux' + run: python -m tools.verify_installed_experiment_run dist/opensmell-0.1.0-py3-none-any.whl --host /tmp/opensmell-lifecycle-host --output dist/lifecycle-proof/experiment-run + - name: Verify installed selected Core plans against actual native sketch if: runner.os == 'Linux' run: python -m tools.verify_installed_core_plan dist/opensmell-0.1.0-py3-none-any.whl --host /tmp/opensmell-lifecycle-host --evidence-directory dist/lifecycle-proof/core-plan diff --git a/README.md b/README.md index 70cd95f..804d81a 100644 --- a/README.md +++ b/README.md @@ -1646,6 +1646,10 @@ The active direction covers the installed SDK/CLI, interoperable data, reusable adapters and a reproducible ESP32 bench. Local Explorer remains a demo client. See [the deliverables and exit criteria](docs/development-status.md#active-direction--developer-kit-and-concrete-prototype-2026-11-10). +The installed [`run-experiment` entry](docs/run-experiment.md) consumes one verified +prepared dossier in caller order, with explicit software transport selection and +retained trial IDs/receipts. It also exposes a transport-neutral SDK entry. + The [transport-neutral sequence SDK](docs/transport-sequences.md) runs explicit offline plans with a caller-owned transport factory. Its installed manual serial entry reuses the same bounded lifecycle runner; software/owned-PTY proofs are diff --git a/docs/development-status.md b/docs/development-status.md index 74d8046..b25b070 100644 --- a/docs/development-status.md +++ b/docs/development-status.md @@ -5,6 +5,21 @@ The broader roadmap remains in the [README](../README.md#roadmap). Operational checkpoints and the short session log live in `state.json` on the `automation/control` branch; follow its pending PR before starting new work. +## Prepared dossier execution — 2026-11-24 evening + +The reusable sequence core/manual serial slice (#44/#45) is closed. The next +usable SDK/data entry is [run-experiment](run-experiment.md): one explicitly +selected prepared dossier, fully checked before a separately selected transport. +No hand enumeration of plan files, implicit port/executable or new wire contract. + +Exit: installed CLI outside checkout consumes a relocated dossier after originals +are removed; distinct caller trials and opaque annotations retained; completion, +Stop, second refusal/unknown preserve earlier receipts and halt later sends; +hash-consistent corrupted last trial and output collision cause no process traffic. +Close this first dossier path after CI. Next prioritize a concrete independent +integration/analysis need over scheduler/retry/catalog extensions. Physical board +measurements and independent adoption stay unobserved gates. + ## Reusable transport sequences — 2026-11-24 The first Windows kit path (#43) is delivered. The next SDK integration gap is diff --git a/docs/run-experiment.md b/docs/run-experiment.md new file mode 100644 index 0000000..26bef20 --- /dev/null +++ b/docs/run-experiment.md @@ -0,0 +1,100 @@ +# Run a prepared experiment (experimental) + +`opensmell prepare-experiment` produces a passive portable dossier. The installed +`run-experiment` entry verifies that whole dossier, then runs its caller-ordered +trials on separately selected trusted software. It does not discover hardware, +select commands from data, randomize trials or establish scientific validity. + +After installation, prepare a dossier using your explicit CSV/graph/profile: + +```sh +opensmell prepare-experiment caller.csv --graph caller.osmell \ + --profile profile.json --output-directory experiment +``` + +Move `experiment` anywhere; original caller files are no longer required. Keep +all retained files together. Explicitly choose the installed software simulator +(replace `python` with your installed environment's Python executable): + +```sh +opensmell run-experiment experiment \ + --software-command-json '["python","-m","opensmell","simulate-device"]' \ + --expected-device-id opensmell-local-simulator-001 \ + --action complete --output new-experiment-report.json +``` + +The supplied profile must match this endpoint's capabilities. The command is a +trusted executable/argument array, not sandboxed; arguments appear in the report. +Use `--action stop-first` and a new output to request cooperative Stop after first +acceptance. A short execution can finish before Stop; its actual terminal state +is preserved. Nothing runs when a dossier is imported or prepared. + +## SDK and evidence + +```python +from opensmell.experimental.experiment_run import run_prepared_experiment +report = run_prepared_experiment( + "experiment", make_owned_transport, + expected_device_id="explicit-device-id", + on_progress=save_checkpoint, + stop_requested=stop_event.is_set, +) +``` + +The trusted lazy factory returns `exchange(str)->str` / `close()`. It is never +selected from manifest contents. The SDK owns the resulting transport; reuse and +[sequence bounds/Stop/uncertainty rules](transport-sequences.md) still apply. +Invalid dossiers raise before invoking the factory. All bytes are read once and +retained before connection; subsequent file changes cannot alter a running trial. + +The loader checks the bounded inventory, exact hashes and byte counts, then +recomputes preparation from retained CSV/source/profile with the normal compiler. +It compares caller order, trial IDs/records, request, mapping, plan and provenance, +including trial/table bindings. Recomputed hashes alone cannot make an inconsistent +plan actionable. Filenames come from recomputation; symlinked files, arbitrary +inventory paths and incomplete dossiers refuse. Current preparation version 0.1 +is supported; artifacts incompatible with the installed compiler refuse rather +than being silently migrated. Recomputing uses disposable local temporary files. + +Extra passive manifest and top-level plan fields survive exact snapshots. Source +and profile unknown data remain preserved and subject to ordinary planning rules; +unknown data never configures execution. This is consistency checking, not source +or device authentication. Hand-edited required fields/records must be prepared +again through the normal entry. + +`prepared_experiment` in each progress/final report retains exact manifest, CSV, +source and profile snapshots and explicit trial order. Each sequence step includes +its caller `trial_id`, separate from session execution/request identifiers. Original +plan snapshots and earlier receipts remain after Stop, refusal or unknown. Later +steps are not attempted. No retry, reconciliation or automatic restart is offered. + +The CLI exclusively creates its report before connection and flushes checkpoints; +invalid dossiers can leave a new empty output. Existing output is never replaced. +The SDK is memory-only without a persistence callback. Flush/callback success does +not guarantee fsync/crash durability. Callback/storage failure closes the transport +and must be treated as potentially uncertain; closing is not emergency Stop. +CLI exit: 0 completed/requested Stop; 3 invalid live configuration/refusal; +1 other incomplete/uncertain result or invalid dossier; 2 filesystem/launch error. +No physical execution or measured odor follows from a software receipt. + +## Reproduce the software proof + +From a checkout with development dependencies and committed ArduinoJson headers +available locally, compile the real lifecycle sketch for the host, build a wheel, +then exercise the installed entry outside the checkout: + +```sh +python -m tools.build_esp32_host --lifecycle --arduinojson /explicit/ArduinoJson --output /tmp/lifecycle-host +python -m build --wheel +python -m tools.verify_installed_experiment_run dist/opensmell-0.1.0-py3-none-any.whl \ + --host /tmp/lifecycle-host --output /tmp/new-experiment-proof +``` + +The proof creates a fresh venv with inherited build dependencies (not clean offline +closure), prepares three distinct-duration caller trials, relocates the dossier, +removes originals and runs completion, Stop, second reply loss and an explicitly +injected software refusal. Receipts retain trial order and bytes; output collision +and hash-consistent trial corruption refuse without new process traffic. The +fault wrapper is explicitly selected by the verifier, never by dossier data. +Actual native sketch software is used; ESP32 electrical/serial/odor observations +and independent third-party adoption remain unobserved. diff --git a/examples/developer_kit/START_HERE.md b/examples/developer_kit/START_HERE.md index b6e61fb..a09bda0 100644 --- a/examples/developer_kit/START_HERE.md +++ b/examples/developer_kit/START_HERE.md @@ -199,3 +199,5 @@ For a reusable lazy transport factory and the installed explicit human serial sequence entry, see [TRANSPORT_SEQUENCES.md](TRANSPORT_SEQUENCES.md). The source recipe never authorizes autonomous physical commands; verification uses owned pseudo-terminals only. Existing software sequence commands remain unchanged. + +For a whole caller-ordered prepared dossier, see [RUN_EXPERIMENT.md](RUN_EXPERIMENT.md). diff --git a/src/opensmell/cli.py b/src/opensmell/cli.py index c6f0421..c697440 100644 --- a/src/opensmell/cli.py +++ b/src/opensmell/cli.py @@ -227,6 +227,40 @@ def _prepare_experiment_command(args): print(json.dumps({"status":"invalid","error":str(error)})); return 1 +def _run_experiment_command(args): + from .experimental.experiment_run import run_prepared_experiment + from .experimental.process_transport import ProcessTransport + import csv + try: + command = _decode(args.software_command_json.encode()) + if (not isinstance(command, list) or not 1 <= len(command) <= 64 + or any(not isinstance(arg, str) or "\0" in arg for arg in command) + or not command[0].strip() or sum(map(len, command)) > 16384): + raise ValueError("Explicit executable/argument array required (max64 items/16KiB)") + stop = [False] + with Path(args.output).open("x", encoding="utf-8") as output: + def save(report): + output.seek(0); output.truncate() + json.dump(report, output, allow_nan=False, indent=2) + output.write("\n"); output.flush() + if args.action == "stop-first" and report.get("sequence"): + if any(s["state"] == "accepted" for s in report["sequence"]["steps"]): + stop[0] = True + report = run_prepared_experiment(args.directory, + lambda: ProcessTransport(command, startup_timeout=5), + expected_device_id=args.expected_device_id, + transport_context={"command":command}, on_progress=save, + stop_requested=lambda: stop[0]) + print(json.dumps(report, allow_nan=False)) + return (0 if report["status"] == "completed" or + (args.action == "stop-first" and report["status"] == "stopped") else + 3 if report["status"] in {"invalid", "rejected", "incompatible"} else 1) + except OSError as error: + print(json.dumps({"status":"error","error":str(error)}), file=sys.stderr); return 2 + except (OpenSmellError, ValueError, TypeError, KeyError, RecursionError, OverflowError, csv.Error) as error: + print(json.dumps({"status":"invalid","error":str(error)}), file=sys.stderr); return 1 + + def _sequence_command(args): from .experimental.software_sequence import run_software_sequence, MAX_BYTES try: @@ -585,6 +619,12 @@ def main(argv: list[str] | None = None) -> int: experiment.add_argument("--graph", required=True, help="Explicit source ResourceGraph") experiment.add_argument("--profile", required=True, help="Explicit mapping/capability profile for every trial") experiment.add_argument("--output-directory", required=True, help="New portable experiment directory; never overwrite") + run_experiment = commands.add_parser("run-experiment", help="Verify and run one prepared experiment on explicitly selected trusted software") + run_experiment.add_argument("directory", help="Explicit prepared-experiment directory; never selects transport") + run_experiment.add_argument("--software-command-json", required=True, help="Trusted executable/argument JSON array; no shell; not sandboxed") + run_experiment.add_argument("--expected-device-id", required=True) + run_experiment.add_argument("--action", choices=("complete", "stop-first"), required=True) + run_experiment.add_argument("--output", required=True, help="New checkpoint report; never overwrite; flush is not crash durability") sequence = commands.add_parser("run-sequence", help="Run explicit offline plans in order on trusted software; no hardware") sequence.add_argument("files", nargs="+", help="1–16 explicit offline-plan JSON files in execution order; no stdin") sequence.add_argument("--software-command-json", required=True, help="Trusted executable/argument JSON array; no shell; arguments retained") @@ -606,6 +646,8 @@ def main(argv: list[str] | None = None) -> int: return _plan_core_command(args) if args.command == "prepare-experiment": return _prepare_experiment_command(args) + if args.command == "run-experiment": + return _run_experiment_command(args) if args.command == "run-sequence": return _sequence_command(args) if args.command == "reference-graph": diff --git a/src/opensmell/experimental/experiment_run.py b/src/opensmell/experimental/experiment_run.py new file mode 100644 index 0000000..6e43237 --- /dev/null +++ b/src/opensmell/experimental/experiment_run.py @@ -0,0 +1,96 @@ +"""Verified passive experiment dossier to an explicitly chosen lifecycle transport.""" +from copy import deepcopy +import hashlib +from pathlib import Path +import tempfile + +from .._json import decode_bytes +from .experiment import prepare_experiment +from .frame_export import _snapshot +from .transport_sequence import prepare_steps, run_transport_sequence + + +def load_prepared_experiment(directory): + """Read once, verify hashes and recompute all trial bindings before any IO. + + Only fixed preparation filenames are read. Extra passive manifest/plan keys + survive in exact snapshots; they never choose a transport or executable. + Hashes establish consistency, not authenticity or scientific validity. + """ + root = Path(directory).resolve(strict=True) + def read(name, bound): + path = root / name + if path.is_symlink() or not path.is_file(): + raise ValueError("Expected regular retained file: " + name) + with path.open('rb') as source: + raw = source.read(bound + 1) + if len(raw) > bound: + raise ValueError("Retained file exceeds bound: " + name) + return raw + manifest_raw = read('experiment.json', 1048576) + manifest = decode_bytes(manifest_raw) + if not isinstance(manifest, dict): + raise ValueError('Experiment manifest must be an object') + raw = {name: read(name, bound) for name, bound in + [('trials.csv', 65536), ('source.osmell', 8*1048576), ('profile.json', 1048576)]} + # Reuse the normal compiler so loader and preparation have one mapping rule. + with tempfile.TemporaryDirectory(prefix='opensmell-experiment-check-') as tmp: + target = Path(tmp) / 'recomputed' + expected = prepare_experiment(raw['trials.csv'], raw['source.osmell'], raw['profile.json'], target) + for key in ('format', 'version', 'status', 'experimental', 'execution', + 'physical_validation', 'total_requested_duration', 'trials'): + if manifest.get(key) != expected[key]: + raise ValueError('Prepared experiment binding mismatch: ' + key) + files = manifest.get('files') + if not isinstance(files, dict) or set(files) != set(expected['files']): + raise ValueError('Unexpected retained file inventory') + plans = [] + for row in expected['trials']: + name = row['plan_file'] # generated fixed filename, never untrusted path + value = read(name, 8*1048576) + plans.append(value) + if sum(map(len, plans)) > 16*1048576: + raise ValueError('Combined plans exceed 16 MiB') + actual_plan, expected_plan = decode_bytes(value), decode_bytes((target/name).read_bytes()) + if not isinstance(actual_plan, dict): + raise ValueError('Trial plan must be an object') + for key in expected_plan: + if actual_plan.get(key) != expected_plan[key]: + raise ValueError('Trial plan binding mismatch: ' + name + '/' + key) + raw[name] = value + for name, value in raw.items(): + entry = files[name] + if (not isinstance(entry, dict) or entry.get('sha256') != hashlib.sha256(value).hexdigest() + or entry.get('byte_count') != len(value)): + raise ValueError('Retained file digest/size mismatch: ' + name) + prepare_steps(plans) + context = {'manifest': _snapshot(manifest_raw), + 'retained_inputs': {name: _snapshot(raw[name]) for name in + ('trials.csv', 'source.osmell', 'profile.json')}, + 'trial_order': deepcopy(expected['trials'])} + return plans, context + + +def run_prepared_experiment(directory, transport_factory, *, expected_device_id, + transport_context=None, on_progress=None, stop_requested=None): + """Verify a selected dossier, then own the separately selected lazy transport. + + Invalid dossiers raise before transport creation. Progress storage is caller + supplied, cooperative Stop and uncertain outcomes follow the sequence SDK. + Returned/callback reports retain exact manifest, inputs and per-step plans. + """ + plans, context = load_prepared_experiment(directory) + def enrich(report): + report['prepared_experiment'] = deepcopy(context) + if report.get('sequence'): + for step, trial in zip(report['sequence']['steps'], context['trial_order']): + step['trial_id'] = trial['trial_id'] + return report + def progress(report): + if on_progress is not None: + on_progress(enrich(report)) + if on_progress is not None and not callable(on_progress): + raise TypeError('on_progress must be callable') + return enrich(run_transport_sequence(plans, transport_factory, + expected_device_id=expected_device_id, transport_context=transport_context, + on_progress=progress, stop_requested=stop_requested)) diff --git a/tests/test_experiment_run.py b/tests/test_experiment_run.py new file mode 100644 index 0000000..12e7d05 --- /dev/null +++ b/tests/test_experiment_run.py @@ -0,0 +1,96 @@ +"""Dossier consistency before any connection and reusable SDK lifecycle behavior.""" +import base64 +import hashlib +import json +import shutil +import subprocess +import sys + +import pytest +from opensmell.experimental.experiment import prepare_experiment +from opensmell.experimental.experiment_run import load_prepared_experiment, run_prepared_experiment +from test_experiment import TABLE, GRAPH, PROFILE +from test_transport_sequence import Transport, ID + +@pytest.fixture +def dossier(tmp_path): + original=tmp_path/'original' + prepare_experiment(TABLE, GRAPH, PROFILE, original) + moved=tmp_path/'moved space';shutil.move(original,moved) + return moved + + +def test_order_snapshots_unknown_and_no_reread_after_factory(dossier): + manifest=json.loads((dossier/'experiment.json').read_bytes()) + manifest['future']={'opaque':[2**70,None]} + raw=json.dumps(manifest).encode();(dossier/'experiment.json').write_bytes(raw) + transport=Transport() + def factory(): + shutil.rmtree(dossier) + return transport + r=run_prepared_experiment(dossier,factory,expected_device_id=ID) + assert r['status']=='completed' and transport.closed==1 + assert [s['trial_id'] for s in r['sequence']['steps']]==['first','second'] + assert base64.b64decode(r['prepared_experiment']['manifest']['data'])==raw + assert base64.b64decode(r['prepared_experiment']['retained_inputs']['trials.csv']['data'])==TABLE + assert [q['duration'] for q in transport.requests if q['type']=='render']==[.1,.2] + + +@pytest.mark.parametrize('bad',['hash','table','order','id','path','inventory','missing','symlink','plan_binding','manifest_type','plan_type']) +def test_invalid_dossier_never_calls_factory(dossier,bad): + manifest=json.loads((dossier/'experiment.json').read_bytes()) + if bad=='hash':manifest['files']['plan-002.json']['sha256']='0'*64 + if bad=='table':(dossier/'trials.csv').write_bytes(TABLE.replace(b'caller-design',b'changed')) + if bad=='order':manifest['trials'].reverse() + if bad=='id':manifest['trials'][1]['trial_id']='first' + if bad=='path':manifest['trials'][1]['plan_file']='../outside' + if bad=='inventory':manifest['files']['../outside']={} + if bad=='missing':(dossier/'plan-002.json').unlink() + if bad=='symlink': + p=dossier/'plan-002.json';value=p.read_bytes();p.unlink();other=dossier.parent/'outside';other.write_bytes(value);p.symlink_to(other) + if bad in {'plan_binding','plan_type'}: + p=dossier/'plan-002.json';obj=json.loads(p.read_bytes()) + if bad=='plan_binding':obj['org.opensmell.experimental.trial']['record']['note']='edited' + else:obj=[] + value=json.dumps(obj).encode();p.write_bytes(value) + manifest['files'][p.name]={'sha256':hashlib.sha256(value).hexdigest(),'byte_count':len(value)} + if bad=='manifest_type':manifest=[] + (dossier/'experiment.json').write_text(json.dumps(manifest)) + opened=[] + with pytest.raises((ValueError,OSError)): + run_prepared_experiment(dossier,lambda:opened.append(True),expected_device_id=ID) + assert opened==[] + + +@pytest.mark.parametrize('mode,state',[('lost','unknown'),('refused','rejected')]) +def test_second_failure_preserves_trial_receipts_and_halts(tmp_path,mode,state): + table=TABLE+TABLE.splitlines()[-1].replace(b'second,',b'third,')+b'\n' + dossier=tmp_path/'d';prepare_experiment(table,GRAPH,PROFILE,dossier) + t=Transport(mode);r=run_prepared_experiment(dossier,lambda:t,expected_device_id=ID) + assert [s['state'] for s in r['sequence']['steps']]==['completed',state,'not_attempted'] + assert [s['trial_id'] for s in r['sequence']['steps']]==['first','second','third'] + assert t.renders==2 and t.closed==1 + + +def test_stop_and_callback_failure_close(dossier): + t=Transport();stop=[False] + def progress(r): + if r['sequence'] and any(s['state']=='accepted' for s in r['sequence']['steps']):stop[0]=True + r=run_prepared_experiment(dossier,lambda:t,expected_device_id=ID,on_progress=progress,stop_requested=lambda:stop[0]) + assert r['status']=='stopped' and t.renders==1 and t.closed==1 + t=Transport() + def broken(r): + if any(json.loads(e['request_line'])['type']=='render' for e in r['transcript']):raise OSError('storage failed') + with pytest.raises(OSError):run_prepared_experiment(dossier,lambda:t,expected_device_id=ID,on_progress=broken) + assert t.closed==1 and t.renders==0 + + +def test_normal_cli_and_collision_before_launch(dossier,tmp_path): + out=tmp_path/'report.json' + cmd=[sys.executable,'-m','opensmell','run-experiment',str(dossier),'--software-command-json',json.dumps([sys.executable,'-m','opensmell','simulate-device']), + '--expected-device-id',ID,'--action','complete','--output',str(out)] + r=subprocess.run(cmd,capture_output=True);assert r.returncode==0,r.stderr + assert json.loads(out.read_bytes())['status']=='completed' + before=out.read_bytes();cmd[cmd.index('--software-command-json')+1]='["definitely-missing-executable"]' + r=subprocess.run(cmd,capture_output=True);assert r.returncode==2 + assert out.read_bytes()==before diff --git a/tools/build_developer_kit.py b/tools/build_developer_kit.py index 1e44fd1..2e6d982 100644 --- a/tools/build_developer_kit.py +++ b/tools/build_developer_kit.py @@ -21,6 +21,7 @@ ROOT = Path(__file__).resolve().parents[1] # Explicit allowlist; external datasets, caches and arbitrary checkout files are excluded. PAYLOADS = { + "RUN_EXPERIMENT.md": "docs/run-experiment.md", "TRANSPORT_SEQUENCES.md": "docs/transport-sequences.md", "WHEEL_STARTER.md": "docs/wheel-starter.md", "CORE_PLANNING.md": "docs/core-planning.md", diff --git a/tools/verify_installed_experiment_run.py b/tools/verify_installed_experiment_run.py new file mode 100644 index 0000000..e75af1b --- /dev/null +++ b/tools/verify_installed_experiment_run.py @@ -0,0 +1,88 @@ +"""Installed relocated dossier -> CLI -> actual native lifecycle sketch. Software only.""" +import argparse +import base64 +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import venv + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('wheel',type=Path);p.add_argument('--host',required=True,type=Path) + p.add_argument('--output',required=True,type=Path) + a=p.parse_args();wheel=a.wheel.resolve(strict=True);host=a.host.resolve(strict=True) + output=a.output.resolve();output.mkdir(parents=True,exist_ok=False) + root=Path(__file__).resolve().parents[1] + proof={'result':'incomplete','physical_validation':False,'cases':[]} + def save():(output/'result.json').write_text(json.dumps(proof,indent=2)+'\n') + save() + with tempfile.TemporaryDirectory(prefix='opensmell-installed-experiment-') as tmp: + work=Path(tmp);venv.EnvBuilder(with_pip=True,system_site_packages=True).create(work/'venv') + python=work/'venv/bin/python';env={k:v for k,v in os.environ.items() if k not in {'PYTHONHOME','PYTHONPATH'}} + def run(args,code=0): + r=subprocess.run(list(map(str,args)),cwd=work,env=env,capture_output=True,timeout=60) + assert r.returncode==code,(args,r.returncode,r.stdout[-1500:],r.stderr[-1500:]) + return r.stdout + run([python,'-m','pip','install','--no-index','--no-deps','--ignore-installed',wheel]) + location=run([python,'-I','-c','import opensmell;print(opensmell.__file__)']).decode().strip() + assert Path(location).is_relative_to(work/'venv') + proof['installed_outside_checkout']=True + proof['dependency_scope']='Installed wheel with inherited build dependencies, not clean offline closure' + graph=work/'caller.osmell';profile=work/'caller-profile.json';table=work/'caller.csv' + graph.write_bytes((root/'examples/multisource_diphenyl_ether.osmell').read_bytes()) + profile.write_bytes((root/'examples/offline_perceptual_profile.json').read_bytes()) + table.write_text('trial_id,resource_id,duration,condition\n'+''.join( + f'{name},219ef28c-9b58-52f2-93a7-0807f5897857,{duration},{note}\n' + for name,duration,note in [('first',1,'opaque-A'),('second',.1,'opaque-B'),('third',.2,'opaque-C')])) + run([python,'-I','-m','opensmell','prepare-experiment',table,'--graph',graph,'--profile',profile,'--output-directory',work/'original']) + moved=work/'relocated dossier';shutil.move(work/'original',moved) + for path in (graph,profile,table):path.unlink() + manifest=(moved/'experiment.json').read_bytes() + # Explicit trusted verifier wrapper injects faults; never selected from dossier. + wrapper=work/'fault-wrapper.py' + wrapper.write_text('''import json,os,sys +from opensmell.experimental.process_transport import ProcessTransport +t=ProcessTransport([sys.argv[1],"--realtime"],startup_timeout=5) +mode=sys.argv[2];count=0 +try: + for line in sys.stdin: + req=json.loads(line) + with open(sys.argv[3],'a') as log:log.write(json.dumps(req)+'\\n') + if req['type']=='render':count+=1 + if count==2 and req['type']=='render' and mode=='refused': + reply=json.dumps({'protocol_version':'0.1','type':'error','code':'busy','message':'Verifier injected refusal before native forwarding'}) + else:reply=t.exchange(line.rstrip('\\n')) + if count==2 and req['type']=='render' and mode=='lost':break + print(reply.rstrip("\\r\\n"),flush=True) +finally:t.close() +''') + for mode,action,code,states in [('normal','complete',0,['completed']*3),('normal','stop-first',0,['stopped','not_attempted','not_attempted']),('lost','complete',1,['completed','unknown','not_attempted']),('refused','complete',3,['completed','rejected','not_attempted'])]: + name=mode+'-'+action;log=output/(name+'-requests.jsonl');report=output/(name+'.json') + cmd=[python,'-I','-m','opensmell','run-experiment',moved,'--software-command-json',json.dumps([str(python),'-I',str(wrapper),str(host),mode,str(log)]),'--expected-device-id','opensmell-esp32-lifecycle-led-001','--action',action,'--output',report] + result=json.loads(run(cmd,code));steps=result['sequence']['steps'] + assert [s['state'] for s in steps]==states,result + assert [s['trial_id'] for s in steps]==['first','second','third'] + assert base64.b64decode(result['prepared_experiment']['manifest']['data'])==manifest + for step in steps: + raw=base64.b64decode(step['context']['input']['data']);obj=json.loads(raw) + assert obj['org.opensmell.experimental.trial']['record']['trial_id']==step['trial_id'] + before=report.read_bytes();traffic=log.read_bytes();run(cmd,2) + assert report.read_bytes()==before and log.read_bytes()==traffic + proof['cases'].append({'name':name,'states':states,'collision_no_traffic':True});save() + # Hash-consistent corrupted trial binding still refuses before process launch. + bad=json.loads((moved/'plan-003.json').read_bytes());bad['org.opensmell.experimental.trial']['record']['condition']='tampered' + raw=json.dumps(bad).encode();(moved/'plan-003.json').write_bytes(raw) + import hashlib + m=json.loads(manifest);m['files']['plan-003.json']={'sha256':hashlib.sha256(raw).hexdigest(),'byte_count':len(raw)} + (moved/'experiment.json').write_text(json.dumps(m)) + log=output/'invalid-requests.jsonl' + run([python,'-I','-m','opensmell','run-experiment',moved,'--software-command-json',json.dumps([str(python),'-I',str(wrapper),str(host),'normal',str(log)]),'--expected-device-id','opensmell-esp32-lifecycle-led-001','--action','complete','--output',output/'invalid.json'],1) + assert not log.exists() + proof['tampered_binding_no_process']=True;proof['result']='passed';save() + print(json.dumps(proof,indent=2)) + +if __name__=='__main__':main()