diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index a1b6c01..142092d 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -25,6 +25,8 @@ on: - "tools/verify_installed_serial_sequence.py" - "tools/verify_installed_experiment_run.py" - "tools/verify_installed_core_plan.py" + - "tools/verify_installed_core_perceptual.py" + - "examples/core_perceptual_only.osmell" - "examples/sequence/**" - "examples/firmware_lifecycle/**" - "examples/lifecycle_client/**" @@ -55,6 +57,8 @@ on: - "tools/verify_installed_serial_sequence.py" - "tools/verify_installed_experiment_run.py" - "tools/verify_installed_core_plan.py" + - "tools/verify_installed_core_perceptual.py" + - "examples/core_perceptual_only.osmell" - "examples/sequence/**" - "examples/firmware_lifecycle/**" - "examples/lifecycle_client/**" @@ -137,7 +141,9 @@ jobs: - 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 + 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 + python -m tools.verify_installed_core_perceptual dist/opensmell-0.1.0-py3-none-any.whl --host /tmp/opensmell-lifecycle-host --output dist/lifecycle-proof/core-plan/perceptual - name: Verify installed serial bench over owned pseudo-terminals if: runner.os == 'Linux' diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 83cc268..a2fbfeb 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -77,7 +77,9 @@ jobs: python -m tools.verify_installed_cli dist/*.whl --js-exchange-directory "$RUNNER_TEMP/js-sdk-exchange" - name: Verify installed explicit Core planning path - run: python -m tools.verify_installed_core_plan dist/opensmell-0.1.0-py3-none-any.whl --evidence-directory dist/core-plan-proof + run: | + python -m tools.verify_installed_core_plan dist/opensmell-0.1.0-py3-none-any.whl --evidence-directory dist/core-plan-proof + python -m tools.verify_installed_core_perceptual dist/opensmell-0.1.0-py3-none-any.whl --output dist/core-plan-proof/perceptual - name: Retain Core planning evidence if: always() diff --git a/README.md b/README.md index 5d01e03..a13ea34 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 [`plan-core` quantitative path](docs/core-perceptual-planning.md) +selects one perceptual representation under an explicit unit/scale/normalization +policy, preserving exact Core bytes without inventing a measured observation. + The installed [`analyze-experiment` entry](docs/trial-analysis.md) joins explicit caller observation IDs to trial receipts and exports loss-preserving JSON/CSV for external analysis. Execution completion never creates a measurement. diff --git a/docs/core-perceptual-planning.md b/docs/core-perceptual-planning.md new file mode 100644 index 0000000..412bedd --- /dev/null +++ b/docs/core-perceptual-planning.md @@ -0,0 +1,114 @@ +# Explicit Core perceptual planning (experimental) + +`plan-core` can now select one quantitative perceptual representation without a +chemical structure. Existing semantic selection remains compatible. This opt-in +application path interprets provisional `org.opensmell.perceptual.measurements` +0.1 from Draft RFC-0005; it does not promote the scheme or change Core0.1, +Generic ResourceGraph, Device Protocol or RFC maturity. No transport opens. + +## Installed normal entry + +With this revision installed, or its locally built wheel: + +```sh +opensmell plan-core examples/core_perceptual_only.osmell --representation-index 0 \ + --profile examples/offline_core_perceptual_profile.json --duration 0.1 --output first.json +opensmell plan-core examples/core_perceptual_only.osmell --representation-index 1 \ + --profile examples/offline_core_perceptual_profile.json --duration 0.1 --output second.json +opensmell encode-frame first.json --capabilities hardware/esp32/led_capabilities.json \ + --output first-frame.json +``` + +Use your own file/profile paths outside the checkout; Core stdin `-` works. +The included source is **declared synthetic** and has no chemical representation. +Index0 produces CH0=.25,CH1=.5,CH2=1 under the explicit profile; index1 changes +CH0 to .75. The third opaque representation cannot be selected as a fallback. +All output files are new/exclusive. Exit0 planned,1 refused/invalid,2 filesystem +error. An offline plan/frame is data, not acceptance, execution or measured odor. + +## Explicit policy, not inferred units or calibration + +The profile still has `mapper:perceptual`, ordinary property/channel `bindings` +and supplied `capabilities`. This Core path additionally requires the recognized +application extension `org.opensmell.experimental.core-perceptual-policy`: + +```json +{ + "version": "0.1", + "normalization": "value-minus-min-over-range", + "measurements": [ + {"property": "flower", "scale": {"min": 0, "max": 10}, "unit": "rating"}, + {"property": "grass", "scale": {"min": -1, "max": 1}, "unit": null}, + {"property": "wood", "scale": {"min": 0, "max": 100}} + ] +} +``` + +This is the application author's explicit choice of the existing demonstration +formula `(value-min)/(max-min)`, not an automatic normalization or a universal +odor mapping. There is no unit conversion, calibration or efficacy claim. Source +units/scale stay untouched in snapshots; command intensities are floating-point +software mapping results. Ranges unusable by that mapper refuse. + +Policy properties must exactly match bindings; each bound property must occur +exactly once in the selected representation. Missing or repeated bound properties +refuse, rather than silently ignoring data or choosing the first occurrence. +The policy's numeric min/max must equal the source scale. Unit spelling and +presence must match exactly: missing, `null` and a nonblank string are distinct. +No percent/rating/score conversion or assumed 0..100 range. Unknown policy +extensions are passive context; only documented fields affect this path. + +The selected known scheme data is validated explicitly; registered Core schemes +still undergo normal whole-envelope validation. Other unselected representations +remain retained and uninterpreted. Ordinary graph perceptual mapping and existing +semantic Core mapping do not acquire this new policy requirement. + +## Projection, SDK and provenance + +The SDK entry stays the same: + +```python +from opensmell.experimental.core_planning import plan_core_bytes +artifact = plan_core_bytes(core_bytes, profile_bytes, representation_index=0, duration=0.1) +``` + +The plan uses the existing offline-plan0.1 envelope. `source.document` contains +one opaque `org.opensmell.experimental.core-perceptual-representation` resource, +with selected scheme/data/context and Core odor ID. It is **not** a Molecule, +Stimulus, participant or measured Observation. An application representation does +not establish a presentation or experimental measurement event. + +The reserved root extension `org.opensmell.experimental.core-perceptual-selection` +retains the explicit index and exact Core bytes/Base64/SHA-256/length. Unknown +source fields, provenance, other representations and JSON whitespace/line endings +are preserved. Parsed profile data and its declared hash are retained; profile +whitespace is not reconstructed. Hashes identify bytes, not authenticity. + +Normal `plan` on the projection, frame export and sequence preflight recompute it +from retained Core bytes/index. A changed projection is refused even if an edited +plan agrees with it. Both semantic and perceptual selection markers in one graph +refuse. Reprepare changed source instead of editing generated projection fields. +The old semantic namespace/output and chemical bridge remain unchanged. Removing +source metadata does not authenticate a graph; the new opaque subject alone is +not a regular Observation accepted by the ordinary perceptual mapper. + +Bounds stay Core4MiB/profile1MiB/offline plan8MiB, finite durations/intensities, +nonempty unique commands and all supplied/live target capabilities. No default +representation, profile, command, retry, discovery or automatic sending is added. + +## Reproduce software interoperability + +```sh +python -m build --wheel +python -m tools.verify_installed_core_perceptual dist/opensmell-0.1.0-py3-none-any.whl \ + --output /tmp/new-core-perceptual-proof +``` + +The fresh-wheel proof runs outside checkout with inherited build dependencies, +prepares both selections, deletes original Core/profile paths, exports frames and +uses explicit Python and independent Node software endpoints. Unit/scale/policy/ +index and stale-projection refusals and output collisions are checked. Optional +`--host /explicit/native-lifecycle-host` adds the actual compiled lifecycle sketch +in native `--realtime` software mode. Existing CI runs that case without flashing. +No physical delivery, participant observation, odor reproduction or independent +third-party adoption follows from these repository-owned software checks. diff --git a/docs/core-planning.md b/docs/core-planning.md index eb1a042..fb7ffea 100644 --- a/docs/core-planning.md +++ b/docs/core-planning.md @@ -1,4 +1,7 @@ -# Explicit Core semantic planning (experimental) +# Explicit Core planning (experimental) + +The semantic path below remains compatible. For the opt-in quantitative path, +see [Core perceptual planning and explicit unit/scale policy](core-perceptual-planning.md). `opensmell plan-core` plans **one explicitly selected semantic representation** from a Core0.1 `.osmell` file with an application-owned mapping/capability profile. @@ -35,7 +38,7 @@ selection is supplied. Use your own Core/profile paths outside the checkout; stdin `-` is supported for Core input. `--output` exclusively creates a new file; stdout is available when it is omitted. Exit0 planned,1 invalid/refused,2 file error. -The first slice accepts only `type:semantic`, +The original semantic slice accepts only `type:semantic`, `org.opensmell.semantic.annotations` version0.1, with an explicit `mapper:semantic` profile. Known scheme data must validate. A selected unknown scheme/type/version, invalid index, unmapped annotation set, incompatible supplied capabilities or diff --git a/docs/development-status.md b/docs/development-status.md index ef7ae18..cfd9aeb 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. +## Core quantitative selection — 2026-11-25 evening + +The first passive trial-analysis slice (#47) is closed. The SDK/format gap is now +[explicit Core perceptual selection](core-perceptual-planning.md): choose one +quantitative representation with explicit normalization and expected unit/scale +policy, without requiring a chemical representation or inventing an Observation. +Existing semantic output and ordinary graph mappers remain compatible. + +Exit: installed Core->two distinct selected plans->frames after originals removed +->Python/Node/actual native sketch receipts; exact Core/provenance/unknown fields +retained, explicit unit presence and scale mismatch/duplicate/missing bound data, +unknown index, stale projection and output collision refusals. Close this bounded +path after CI; no automatic representation/policy catalog. Human hardware evidence +and independent adoption remain unobserved, separate whole-kit gates. + ## Trial observation analysis — 2026-11-25 The first installed dossier execution path (#46) is closed. The next concrete diff --git a/examples/core_perceptual_only.osmell b/examples/core_perceptual_only.osmell new file mode 100644 index 0000000..38da9e7 --- /dev/null +++ b/examples/core_perceptual_only.osmell @@ -0,0 +1,122 @@ +{ + "opensmell": "0.1", + "odor": { + "id": "urn:opensmell:synthetic:core-perceptual", + "representations": [ + { + "type": "perceptual", + "scheme": { + "id": "org.opensmell.perceptual.measurements", + "version": "0.1", + "caller_extension": "retained" + }, + "data": { + "measurements": [ + { + "property": "flower", + "value": 2.5, + "scale": { + "min": 0, + "max": 10 + }, + "unit": "rating", + "future": { + "opaque": [ + null, + 36893488147419103232 + ] + } + }, + { + "property": "grass", + "value": 0, + "scale": { + "min": -1, + "max": 1 + }, + "unit": null + }, + { + "property": "wood", + "value": 100, + "scale": { + "min": 0, + "max": 100 + } + } + ] + }, + "provenance": { + "source": "Declared synthetic Core example; no measured participant/device outcome" + } + }, + { + "type": "perceptual", + "scheme": { + "id": "org.opensmell.perceptual.measurements", + "version": "0.1", + "caller_extension": "retained" + }, + "data": { + "measurements": [ + { + "property": "flower", + "value": 7.5, + "scale": { + "min": 0, + "max": 10 + }, + "unit": "rating", + "future": { + "opaque": [ + null, + 36893488147419103232 + ] + } + }, + { + "property": "grass", + "value": 0, + "scale": { + "min": -1, + "max": 1 + }, + "unit": null + }, + { + "property": "wood", + "value": 100, + "scale": { + "min": 0, + "max": 100 + } + } + ] + }, + "provenance": { + "source": "Declared synthetic Core example; no measured participant/device outcome" + } + }, + { + "type": "caller.future", + "scheme": { + "id": "caller.unknown", + "version": "9" + }, + "data": { + "opaque": [ + true, + null, + 1180591620717411303424 + ] + } + } + ], + "metadata": { + "description": "Two quantitative source selections; no chemical representation and no measured odor outcome." + } + }, + "future": { + "retain": "all bytes" + } +} diff --git a/examples/developer_kit/START_HERE.md b/examples/developer_kit/START_HERE.md index cd6a1e9..5b37537 100644 --- a/examples/developer_kit/START_HERE.md +++ b/examples/developer_kit/START_HERE.md @@ -203,3 +203,5 @@ pseudo-terminals only. Existing software sequence commands remain unchanged. For a whole caller-ordered prepared dossier, see [RUN_EXPERIMENT.md](RUN_EXPERIMENT.md). For passive receipt/observation joins and CSV analysis, see [TRIAL_ANALYSIS.md](TRIAL_ANALYSIS.md). + +For explicit quantitative Core selection, see [CORE_PERCEPTUAL.md](CORE_PERCEPTUAL.md). diff --git a/examples/offline_core_perceptual_profile.json b/examples/offline_core_perceptual_profile.json new file mode 100644 index 0000000..b523682 --- /dev/null +++ b/examples/offline_core_perceptual_profile.json @@ -0,0 +1,73 @@ +{ + "format": "org.opensmell.experimental.mapping-profile", + "version": "0.1", + "description": "Explicit synthetic Core software demonstration. No unit conversion or physical output claim.", + "capabilities": { + "protocol_version": "0.1", + "type": "capabilities", + "device_id": "opensmell-offline-example-3ch", + "channels": [ + { + "channel": 0, + "min_intensity": 0.0, + "max_intensity": 1.0 + }, + { + "channel": 1, + "min_intensity": 0.0, + "max_intensity": 1.0 + }, + { + "channel": 2, + "min_intensity": 0.0, + "max_intensity": 1.0 + } + ], + "min_duration": 0.1, + "max_duration": 30.0 + }, + "mapper": "perceptual", + "bindings": [ + { + "property": "flower", + "channel": 0 + }, + { + "property": "grass", + "channel": 1 + }, + { + "property": "wood", + "channel": 2 + } + ], + "org.opensmell.experimental.core-perceptual-policy": { + "version": "0.1", + "normalization": "value-minus-min-over-range", + "measurements": [ + { + "property": "flower", + "scale": { + "min": 0, + "max": 10 + }, + "unit": "rating" + }, + { + "property": "grass", + "scale": { + "min": -1, + "max": 1 + }, + "unit": null + }, + { + "property": "wood", + "scale": { + "min": 0, + "max": 100 + } + } + ] + } +} diff --git a/rfcs/RFC-0015.md b/rfcs/RFC-0015.md index f29a7f9..37ddfb0 100644 --- a/rfcs/RFC-0015.md +++ b/rfcs/RFC-0015.md @@ -109,3 +109,22 @@ separately labeled negative control and fake PWM/clock samples. Unknown/failure and acceptance are distinct: a known acceptance need not imply a completed trial. It adds no protocol wire field, serial transport, authentication, lifecycle/Stop or physical result. The report and this RFC remain experimental and non-normative. + + +## Experimental Core perceptual selection application policy + +The opt-in `plan-core` consumer may interpret one explicitly indexed provisional +perceptual-measurements0.1 representation under the recognized profile extension +`org.opensmell.experimental.core-perceptual-policy`, version0.1. It requires +`normalization:value-minus-min-over-range` and `measurements` entries matching +all bound properties, with explicit expected numeric scales and exact unit +presence/value. Units are compared, never converted. Duplicate/missing bound +measurements refuse. Unknown fields remain passive; ordinary graph/semantic +mapping is unchanged. See the Core perceptual guide for complete examples. + +Its reserved `org.opensmell.experimental.core-perceptual-selection` projection +retains exact source bytes/index and one opaque representation resource; it does +not invent a Stimulus or observed experiment. The normal planning/frame/sequence +boundaries recompute it from the source and validate the policy before commands +are actionable. This is an experimental application convention, not a Core wire +change, global scheme registration or promotion of RFC-0005/0015 beyond Draft. diff --git a/src/opensmell/cli.py b/src/opensmell/cli.py index 42293db..4006681 100644 --- a/src/opensmell/cli.py +++ b/src/opensmell/cli.py @@ -584,7 +584,7 @@ def main(argv: list[str] | None = None) -> int: workspace = commands.add_parser("init-workspace", help="Create a new passive synthetic software starter using only installed resources") workspace.add_argument("directory", help="New workspace directory; never overwrite") commands.add_parser("simulate-device", help="Serve the SDK software simulator over bounded stdin/stdout JSON lines; no hardware") - core_planning = commands.add_parser("plan-core", help="Plan one explicitly selected Core semantic representation passively") + core_planning = commands.add_parser("plan-core", help="Plan one explicitly selected Core semantic/perceptual representation passively") core_planning.add_argument("file", help="Core0.1 file or stdin (-); max4MiB") core_planning.add_argument("--representation-index", type=int, required=True, help="Explicit zero-based semantic annotations0.1 representation index") core_planning.add_argument("--profile", required=True, help="Explicit semantic mapping/capability profile") diff --git a/src/opensmell/experimental/core_perceptual.py b/src/opensmell/experimental/core_perceptual.py new file mode 100644 index 0000000..4654b94 --- /dev/null +++ b/src/opensmell/experimental/core_perceptual.py @@ -0,0 +1,98 @@ +"""Experimental Core quantitative projection; no measured Observation is invented.""" +import base64 +from copy import deepcopy +import hashlib +import math + +from ..schemes.perceptual_measurements import validate +from .generic_graph import GENERIC_RESOURCE_GRAPH_FORMAT, generic_graph_to_dict +from .perceptual_channel_mapper import PerceptualChannelMapper +from .rendering import DeviceCommand, RenderingPlan + +SELECTION_KEY = 'org.opensmell.experimental.core-perceptual-selection' +POLICY_KEY = 'org.opensmell.experimental.core-perceptual-policy' +NORMALIZATION = 'value-minus-min-over-range' +SCHEME = {'id':'org.opensmell.perceptual.measurements','version':'0.1'} + + +def project_perceptual_selection(raw, document, index): + """Project one already envelope-validated Core representation as opaque data.""" + selected = document['odor']['representations'][index] + if selected['type'] != 'perceptual' or any(selected['scheme'].get(k) != v for k,v in SCHEME.items()): + raise ValueError('Selected perceptual representation must use measurements0.1') + validate(selected['data']) + digest = hashlib.sha256(raw).hexdigest() + subject = f'urn:opensmell:core-perceptual-selection:{digest}:{index}' + return {'format':GENERIC_RESOURCE_GRAPH_FORMAT,'version':'0.1', + SELECTION_KEY:{'version':'0.1','representation_index':index, + 'source':{'encoding':'base64','data':base64.b64encode(raw).decode('ascii'), + 'sha256':digest,'byte_count':len(raw)}}, + 'resources':[{'id':subject,'type':'org.opensmell.experimental.core-perceptual-representation', + 'type_version':'0.1','core_odor_id':document['odor']['id'], + 'scheme':deepcopy(selected['scheme']),'data':deepcopy(selected['data']), + 'core_representation_context':{k:deepcopy(v) for k,v in selected.items() if k not in {'scheme','data'}}}]},subject + + +def map_core_perceptual(graph, request, profile, mapper): + """Reuse the demonstration mapper's formula under explicit source expectations. + + Only this reserved Core projection understands the policy extension. Ordinary + graph/semantic mapping remains unchanged. Units are compared, never converted. + """ + from .core_planning import validate_core_projection + document = generic_graph_to_dict(graph) + validate_core_projection(document) + if not isinstance(mapper, PerceptualChannelMapper): + raise ValueError('Core perceptual selection requires mapper:perceptual') + selected = document['resources'][0] + if request.resource_id != selected['id']: + raise ValueError('Request must select the explicitly projected Core subject') + policy = profile.get(POLICY_KEY) + if (not isinstance(policy, dict) or policy.get('version') != '0.1' + or policy.get('normalization') != NORMALIZATION): + raise ValueError('Explicit Core perceptual policy/version and normalization required') + expectations = policy.get('measurements') + if not isinstance(expectations, list) or not expectations: + raise ValueError('Core perceptual policy requires measurement expectations') + by_property = {} + for entry in expectations: + if (not isinstance(entry, dict) or not isinstance(entry.get('property'), str) + or not entry['property'].strip() or entry['property'] in by_property): + raise ValueError('Unique nonblank policy properties required') + scale = entry.get('scale') + if (not isinstance(scale, dict) or any(isinstance(scale.get(k), bool) + or not isinstance(scale.get(k),(int,float)) for k in ('min','max')) + or scale['min'] >= scale['max']): + raise ValueError('Policy requires explicit numeric min= float(scale['max']): + raise ValueError('Policy scale must be finite and usable by the float demonstration mapper') + except OverflowError as error: + raise ValueError('Policy scale exceeds demonstration mapper range') from error + if 'unit' in entry and entry['unit'] is not None and (not isinstance(entry['unit'],str) or not entry['unit'].strip()): + raise ValueError('Policy unit must be a nonblank string or null; omission requires absent source unit') + by_property[entry['property']] = entry + if set(by_property) != {b.property for b in mapper.bindings}: + raise ValueError('Policy properties must match the explicit bindings exactly') + measurements = selected['data']['measurements'] + commands = [] + for binding in mapper.bindings: + candidates = [m for m in measurements if m['property'] == binding.property] + if len(candidates) != 1: + raise ValueError('Each bound property requires exactly one selected measurement: ' + binding.property) + measurement, expectation = candidates[0], by_property[binding.property] + if ('unit' in measurement) != ('unit' in expectation) or measurement.get('unit') != expectation.get('unit'): + raise ValueError('Selected measurement unit/presence does not match policy: ' + binding.property) + if any(measurement['scale'][k] != expectation['scale'][k] for k in ('min','max')): + raise ValueError('Selected measurement scale does not match policy: ' + binding.property) + try: + parsed = mapper._parse_measurement(measurement) + if parsed is None or not math.isfinite(parsed[1]): + raise ValueError('Selected measurement cannot be normalized') + except (OverflowError,ZeroDivisionError) as error: + raise ValueError('Selected measurement exceeds demonstration mapper range') from error + commands.append(DeviceCommand(binding.channel, parsed[1])) + return RenderingPlan(commands, request.duration, + extra={'mapper':'org.opensmell.experimental.core-perceptual-channel-mapper', + 'source_resource_id':request.resource_id,'normalization':NORMALIZATION, + 'policy_key':POLICY_KEY}) diff --git a/src/opensmell/experimental/core_planning.py b/src/opensmell/experimental/core_planning.py index 16faee6..82b0d51 100644 --- a/src/opensmell/experimental/core_planning.py +++ b/src/opensmell/experimental/core_planning.py @@ -1,4 +1,4 @@ -"""Explicit semantic Core selection to an ordinary experimental offline plan. +"""Explicit semantic or perceptual Core selection to an ordinary experimental offline plan. No chemical representation required; no new Core or device wire contract. """ @@ -20,7 +20,7 @@ def project_core_selection(raw, representation_index): - """Project exactly one selected known semantic representation, retaining all bytes.""" + """Project exactly one selected supported representation, retaining all bytes.""" if not isinstance(raw, bytes) or len(raw) > MAX_CORE_BYTES: raise ValueError('Core bytes required; at most 4 MiB') document = decode_bytes(raw) @@ -31,6 +31,9 @@ def project_core_selection(raw, representation_index): if type(representation_index) is not int or not 0 <= representation_index < len(representations): raise ValueError('Explicit zero-based representation index required and must exist') selected = representations[representation_index] + if selected['type'] == 'perceptual': + from .core_perceptual import project_perceptual_selection + return project_perceptual_selection(raw, document, representation_index) scheme = selected['scheme'] if (selected['type'] != 'semantic' or scheme['id'] != 'org.opensmell.semantic.annotations' or scheme['version'] != '0.1'): @@ -58,11 +61,15 @@ def validate_core_projection(document): Other generic graphs are unchanged. Integrity is not source authentication; removing this application convention does not authenticate a different graph. """ - if SELECTION_KEY not in document: + from .core_perceptual import SELECTION_KEY as PERCEPTUAL_KEY + keys = [key for key in (SELECTION_KEY, PERCEPTUAL_KEY) if key in document] + if not keys: return - selection = document[SELECTION_KEY] + if len(keys) != 1: + raise ValueError('Ambiguous Core selection projection') + selection = document[keys[0]] if not isinstance(selection, dict) or selection.get('version') != '0.1': - raise ValueError('Unsupported Core semantic selection projection') + raise ValueError('Unsupported Core selection projection') snapshot = selection.get('source') if not isinstance(snapshot, dict) or snapshot.get('encoding') != 'base64': raise ValueError('Missing exact Core source snapshot') @@ -84,19 +91,21 @@ def plan_core_bytes(raw, profile_raw, *, representation_index, duration): raise ValueError('Profile bytes required; at most 1 MiB') projection, subject = project_core_selection(raw, representation_index) profile = decode_bytes(profile_raw) - if not isinstance(profile, dict) or profile.get('mapper') != 'semantic': - raise ValueError('Selected Core semantic representation requires an explicit semantic mapping profile') + from .core_perceptual import SELECTION_KEY as PERCEPTUAL_KEY + kind = 'perceptual' if PERCEPTUAL_KEY in projection else 'semantic' + if not isinstance(profile, dict) or profile.get('mapper') != kind: + raise ValueError('Selected Core ' + kind + ' representation requires an explicit ' + kind + ' mapping profile') graph = generic_graph_from_dict(projection, registry=interchange_registry()) request = RenderRequest(subject, duration) plan = plan_with_profile(graph, request, profile) encoded_projection = json.dumps(projection,sort_keys=True,allow_nan=False).encode() artifact = {'format':'org.opensmell.experimental.offline-plan','version':'0.1','status':'planned', 'execution':'not_attempted','capability_basis':'supplied_profile_not_live_device', - 'source':{'input':'explicit Core semantic projection','sha256':hashlib.sha256(encoded_projection).hexdigest(), + 'source':{'input':'explicit Core ' + kind + ' projection','sha256':hashlib.sha256(encoded_projection).hexdigest(), 'document':projection}, 'profile':{'input':'supplied profile','sha256':hashlib.sha256(profile_raw).hexdigest(),'document':profile}, 'request':asdict(request),'plan':asdict(plan), - 'limitations':['Only the explicitly selected Core semantic annotations0.1 are interpreted.', + 'limitations':[('Only the explicitly selected Core semantic annotations0.1 are interpreted.' if kind == 'semantic' else 'Only selected experimental Core perceptual measurements0.1 are mapped under explicit unit/scale/normalization policy.'), 'Exact Core bytes retain all other representations and provenance; no chemical identity is inferred.', 'Application mapping and supplied capabilities; no command, acceptance, execution or odor result.', 'Projection is an experimental application convention; hashes are not signatures.']} diff --git a/src/opensmell/experimental/planning.py b/src/opensmell/experimental/planning.py index 14994e5..d95d4af 100644 --- a/src/opensmell/experimental/planning.py +++ b/src/opensmell/experimental/planning.py @@ -29,6 +29,8 @@ def plan_with_profile( mappers. No channel meaning or physical effect is inferred from input data. See Draft RFC-0015 for this experimental configuration envelope. """ + if not isinstance(graph, GenericResourceGraph): + raise TypeError("graph must be a GenericResourceGraph") if not isinstance(profile, dict): raise TypeError("mapping profile must be an object") if profile.get("format") != MAPPING_PROFILE_FORMAT or profile.get("version") != "0.1": @@ -48,7 +50,11 @@ def plan_with_profile( require_support = getattr(mapper, "require_support", None) if require_support is not None: require_support(capabilities) - plan = mapper.map(graph, request) + from .core_perceptual import SELECTION_KEY as CORE_PERCEPTUAL_KEY, map_core_perceptual + if CORE_PERCEPTUAL_KEY in graph.extra: + plan = map_core_perceptual(graph, request, profile, mapper) + else: + plan = mapper.map(graph, request) capabilities.require_plan(plan) if not plan.commands: raise ValueError("mapping produced no commands; check the selected resource and bindings") diff --git a/tests/test_core_perceptual_planning.py b/tests/test_core_perceptual_planning.py new file mode 100644 index 0000000..7dc55b7 --- /dev/null +++ b/tests/test_core_perceptual_planning.py @@ -0,0 +1,108 @@ +"""Selected Core quantitative data, explicit unit/scale policy, no invented experiment.""" +import base64 +from copy import deepcopy +import json +from pathlib import Path +import subprocess +import sys +import pytest +from opensmell.exceptions import OpenSmellError +from opensmell.experimental.core_planning import plan_core_bytes, validate_core_projection +from opensmell.experimental.core_perceptual import POLICY_KEY, SELECTION_KEY +from opensmell.experimental.core_interchange import interchange_registry +from opensmell.experimental.generic_graph import generic_graph_from_dict +from opensmell.experimental.planning import plan_with_profile +from opensmell.experimental.rendering import RenderRequest +from opensmell.experimental.frame_export import encode_plan_frame +from opensmell.experimental.transport_sequence import prepare_steps, run_transport_sequence +from test_transport_sequence import Transport, ID + +ROOT=Path(__file__).resolve().parents[1] +CORE=(ROOT/'examples/core_perceptual_only.osmell').read_bytes() +PROFILE=(ROOT/'examples/offline_core_perceptual_profile.json').read_bytes() +TARGET=json.dumps(json.loads(PROFILE)['capabilities']).encode() + + +def encoded(obj):return json.dumps(obj,indent=3).encode()+b'\r\n' + + +def test_selected_representations_normal_frame_sdk_and_no_fabricated_observation(): + plans=[] + for index,flower in [(0,.25),(1,.75)]: + artifact=plan_core_bytes(CORE,PROFILE,representation_index=index,duration=.1) + assert artifact['plan']['commands']==[{'channel':0,'intensity':flower},{'channel':1,'intensity':.5},{'channel':2,'intensity':1}] + doc=artifact['source']['document'];assert base64.b64decode(doc[SELECTION_KEY]['source']['data'])==CORE + assert len(doc['resources'])==1 and doc['resources'][0]['type']=='org.opensmell.experimental.core-perceptual-representation' + assert not any(r['type'] in {'observation','stimulus','org.opensmell.molecule'} for r in doc['resources']) + raw=encoded(artifact);plans.append(raw) + assert json.loads(encode_plan_frame(raw,TARGET)['frame']['line'])['commands']==artifact['plan']['commands'] + t=Transport();report=run_transport_sequence(plans,lambda:t,expected_device_id=ID) + assert report['status']=='completed' and t.renders==2 and t.closed==1 + assert [s.plan.commands[0].intensity for s in prepare_steps(plans)]==[.25,.75] + + +@pytest.mark.parametrize('bad',['no_policy','version','normalization','unit','missing_unit','null_unit','scale','extra_policy_property', + 'duplicate_policy_property','missing_policy_property','policy_bool','policy_unit_object','policy_scale_overflow','profile_mapper', + 'source_duplicate','source_missing','source_invalid','source_unknown_scheme','source_unknown_version','index','no_bindings','duration']) +def test_refused_inputs_never_choose_fallback(bad): + core=json.loads(CORE);profile=json.loads(PROFILE);index=0;duration=.1 + policy=profile[POLICY_KEY];source=core['odor']['representations'][0]['data']['measurements'] + if bad=='no_policy':profile.pop(POLICY_KEY) + if bad=='version':policy['version']='9' + if bad=='normalization':policy['normalization']='infer' + if bad=='unit':policy['measurements'][0]['unit']='percent' + if bad=='missing_unit':policy['measurements'][0].pop('unit') + if bad=='null_unit':policy['measurements'][2]['unit']=None + if bad=='scale':policy['measurements'][0]['scale']['max']=100 + if bad=='extra_policy_property':policy['measurements'].append({'property':'extra','scale':{'min':0,'max':1}}) + if bad=='duplicate_policy_property':policy['measurements'].append(deepcopy(policy['measurements'][0])) + if bad=='missing_policy_property':policy['measurements'].pop() + if bad=='policy_bool':policy['measurements'][0]['scale']['min']=False + if bad=='policy_unit_object':policy['measurements'][0]['unit']={} + if bad=='policy_scale_overflow':policy['measurements'][0]['scale']['max']=10**400 + if bad=='profile_mapper':profile['mapper']='semantic' + if bad=='source_duplicate':source.append(deepcopy(source[0])) + if bad=='source_missing':source.pop() + if bad=='source_invalid':source[0]['value']=1000 + if bad=='source_unknown_scheme':core['odor']['representations'][0]['scheme']['id']='caller.future' + if bad=='source_unknown_version':core['odor']['representations'][0]['scheme']['version']='9' + if bad=='index':index=2 + if bad=='no_bindings':profile['bindings']=[] + if bad=='duration':duration=31 + with pytest.raises((OpenSmellError,ValueError,TypeError)): + plan_core_bytes(encoded(core),encoded(profile),representation_index=index,duration=duration) + + +@pytest.mark.parametrize('bad',['value','unit','scale','index','snapshot','both','policy','request']) +def test_stale_projection_and_inconsistent_policy_refused_at_existing_normal_boundaries(bad): + artifact=plan_core_bytes(CORE,PROFILE,representation_index=0,duration=.1) + doc=artifact['source']['document'];m=doc['resources'][0]['data']['measurements'][0] + if bad=='value': + m['value']=7.5;artifact['plan']['commands'][0]['intensity']=.75 + if bad=='unit':m['unit']='percent' + if bad=='scale':m['scale']['max']=100 + if bad=='index':doc[SELECTION_KEY]['representation_index']=1 + if bad=='snapshot':doc[SELECTION_KEY]['source']['sha256']='0'*64 + if bad=='both':doc['org.opensmell.experimental.core-semantic-selection']=deepcopy(doc[SELECTION_KEY]) + if bad=='policy':artifact['profile']['document'][POLICY_KEY]['measurements'][0]['unit']='other' + if bad=='request':artifact['request']['resource_id']='another' + with pytest.raises(ValueError):encode_plan_frame(encoded(artifact),TARGET) + opened=[];r=run_transport_sequence([encoded(artifact)],lambda:opened.append(True),expected_device_id=ID) + assert r['status']=='invalid' and opened==[] + + +def test_direct_graph_plan_obeys_same_projection_and_policy_guard(): + artifact=plan_core_bytes(CORE,PROFILE,representation_index=0,duration=.1) + doc=artifact['source']['document'];doc['resources'][0]['data']['measurements'][0]['value']=7.5 + graph=generic_graph_from_dict(doc,registry=interchange_registry()) + with pytest.raises(ValueError):plan_with_profile(graph,RenderRequest(artifact['request']['resource_id'],.1),json.loads(PROFILE)) + + +def test_normal_cli_exclusive_output_and_no_profile_auto_selection(tmp_path): + output=tmp_path/'plan.json' + cmd=[sys.executable,'-m','opensmell','plan-core','-','--representation-index','0','--profile',str(ROOT/'examples/offline_core_perceptual_profile.json'),'--duration','.1','--output',str(output)] + r=subprocess.run(cmd,input=CORE,capture_output=True);assert r.returncode==0,r.stderr + before=output.read_bytes();assert subprocess.run(cmd,input=CORE,capture_output=True).returncode==2 + assert output.read_bytes()==before + cmd[cmd.index('--representation-index')+1]='2';cmd[-1]=str(tmp_path/'refused.json') + assert subprocess.run(cmd,input=CORE,capture_output=True).returncode==1 and not (tmp_path/'refused.json').exists() diff --git a/tools/build_developer_kit.py b/tools/build_developer_kit.py index 01f4a83..deed158 100644 --- a/tools/build_developer_kit.py +++ b/tools/build_developer_kit.py @@ -21,6 +21,9 @@ ROOT = Path(__file__).resolve().parents[1] # Explicit allowlist; external datasets, caches and arbitrary checkout files are excluded. PAYLOADS = { + "CORE_PERCEPTUAL.md": "docs/core-perceptual-planning.md", + "data/core_perceptual_only.osmell": "examples/core_perceptual_only.osmell", + "data/core_perceptual_profile.json": "examples/offline_core_perceptual_profile.json", "TRIAL_ANALYSIS.md": "docs/trial-analysis.md", "RUN_EXPERIMENT.md": "docs/run-experiment.md", "TRANSPORT_SEQUENCES.md": "docs/transport-sequences.md", diff --git a/tools/verify_installed_core_perceptual.py b/tools/verify_installed_core_perceptual.py new file mode 100644 index 0000000..415e313 --- /dev/null +++ b/tools/verify_installed_core_perceptual.py @@ -0,0 +1,98 @@ +"""Installed quantitative Core -> explicit policy -> frame -> Python/Node/native.""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import venv + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('wheel',type=Path);parser.add_argument('--host',type=Path) + parser.add_argument('--output',type=Path,required=True) + args=parser.parse_args();wheel=args.wheel.resolve(strict=True) + host=args.host.resolve(strict=True) if args.host else None + output=args.output.resolve();output.mkdir(parents=True,exist_ok=False) + root=Path(__file__).resolve().parents[1] + result={'result':'incomplete','physical_validation':False,'source_kind':'declared synthetic Core','cases':[]} + def save():(output/'result.json').write_text(json.dumps(result,indent=2)+'\n') + save() + with tempfile.TemporaryDirectory(prefix='opensmell-installed-core-perceptual-') as tmp: + work=Path(tmp);venv.EnvBuilder(with_pip=True,system_site_packages=True).create(work/'venv') + python=work/'venv'/('Scripts/python.exe' if os.name=='nt' else 'bin/python') + env={k:v for k,v in os.environ.items() if k not in {'PYTHONPATH','PYTHONHOME'}} + def run(command,code=0): + r=subprocess.run(list(map(str,command)),cwd=work,env=env,capture_output=True,timeout=60) + assert r.returncode==code,(command,r.returncode,r.stdout[-1000:],r.stderr[-1000:]) + return r.stdout + cli=[python,'-I','-m','opensmell'] + 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');result['installed_outside_checkout']=True + result['dependency_scope']='Installed wheel with inherited build dependencies; no clean offline or physical proof' + raw=(root/'examples/core_perceptual_only.osmell').read_bytes().replace(b'\n',b'\r\n') + profile=(root/'examples/offline_core_perceptual_profile.json').read_bytes() + source=work/'caller.osmell';source.write_bytes(raw) + supplied=work/'profile.json';supplied.write_bytes(profile) + target=work/'target.json';target.write_text(json.dumps(json.loads(profile)['capabilities'])) + plans=[] + for index in (0,1): + path=work/f'plan-{index}.json' + cmd=[*cli,'plan-core',source,'--representation-index',str(index),'--profile',supplied,'--duration','.1','--output',path] + run(cmd);artifact=json.loads(path.read_bytes());doc=artifact['source']['document'] + assert len(doc['resources'])==1 and doc['resources'][0]['type']=='org.opensmell.experimental.core-perceptual-representation' + snapshot=doc['org.opensmell.experimental.core-perceptual-selection']['source'] + assert base64.b64decode(snapshot['data'])==raw and snapshot['sha256']==hashlib.sha256(raw).hexdigest() + assert [c['intensity'] for c in artifact['plan']['commands']]==[.25 if index==0 else .75,.5,1] + before=path.read_bytes();run(cmd,2);assert path.read_bytes()==before + shutil.copyfile(path,output/path.name);plans.append(path) + # Wrong unit, scale, policy and unknown index must refuse before output. + policy='org.opensmell.experimental.core-perceptual-policy' + for kind in ('unit','scale','normalization','missing-policy','unknown-index'): + p=json.loads(profile);index=0 + if kind=='unit':p[policy]['measurements'][0]['unit']='percent' + if kind=='scale':p[policy]['measurements'][0]['scale']['max']=100 + if kind=='normalization':p[policy]['normalization']='guess' + if kind=='missing-policy':p.pop(policy) + if kind=='unknown-index':index=2 + bad_profile=work/(kind+'.json');bad_profile.write_text(json.dumps(p)) + absent=work/(kind+'-must-not-exist') + run([*cli,'plan-core',source,'--representation-index',str(index),'--profile',bad_profile,'--duration','.1','--output',absent],1) + assert not absent.exists() + source.unlink();supplied.unlink() + for path in plans: + frame=json.loads(run([*cli,'encode-frame',path,'--capabilities',target])) + assert frame['transport']=='not_opened' + (output/(path.stem+'-frame.json')).write_text(json.dumps(frame,indent=2)) + shutil.copyfile(root/'examples/lifecycle_adapter/python_device.py',work/'device.py') + shutil.copyfile(root/'examples/lifecycle_adapter/device.cjs',work/'device.cjs') + endpoints=[('python',[str(python),'-I',str(work/'device.py')],'opensmell-local-simulator-001'), + ('node',['node',str(work/'device.cjs')],'opensmell-node-simulator-001')] + if host:endpoints.append(('native',[str(host),'--realtime'],'opensmell-esp32-lifecycle-led-001')) + for name,command,identity in endpoints: + receipt=output/(name+'-receipt.json') + report=json.loads(run([*cli,'run-sequence',*plans,'--software-command-json',json.dumps(command), + '--expected-device-id',identity,'--output',receipt])) + assert report['status']=='completed' and [s['state'] for s in report['sequence']['steps']]==['completed','completed'] + assert [[c['intensity'] for c in s['plan']['commands']] for s in report['sequence']['steps']]==[[.25,.5,1],[.75,.5,1]] + result['cases'].append({'endpoint':name,'states':['completed','completed']});save() + # A matching edited graph/plan cannot replace the original retained Core. + changed=json.loads(plans[0].read_bytes());changed['source']['document']['resources'][0]['data']['measurements'][0]['value']=7.5 + changed['plan']['commands'][0]['intensity']=.75 + stale=work/'stale.json';stale.write_text(json.dumps(changed)) + flag=work/'must-not-launch';command=[str(python),'-c',f"from pathlib import Path;Path({str(flag)!r}).write_text('launched')"] + refusal=json.loads(run([*cli,'run-sequence',stale,'--software-command-json',json.dumps(command), + '--expected-device-id','opensmell-local-simulator-001','--output',output/'stale-refusal.json'],1)) + assert refusal['status']=='invalid' and not flag.exists() and refusal['transcript']==[] + result.update(result='passed',exact_core_preserved=True,original_preparation_paths_deleted=True, + no_invented_observation=True,explicit_unit_scale_policy_refusals=True, + stale_projection_no_process=True,collision_preserved=True) + save() + print(json.dumps(result,indent=2)) + +if __name__=='__main__':main()