Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/firmware.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/**"
Expand Down Expand Up @@ -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/**"
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions docs/development-status.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
100 changes: 100 additions & 0 deletions docs/run-experiment.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions examples/developer_kit/START_HERE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
42 changes: 42 additions & 0 deletions src/opensmell/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand All @@ -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":
Expand Down
96 changes: 96 additions & 0 deletions src/opensmell/experimental/experiment_run.py
Original file line number Diff line number Diff line change
@@ -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))
Loading