Gate decides
Healthy work proceeds. Drift or missing evidence returns the session to repair.
diff --git a/.gitignore b/.gitignore
index f385dc1..485aaea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -57,6 +57,8 @@ ENV/
.cursor/settings.local.json
.mcp.local.json
.melampus/
+pilot-results/
+pilot-results/*.lock
# macOS
.DS_Store
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50ba339..ac1eb39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.2.0] - 2026-10-02
+
+### Added
+
+- Explicit `instrument(target, namespace=..., contracts=...)` registration for
+ ordinary Python class instances, modules and grouped function boundaries.
+ Selected methods preserve binding, signatures, sync/async behavior and target
+ typing; shared classes are untouched and unsupported descriptors fail explicitly.
+- Optional stable `path=` on existing function decorators; the inferred path
+ and experimental 0.1.0 wire schema remain compatible.
+- Three-style registration/repair demo, Claude session example, official-source
+ SDK/decorator research and documented scope/bypass tradeoffs.
+- Local timed, resumable pilot covering all seven worksheet measures, six task
+ order rotations and Markdown/CSV/JSON reports. Synthetic runs are labeled;
+ human preference and comfort remain unmeasured.
+
+### Changed
+
+- Permit matching declarations from multiple instances sharing reviewed paths;
+ conflicts remain incomplete and passing calls do not erase drift.
+- Recommend explicit registration for existing services while retaining native
+ decorators as an equal supported choice for small function integrations.
+
## [0.1.0] - 2026-09-28
### Added
diff --git a/Makefile b/Makefile
index 2c6f438..8124864 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: dev lint typecheck test cov semconv build ci format demo demo-otlp benchmark
+.PHONY: dev lint typecheck test cov semconv build ci format demo demo-otlp demo-registration demo-pilot pilot benchmark
dev:
uv sync --locked --all-extras
@@ -7,6 +7,7 @@ lint:
uv run --locked ruff format --check .
typecheck:
uv run --locked mypy -p melampus
+ uv run --locked mypy --strict tests/types/public_api.py
test:
uv run --locked pytest
cov:
@@ -25,5 +26,11 @@ demo:
uv run --locked python scripts/demo_agent_session.py
demo-otlp:
uv run --locked python scripts/demo_session.py
+demo-registration:
+ uv run --locked python scripts/demo_registration.py
+demo-pilot:
+ uv run --locked python scripts/demo_pilot.py --demo
+pilot:
+ uv run --locked python scripts/demo_pilot.py $(ARGS)
benchmark:
uv run --locked python benchmarks/overhead.py
diff --git a/README.md b/README.md
index 55e4fab..9280ed7 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,8 @@ Keep an AI coding session aligned with reviewed intent. Give the agent a small
set of SDK contracts, run a local supervisor beside it, and feed execution
failures back into repair before the agent continues building.
-**0.1.0 alpha is in preparation; no PyPI release is claimed yet.** The SDK and
+**0.2.0 alpha. GitHub releases include validated wheels and sdists; PyPI
+publication is separate.** The SDK and
wire schema are experimental. The supervisor needs no SaaS, LLM judge, tracing
backend, collector, or unit-test framework. Python 3.11+, macOS/Linux.
@@ -57,7 +58,7 @@ It cannot infer arbitrary intent from prose, inspect unfinished model tokens,
prove unexecuted behavior, or guarantee the absence of all AI-generated slop.
Review the claims and scenarios before asking the agent to implement them.
-## SDK contracts travel with the code
+## Register reviewed contracts at the application boundary
Keep the reviewed definition in `intent.py`:
@@ -71,21 +72,58 @@ PRICE = Contract(
CONTRACTS = {"pricing:price": PRICE}
```
-The agent writes `pricing.py`:
+Keep business functions plain in `pricing.py`:
```python
-from intent import PRICE
-
-
-@PRICE.instrument(generator="claude-code")
def price(cents: int) -> int:
return max(0, cents)
```
+Register once in `registration.py`, then call through that object:
+
+```python
+from types import SimpleNamespace
+from melampus import instrument
+from intent import PRICE
+from pricing import price
+
+pricing = instrument(
+ SimpleNamespace(price=price),
+ namespace="pricing",
+ contracts={"price": PRICE},
+ generator="claude-code",
+)
+pricing.price(-100)
+```
+
+For an existing service use
+`instrument(PricingService(), namespace="pricing:PricingService", contracts={"price": PRICE})`
+and review `pricing:PricingService.price` in `CONTRACTS`. Registration returns
+the same typed object, preserves bound state and sync/async behavior, and never
+changes the shared class. Register each instance before sharing it. Original
+imports and captured references bypass registration; omitted methods are unconfigured.
+
+For a few functions, the existing `@PRICE.instrument()` and `@instrumented(...)`
+decorators remain supported. The original agent example/recording demonstrates
+that approach; [the registration example](examples/sdk-registration/README.md)
+shows all three styles beside an agent.
+
The session runner owns local OTel setup automatically. It verifies that the
function used the reviewed check objects and that every required check actually
ran. No network export is needed for this local path. The plain `@instrumented`
API remains available for applications that own their tracing configuration.
+Multiple instances can share reviewed paths; conflicts remain incomplete and
+a passing call cannot erase drift. The wire schema remains at **0.1.0**.
+
+```sh
+make demo-registration # compare decorator, class and module-boundary repair
+make demo-pilot # synthetic measurement walkthrough, no human claims
+make pilot ARGS='--participant p01 --rotation 0' # local, resumable participant study
+```
+
+[API boundaries](docs/SDK-REGISTRATION.md) ·
+[Official-source SDK/decorator research](docs/SDK-UX-RESEARCH.md) ·
+[Pilot tasks and reports](examples/pilot_study/README.md).
## Optional OTLP foundation demo
diff --git a/VERSION b/VERSION
index 6e8bf73..0ea3a94 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.0
+0.2.0
diff --git a/docs/AGENT-SESSION.md b/docs/AGENT-SESSION.md
index 311bc4f..e963b87 100644
--- a/docs/AGENT-SESSION.md
+++ b/docs/AGENT-SESSION.md
@@ -6,6 +6,14 @@ and makes fresh SDK evidence available to synchronous agent hooks. Service
monitoring and broader tracing workflows are later expansion; the OTLP watcher
remains a reusable foundation.
+## Registration alternative (0.2.0)
+
+For existing services, register reviewed contracts at application setup with
+`instrument(service, namespace=..., contracts=...)`, keeping business methods
+plain. [SDK registration](SDK-REGISTRATION.md) explains binding, scope and
+compatibility; the [runnable comparison](../examples/sdk-registration/README.md)
+includes Claude hooks. The original decorator session remains supported.
+
## What you review, and what the agent writes
1. **Approve intent once.** Put a small set of `Contract` objects in a Python
diff --git a/docs/RELEASE.md b/docs/RELEASE.md
index f4fb0c9..1470eb7 100644
--- a/docs/RELEASE.md
+++ b/docs/RELEASE.md
@@ -1,6 +1,21 @@
-# First release: 0.1.0 alpha
+# Releases and publishing
-## Scope and evidence
+## 0.2.0 alpha: registration and onboarding
+
+Version 0.2.0 mirrors TypeScript 0.2.0's explicit class/module
+registration and measured pilot, adapted to Python method binding and native
+decorators. ADR-0009 records the accepted integration recommendation.
+The wire schema remains 0.1.0 independently of the SDK version.
+
+Run `make ci`, `make demo`, `make demo-registration` and `make demo-pilot`.
+The distribution check installs the built wheel in a separate environment and
+executes the original session plus registration and synthetic pilot demos.
+CI verifies the same behavior across its Python/macOS/Linux matrix. Research
+and API boundaries are in [SDK-UX-RESEARCH.md](SDK-UX-RESEARCH.md) and
+[SDK-REGISTRATION.md](SDK-REGISTRATION.md). Human comfort/preference remains
+unmeasured; synthetic output verifies collection rather than adoption benefits.
+
+## 0.1.0 alpha: original scope and evidence
The primary product is a local AI coding-session supervisor: reviewed SDK
contracts, fresh execution after edits, required-check evidence, and synchronous
@@ -75,7 +90,8 @@ events do not automatically trigger another workflow with the default token.
## One-time registry setup (project owner)
-Configure a pending trusted publisher in **each** registry you intend to use:
+For the first PyPI upload, configure a pending trusted publisher on the owner's
+[PyPI account publishing page](https://pypi.org/manage/account/publishing/):
| Field | Value |
| --- | --- |
@@ -83,27 +99,37 @@ Configure a pending trusted publisher in **each** registry you intend to use:
| Owner | `melampus-org` |
| Repository | `melampus-python` |
| Workflow filename | `publish.yml` |
-| Environment | `testpypi` on TestPyPI; `pypi` on PyPI |
+| Environment | `pypi` |
-No long-lived PyPI token is required. Restrict the GitHub `pypi` environment to
-main and maintainers who may publish. See [PyPI's publisher setup](https://docs.pypi.org/trusted-publishers/adding-a-publisher/)
+No long-lived PyPI token is required. The GitHub `pypi` environment is configured
+to allow deployments from `main` only. See [PyPI's publisher setup](https://docs.pypi.org/trusted-publishers/adding-a-publisher/)
and [pending publishers](https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/).
These settings must exist before the first registry upload; the workflow cannot
-create ownership on your behalf.
+create the pending publisher on your behalf. A pending publisher creates the
+project on first upload and does not reserve the name in advance.
+
+As checked on 2026-10-02, TestPyPI's `melampus` project belongs to the unrelated
+`orfi2017/quantimage-melampus` project. Do not dispatch our `testpypi` upload under
+that name unless ownership is legitimately resolved. The two registries have
+independent ownership; TestPyPI's name collision does not establish PyPI ownership.
+Rehearsing under another name requires separately reviewed distribution metadata.
+The GitHub wheel's clean-environment install/repair checks remain available
+without a registry upload.
## Publish
1. Resolve review blockers, merge the version PR, and inspect the validated GitHub artifacts.
-2. Dispatch **Publish Python package** from `main`, with the existing tag and
- `registry=testpypi`. It validates tag ancestry/version, rebuilds and tests, and
- uploads from a separate job with only OIDC permission.
-3. Install the TestPyPI artifact with its `session` extra into a fresh environment
- and rerun the local agent-session demo and enabled Claude hook walkthrough.
- Download the exact project/version from TestPyPI without dependencies, then
- install that wheel with dependencies from the normal PyPI index; avoid combining
- indexes for general dependency resolution.
-4. Dispatch the same workflow with `registry=pypi`, then verify install, CLI and
- import from the real index. Update README's preparation notice after publication.
+2. Complete the PyPI pending publisher setup above. Dispatch **Publish Python
+ package** from `main`, with the existing tag and `registry=pypi`. It validates
+ tag ancestry/version, rebuilds and tests, and uploads from a separate job with
+ only OIDC permission. A missing publisher fails authentication and cannot
+ be repaired by creating GitHub tags or API tokens.
+3. Verify the exact version's wheel/sdist on PyPI, install the `session` extra
+ into a fresh environment, check CLI/import, and rerun the local session demos.
+4. TestPyPI remains an optional rehearsal after its name/ownership is resolved.
+ Download only the exact project's wheel without dependencies from TestPyPI,
+ then install it with dependencies from normal PyPI; do not combine indexes
+ for general dependency resolution.
Uploads are immutable. Fix a bad published package with a new patch release;
never attempt to overwrite an existing distribution filename.
diff --git a/docs/SDK-REGISTRATION.md b/docs/SDK-REGISTRATION.md
new file mode 100644
index 0000000..a4137d2
--- /dev/null
+++ b/docs/SDK-REGISTRATION.md
@@ -0,0 +1,153 @@
+# Choose the integration style that fits your code
+
+Version 0.2.0 adds `instrument` for existing service instances
+and module boundaries. The 0.1.0 artifact supports the existing function
+decorators. PyPI publication is separate from GitHub releases.
+
+| Your code | Start with | Main tradeoff |
+| --- | --- | --- |
+| A few functions you own | `@PRICE.instrument()` | Familiar decorator, one edit per function |
+| Existing service class | `instrument(service, ...)` | One explicit setup map; register each instance |
+| Plain module functions | Register a `SimpleNamespace` boundary | Business code stays plain; callers must use the boundary |
+| Third-party objects, frozen models, slots or dynamic proxies | Decorate a plain adapter function | More explicit glue; avoids surprising mutation |
+
+## Register a service once
+
+Reviewed `intent.py`:
+
+```python
+from melampus import Check, Contract
+
+PRICE = Contract(
+ intent="Return a nonnegative price in cents",
+ checks=(Check("nonnegative", lambda value: value >= 0, "Price is nonnegative."),),
+)
+CONTRACTS = {"pricing:PricingService.price": PRICE}
+```
+
+Plain `service.py`:
+
+```python
+class PricingService:
+ def price(self, cents: int) -> int:
+ return max(0, cents)
+```
+
+Application boundary `registration.py`:
+
+```python
+from melampus import instrument
+from intent import PRICE
+from service import PricingService
+
+pricing = instrument(
+ PricingService(),
+ namespace="pricing:PricingService",
+ contracts={"price": PRICE},
+ generator="claude-code",
+)
+pricing.price(-100)
+```
+
+The returned object is the same instance and retains its type. Bound method
+arguments, instance state, signatures, annotations and docstrings remain intact.
+Sync stays sync; async methods are evaluated after `await`. Method references
+captured **after** registration remain bound to the registered instance.
+
+Namespace `pricing` emits `pricing:price`; `pricing:PricingService` emits
+`pricing:PricingService.price`. Use stable reviewed paths, not instance IDs.
+`generator`, `policy` and `tracer` are shared keyword options. Each Contract
+owns its intent, assumptions and checks. Explicit `path=` is also available on
+`instrumented` and `Contract.instrument`; omitting it retains the 0.1.0 inferred path.
+
+## Group functions at an explicit module boundary
+
+```python
+from types import SimpleNamespace
+from melampus import instrument
+from functions import price, label
+from intent import PRICE
+
+pricing = instrument(
+ SimpleNamespace(price=price, label=label),
+ namespace="pricing",
+ contracts={"price": PRICE},
+)
+pricing.price(-100) # checked with a recording tracer
+pricing.label() # deliberately unconfigured
+price(-100) # original imported reference: no check
+```
+
+An actual Python module is supported too: `instrument(module, ...)` replaces
+selected module attributes. Existing `from module import price` references
+bypass that replacement. Later attribute/global lookups can reach the replacement,
+including module-internal calls. Prefer a `SimpleNamespace` boundary when you
+want mutation confined to a newly created object.
+
+## Scope is visible, never automatic
+
+| Call | Evidence |
+| --- | --- |
+| Registered instance's selected method | Checks its successful result |
+| `self.price(...)` on that instance | Reaches the installed wrapper |
+| Another unregistered instance | Uncovered |
+| Method/reference captured before registration | Uncovered |
+| `PricingService.price(instance, ...)` directly | Uncovered |
+| Omitted method | Unconfigured; no automatic discovery |
+| Required method not exercised in the scenario | Session incomplete (exit 2) |
+| A failure followed by a pass in the same scenario | Drift remains (exit 1) |
+
+Every required check must run; the session aggregates evidence by path, not by
+instance. Multiple instances may share a reviewed path if intent, assumptions
+and exact Check objects match. A conflicting declaration remains incomplete
+even if later registrations are valid. This is not per-instance coverage proof.
+
+Registration mutates selected instance/module attributes, never the class.
+Register before sharing the object across threads or handing references to a
+framework. Register each object once with its full map. Replacing its methods
+afterwards bypasses instrumentation; sessions report missing required evidence
+when their scenarios only reach the replacement.
+
+Supported targets are ordinary writable Python objects, modules and
+`SimpleNamespace`; selected members must be Python functions or bound methods.
+Inherited methods and instance-owned function fields are supported. Properties,
+custom descriptors, private/dunder names, class/static methods, class objects,
+custom attribute hooks, slot-only/frozen objects and generators fail explicitly.
+All entries are validated before mutation. No property getter runs during
+method discovery. Registration is not a sandbox for arbitrary objects.
+
+Unlike TypeScript's mapped member types, Python's `Mapping[str, Contract]` cannot
+statically validate arbitrary method names or predicate return types. Typos fail
+at registration; `instrument` preserves the target type and function decorators
+preserve parameter/return types. Predicates still must return exactly `bool`.
+
+The core SDK remains OpenTelemetry API-only. Ordinary applications own provider
+and export setup; checks need recording spans. Local `melampus session` owns an
+always-on provider in each fresh scenario process. No arguments, returned
+values, intent prose or exception text are exported. Failures preserve results;
+application exceptions and cancellation propagate unchanged. Wire schema stays
+at **0.1.0**. Registration does not add argument/state predicates or prove
+unexercised behavior; no new performance guarantee is claimed.
+
+## Try it beside an agent
+
+```sh
+uv sync --locked --all-extras
+make demo-registration
+source .venv/bin/activate
+cd examples/sdk-registration
+melampus session
+```
+
+In another terminal, activate the same environment, enter the same example
+directory, and start Claude Code with the supplied project hooks enabled.
+Ask it to edit `service.py` while preserving registration and reviewed intent.
+The supervisor detects edits; hooks block progression/completion on drift or
+missing evidence and permit scoped repair. Other automation can call
+`melampus gate` and use its 0/1/2 exits. See [session setup](AGENT-SESSION.md).
+
+Run `make demo-pilot` to validate collection across decorator/class/module
+styles. Run `make pilot ARGS='--participant p01 --rotation 0'` to collect
+participant feedback. See the [pilot guide](../examples/pilot_study/README.md)
+and [design research](SDK-UX-RESEARCH.md). Familiar APIs and lower edit counts
+are design hypotheses; human comfort and preference require actual participants.
diff --git a/docs/SDK-UX-RESEARCH.md b/docs/SDK-UX-RESEARCH.md
new file mode 100644
index 0000000..8938fe1
--- /dev/null
+++ b/docs/SDK-UX-RESEARCH.md
@@ -0,0 +1,72 @@
+# Python SDK onboarding: evidence and design decisions
+
+The project owner accepted ADR-0009 on 2026-10-02 for version 0.2.0: native
+decorators for a few functions, explicit registration for existing services.
+This accepts the design recommendation; human comfort and preference remain
+unmeasured until participant feedback is collected.
+
+Research date: 2026-10-01. This comparison uses official documentation and the
+TypeScript [0.2.0 alpha release](https://github.com/melampus-org/melampus-typescript/releases/tag/v0.2.0),
+commit `2af85ad82db624e0c32cdfe54116f57f3789d7db`. It evaluates interaction
+patterns; it does not claim adoption rankings or measured Melampus preference.
+
+## Familiarity reduces the concepts users must learn
+
+| Reference | Documented pattern | Melampus design inference | Tradeoff |
+| --- | --- | --- | --- |
+| [OpenTelemetry Python](https://opentelemetry.io/docs/languages/python/instrumentation/) | Function decorators/context managers; libraries depend on the API, applications configure the SDK | Retain decorators and API-only core; the local session supplies tracing automatically | Plain SDK usage still requires a recording provider |
+| [OpenTelemetry FastAPI instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/fastapi/fastapi.html) | `instrument_app(app)` registers an existing application | Offer explicit per-service registration at composition time | We instrument selected business members, not framework traffic automatically |
+| [Pydantic validate_call](https://docs.pydantic.dev/latest/concepts/validation_decorator/) | Decorator supports async functions and parameter forms; return validation is optional; input coercion is default | Preserve call signatures, typing and async behavior; clearly state what checks observe | Melampus neither parses inputs nor coerces results; it records reviewed predicate outcomes |
+| [AWS Powertools Tracer](https://docs.aws.amazon.com/powertools/python/latest/core/tracer/) | Shared tracer plus `capture_method`; response capture is configurable and default-on | Keep one setup object/map and small decorator examples; expose privacy behavior early | Melampus exports bounded check metadata and hashes, not response content |
+| [icontract](https://icontract.readthedocs.io/en/latest/api.html) | `require`/`ensure` decorators; postconditions can refer to result and arguments | Keep reviewed, named claims separate and explain them in terms of executable postconditions | Melampus currently checks results only and gates agent progression; it does not implement all design-by-contract semantics |
+| [wrapt](https://wrapt.readthedocs.io/en/master/decorators.html) | Dedicated binding/introspection semantics for functions and methods | Treat binding and signatures as behavior to test; reject unsupported descriptors explicitly | No broad proxy/decorator compatibility claim; use adapters for exotic objects |
+| [FastAPI dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) | Compose application dependencies via explicit callables | Register services before handing them to framework handlers/dependency factories | Register before the framework captures a reference; no FastAPI dependency is added |
+
+These are inferred choices from documented patterns. A familiar surface is a
+reasonable starting point, but it is not evidence that participants prefer it.
+
+## Recommendation: two entry points, one contract model
+
+For a small function, use `@PRICE.instrument()`: it is discoverable beside the
+code, retains the original inferred path and requires no service abstraction.
+For an existing service or function group, use
+`instrument(target, namespace=..., contracts=...)`: business methods stay plain,
+the reviewed map is visible at application setup, and the same object is returned.
+
+Avoid a new base class, global auto-patching, metaclass, class replacement,
+framework dependency or automatic discovery of business intent. Those mechanisms
+would make scope and side effects harder to explain. Keep explicit member names
+and stable paths even though they require a setup map. Keep decorators as a
+first-class alternative; Python already has native decorator syntax, unlike the
+Node type-stripping constraint behind the TypeScript release's decorator deferral.
+
+## Comfort criteria we can verify now
+
+| Concern | Implementation/verification |
+| --- | --- |
+| Will it change my calls? | Tests preserve sync/async, arguments, method binding, signatures, docstrings, identity and exception propagation |
+| Do I need to rewrite business code? | Class/module-boundary reference integrations edit only entry.py; decorator integration edits business.py |
+| What is actually covered? | Examples explicitly exercise captured references, unregistered instances and omitted members; missing required execution yields exit 2 |
+| Does a passing instance hide a failing one? | Fresh-process tests retain drift and conflicting declarations across shared paths |
+| Does it leak values? | Existing hash/metadata-only telemetry behavior remains; no new content export path |
+| Can I undo adoption? | Remove the setup registration or decorators and restart with an owner-reviewed registry; current session deliberately reports missing evidence |
+| Can I try it without cloud accounts? | Demos need no LLM request/backend; participant study stays local |
+
+The zero-business-edit metric excludes registration edits and is not zero setup
+effort. Both approaches still need reviewed claims, exercise inputs and local
+session configuration. A strong unit test can catch the same predicate failure;
+the supervisor adds automatic replay, required evidence and agent hook decisions.
+See [test/CI comparison](AGENT-SESSION.md).
+
+## What needs human evidence
+
+Use the [counterbalanced pilot](../examples/pilot_study/README.md) to collect
+seven worksheet measures: first passing gate time, business-code edits, time to
+add a second method, coverage understanding, diagnosis/repair, confusion and
+explicit preference/reason. Rotate all six style orders to reduce order bias.
+Keep environment setup outside the integration timer and apply equal assistance.
+
+Synthetic tests validate measurement, gates and reporting. They cannot establish
+comfort, human onboarding time or which API is best. Review actual participant
+comments as well as timing. Revise onboarding before introducing a class decorator
+or framework adapter; add one only if feedback identifies a repeated unmet need.
diff --git a/docs/adr/0009-explicit-sdk-registration.md b/docs/adr/0009-explicit-sdk-registration.md
new file mode 100644
index 0000000..1d48452
--- /dev/null
+++ b/docs/adr/0009-explicit-sdk-registration.md
@@ -0,0 +1,38 @@
+# ADR-0009: Explicit registration with native decorator compatibility
+
+Status: accepted for 0.2.0 (2026-10-02), confirmed by the project owner.
+
+## Context
+
+TypeScript 0.2.0 alpha moves SDK setup to a selected-member registration map and
+adds a measured pilot. Python has native decorators and different method binding,
+module mutation and typing semantics. Port the workflow, not JavaScript mechanics.
+See [official-source research](../SDK-UX-RESEARCH.md).
+
+## Decision
+
+Add `instrument(target, *, namespace, contracts, generator, policy, tracer)` for
+ordinary instances, modules and SimpleNamespace boundaries. Return the same typed
+object, wrap only selected functions and bound methods, preserve sync/async and
+introspection, and never mutate shared classes. Validate the entire plan before
+writing. Reject descriptors/dynamic or immutable objects explicitly. Retain
+`instrumented` and `Contract.instrument`; allow optional stable `path=` on both.
+
+Allow repeated matching declarations for shared reviewed paths; retain conflicts
+and all failures. Sessions require each reviewed check to execute, not every
+instance. Retain the 0.1.0 wire schema and API-only core dependency model.
+
+Port the three-style demo and local, timed, resumable, counterbalanced pilot with
+Markdown/CSV/JSON reports. Mark synthetic output separately. Human preference
+and comfort remain unmeasured until actual participants supply feedback.
+
+## Consequences
+
+Class/grouped-function integration can leave business code plain. Captured raw
+references, direct class calls, omitted members and unregistered instances bypass
+registration. In-place changes are observable; register once before sharing.
+Python typing preserves the target but cannot verify arbitrary string member
+maps or predicate result types. Frozen/slot-only/framework models need a plain
+adapter or existing decorators. Framework-wide and class-decorator APIs are
+deferred pending feedback. The existing decorator agent demo and recorded 0.1.0
+walkthrough remain reproducible compatibility examples.
diff --git a/examples/pilot_study/README.md b/examples/pilot_study/README.md
new file mode 100644
index 0000000..b583cc3
--- /dev/null
+++ b/examples/pilot_study/README.md
@@ -0,0 +1,106 @@
+# Timed Python SDK integration pilot
+
+This ports the TypeScript 0.2.0 pilot to native Python decorators, class instances
+and grouped module functions. It collects feedback locally with the participant's
+usual editor and uses fresh Melampus scenarios to verify task completion.
+
+## Validate the collection workflow
+
+```sh
+uv sync --locked --all-extras
+make demo-pilot
+```
+
+This is a **synthetic walkthrough**, not human feedback. It supplies scripted
+edits, answers and notes for all styles and checks detection/block/repair.
+Reports under `pilot-results/demo-.../` say SYNTHETIC; their timings cannot
+establish human onboarding speed or comfort.
+
+## Run with a participant
+
+```sh
+make pilot ARGS='--participant p01 --rotation 0'
+# Optional persistent directory:
+make pilot ARGS='--participant p01 --rotation 0 --dir /path/to/p01-study'
+```
+
+Python/session dependencies must already be installed in the same environment.
+Environment installation is outside the timers. Task time starts when integration
+instructions appear and includes reading, edits and gate evaluation. This measures
+integration into a prepared service, not machine setup.
+
+Open the printed style directory in the participant's editor. Type `check` after
+editing or `pause` at any prompt; Ctrl+C/EOF also saves and pauses. Repeat the
+same command/options to resume. One-second checkpoints retain active timing;
+an unexpected termination excludes downtime, records an interruption and can
+lose up to one second since the last checkpoint. Verify an earlier process stopped
+before removing a stale `.lock`. One runner owns each directory. A completed
+study remains completed; use a new participant ID/directory for another trial.
+
+Use pseudonymous IDs. Nothing is uploaded. `pilot-results/` is Git-ignored.
+Review free-text responses before sharing them. Treat test/demo-generated
+responses as scripted data even when exercising participant mode in tests.
+
+## Every worksheet measure has a task
+
+| Measure | Participant task | Stored evidence |
+| --- | --- | --- |
+| Minutes to first passing gate | Instrument only price | Active milliseconds/minutes and all gate attempts |
+| Business-code lines changed | Submit the first passing business.py | Added/deleted lines, total and submitted snapshot |
+| Minutes to second checked method | Add discount after first pass | Separate timer, attempts and incremental business diff |
+| Covered/uncovered calls recognized | Answer six scope questions | Answer, ground truth, correctness and score |
+| Understand and repair a failure | Diagnose seeded negative-price drift and repair it | Cause score, explanation, drift, blocked Stop, attempts and fresh gate 0 |
+| Setup/error confusion | Answer three prompts per style | Setup, second-method and error-message notes; `none` is valid |
+| Preferred style and reason | Compare after all three styles | Explicit wrapper/class/module/no-preference and free-text reason |
+
+The fixture calls price, discount and label on inputs -100, 0 and 250. Price is
+initially the only required path. After first pass the harness extends reviewed
+intent with discount. Label stays unconfigured. Adding discount early, checking
+label or duplicate wrappers fails the task protocol even when the SDK gate is
+healthy; reports retain SDK exit separately. Modifying reviewed intent/scenario/
+configuration cannot pass a task. Keep the supplied business formulas throughout
+integration; the runner changes price later for the repair task.
+
+Wrapper style edits `business.py` with `@PRICE.instrument(path="pilot:price")`
+and later `@DISCOUNT.instrument(path="pilot:discount")`. Class style edits
+`entry.py` using `instrument(api, namespace="pilot:PricingService", ...)`.
+Module style edits `entry.py` using `instrument(api, namespace="pilot", ...)`.
+Import `instrument` from `melampus` and reviewed contracts from `intent.py`.
+
+Business-line counts use literal additions + deletions: a replacement counts as
+two lines; formatting changes count; CRLF/LF differences do not. Registration
+edits in entry.py are excluded, so zero business edits **is not zero setup effort**.
+All styles share claims, inputs, runtime and checkpoints. The first gate's
+submitted business snapshot anchors the second-method diff.
+
+## Balance learning effects
+
+Assign successive participants rotations 0–5, then repeat:
+
+| Rotation | First | Second | Third |
+| --- | --- | --- | --- |
+| 0 | wrapper | class | module |
+| 1 | wrapper | module | class |
+| 2 | class | wrapper | module |
+| 3 | class | module | wrapper |
+| 4 | module | wrapper | class |
+| 5 | module | class | wrapper |
+
+This balances order across six participants but cannot eliminate learning effects.
+Apply the same help policy and record facilitator assistance in the notes.
+Participants may consult [API documentation](../../docs/SDK-REGISTRATION.md).
+The cause-choice score measures basic diagnosis; review the explanation for
+deeper understanding. Wrong answers remain wrong after a successful repair.
+
+## Reports and interpretation
+
+- `feedback.md`: worksheet with pending cells empty and mode prominently labeled.
+- `feedback.csv`: one row per style, including identity, mode, rotation, status,
+ all measures, confusion and preference. Filter completed participant studies
+ and exclude scripted/test runs before analyzing human usability.
+- `study.json`: full resumable state, attempts, timing, snapshots, quiz answers,
+ diagnosis, interruptions and preference.
+
+Preference is supplied by a participant and never inferred from speed/edit count.
+Incomplete studies remain incomplete. Synthetic runs validate collection; actual
+human participation is required to conclude which API feels comfortable.
diff --git a/examples/pilot_study/__init__.py b/examples/pilot_study/__init__.py
new file mode 100644
index 0000000..2961e14
--- /dev/null
+++ b/examples/pilot_study/__init__.py
@@ -0,0 +1 @@
+"""Local, resumable comparison of Python SDK integration styles."""
diff --git a/examples/pilot_study/cli.py b/examples/pilot_study/cli.py
new file mode 100644
index 0000000..53d6787
--- /dev/null
+++ b/examples/pilot_study/cli.py
@@ -0,0 +1,198 @@
+"""Run a participant pilot or an explicitly synthetic collection walkthrough."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import threading
+from datetime import UTC, datetime
+from pathlib import Path
+
+from .fixtures import coverage_questions, path_for, solution
+from .study import PilotStudy
+
+
+def run_synthetic(study: PilotStudy) -> None:
+ if (
+ study.data["mode"] != "synthetic"
+ or study.data["stage"] != "setup"
+ or study.data["index"] != 0
+ ):
+ raise ValueError("Synthetic walkthrough requires a new synthetic study.")
+ while study.data["stage"] != "preference":
+ style = study.style
+ study.start_timer()
+ assert study.check()["exit_code"] == 2
+ solution(study.folder, style, False)
+ assert study.check()["exit_code"] == 0
+ study.start_timer()
+ assert study.check()["exit_code"] == 2
+ solution(study.folder, style, True)
+ assert study.check()["exit_code"] == 0
+ study.answer_coverage([q["expected"] for q in coverage_questions(style)])
+ drift = study.introduce_drift()
+ assert drift["report"]["exit_code"] == 1 and drift["blocked"]
+ study.answer_diagnosis(
+ "result", "Scripted: min returns a negative price for negative input."
+ )
+ study.start_timer()
+ assert study.check()["exit_code"] == 1
+ source = study.folder / "business.py"
+ source.write_text(source.read_text().replace("min(0, cents)", "max(0, cents)", 1))
+ assert study.check()["exit_code"] == 0
+ study.feedback(
+ dict.fromkeys(("setup", "second", "errors"), "Scripted walkthrough; no human feedback.")
+ )
+ print(
+ f"{style}: setup, second method, coverage quiz, diagnosis, blocked drift, repair, notes recorded"
+ )
+ study.finish("no-preference", "Synthetic collection test; no human preference is measured.")
+
+
+def run_participant(study: PilotStudy) -> None:
+ stop = threading.Event()
+
+ def checkpoint() -> None:
+ while not stop.wait(1):
+ study.tick()
+
+ def ask(prompt: str, choices: tuple[str, ...] = ()) -> str:
+ while True:
+ answer = input(prompt + "\n> ").strip()
+ if answer.lower() == "pause":
+ raise EOFError
+ if answer and len(answer) <= 4000 and (not choices or answer in choices):
+ return answer
+ print(
+ "Choose " + " / ".join(choices)
+ if choices
+ else "Enter up to 4000 characters, or pause."
+ )
+
+ worker = threading.Thread(target=checkpoint, daemon=True)
+ worker.start()
+ try:
+ print(f"Participant {study.data['participant']}; order: {' → '.join(study.data['order'])}.")
+ print(
+ "Use your usual editor. Type pause or Ctrl+C to save and exclude downtime. Preserve formulas/reviewed files. All results stay local."
+ )
+ while study.data["stage"] != "done":
+ stage = study.data["stage"]
+ if stage in {"setup", "second", "repair"}:
+ print(f"\n{study.style}: {stage}. Edit {study.folder}")
+ if stage == "setup":
+ print(
+ f"Register only price with PRICE from intent.py; path {path_for(study.style, 'price')}. For wrapper use @PRICE.instrument(path=...) in business.py. For class/module import instrument from melampus and register api in entry.py. Leave discount and label unregistered."
+ )
+ elif stage == "second":
+ print(
+ f"Add DISCOUNT; both price and {path_for(study.style, 'discount')} are now required. Preserve formulas, leave label unconfigured."
+ )
+ else:
+ print(
+ "Repair the failing price formula, keep both contracts/integrations, obtain a fresh gate 0."
+ )
+ study.start_timer()
+ ask("After editing, enter check to evaluate, or pause.", ("check",))
+ report = study.check()
+ print(f"Gate {report['exit_code']}: {json.dumps(report)}")
+ elif stage == "coverage":
+ print(
+ "Assume a recording tracer. covered/uncovered describe calls; incomplete/drift describe gates."
+ )
+ answers = [
+ ask(q["prompt"], ("covered", "uncovered", "incomplete", "drift"))
+ for q in coverage_questions(study.style)
+ ]
+ study.answer_coverage(answers)
+ print("Answers saved; scores available after the study.")
+ elif stage == "diagnosis":
+ print(json.dumps(study.introduce_drift(), indent=2))
+ cause = ask(
+ "Cause? result = predicate violated; network = transport problem; missing = method not exercised.",
+ ("result", "network", "missing"),
+ )
+ explanation = ask(
+ "Explain the failing behavior in your own words before repairing it."
+ )
+ study.answer_diagnosis(cause, explanation)
+ elif stage == "feedback":
+ notes = {
+ key: ask(prompt + " Enter none if nothing.")
+ for key, prompt in (
+ ("setup", "What confused you in setup?"),
+ ("second", "What confused you adding the second method?"),
+ ("errors", "Were failure messages understandable? Describe any confusion."),
+ )
+ }
+ study.feedback(notes)
+ elif stage == "preference":
+ style = ask(
+ "Which style would you use in your own project?",
+ ("wrapper", "class", "module", "no-preference"),
+ )
+ study.finish(style, ask("Why? Explain comfort, readability and setup tradeoffs."))
+ else:
+ raise ValueError("Unknown study stage.")
+ except (KeyboardInterrupt, EOFError):
+ print("\nPaused; repeat the same command to resume.")
+ finally:
+ stop.set()
+ worker.join()
+ study.pause()
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--participant", help="pseudonymous ID; repeat the same options to resume")
+ parser.add_argument("--rotation", type=int, choices=range(6), default=0)
+ parser.add_argument("--dir", type=Path)
+ parser.add_argument(
+ "--demo", action="store_true", help="synthetic collection test, not usability evidence"
+ )
+ args = parser.parse_args()
+ participant = args.participant or (
+ "demo-" + datetime.now(UTC).strftime("%Y%m%dT%H%M%S%f") if args.demo else None
+ )
+ if participant is None:
+ parser.error("provide --participant ID, or --demo")
+ # Validate identity before using it in a filesystem path.
+ import re
+
+ if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", participant):
+ parser.error("participant ID must be 1–64 letters/digits/_/-")
+ directory = (args.dir or Path("pilot-results") / participant).resolve()
+ directory.parent.mkdir(parents=True, exist_ok=True)
+ lock = directory.with_name(directory.name + ".lock")
+ try:
+ descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ parser.error(
+ f"runner lock exists: {lock}; verify the earlier runner stopped before removing a stale lock"
+ )
+ try:
+ os.close(descriptor)
+ study = PilotStudy(
+ directory,
+ participant=participant,
+ rotation=args.rotation,
+ mode="synthetic" if args.demo else "participant",
+ )
+ if args.demo:
+ print(
+ "SYNTHETIC WALKTHROUGH: automated timings/answers are not human usability evidence."
+ )
+ run_synthetic(study)
+ else:
+ run_participant(study)
+ study.write_reports()
+ print(
+ f"Study {study.data['stage']}. Reports: {directory}/feedback.md, feedback.csv, study.json"
+ )
+ finally:
+ lock.unlink(missing_ok=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/pilot_study/fixtures.py b/examples/pilot_study/fixtures.py
new file mode 100644
index 0000000..ad11c17
--- /dev/null
+++ b/examples/pilot_study/fixtures.py
@@ -0,0 +1,154 @@
+from pathlib import Path
+
+STYLES = ("wrapper", "class", "module")
+ORDERS = (
+ ("wrapper", "class", "module"),
+ ("wrapper", "module", "class"),
+ ("class", "wrapper", "module"),
+ ("class", "module", "wrapper"),
+ ("module", "wrapper", "class"),
+ ("module", "class", "wrapper"),
+)
+
+
+def namespace(style: str) -> str:
+ return "pilot:PricingService" if style == "class" else "pilot"
+
+
+def path_for(style: str, method: str) -> str:
+ return f"{namespace(style)}{'.' if style == 'class' else ':'}{method}"
+
+
+def business(style: str) -> str:
+ if style == "class":
+ return """class PricingService:
+ def price(self, cents: int) -> int:
+ return max(0, cents)
+
+ def discount(self, cents: int) -> int:
+ return max(0, cents) * 9 // 10
+
+ def label(self) -> str:
+ return "cents"
+"""
+ return """def price(cents: int) -> int:
+ return max(0, cents)
+
+
+def discount(cents: int) -> int:
+ return max(0, cents) * 9 // 10
+
+
+def label() -> str:
+ return "cents"
+"""
+
+
+def entry(style: str) -> str:
+ if style == "class":
+ return "from business import PricingService\n\napi = PricingService()\n"
+ return "from types import SimpleNamespace\nfrom business import price, discount, label\n\napi = SimpleNamespace(price=price, discount=discount, label=label)\n"
+
+
+def reviewed(style: str, second: bool) -> dict[str, str]:
+ registry = repr(path_for(style, "price")) + ": PRICE"
+ if second:
+ registry += ", " + repr(path_for(style, "discount")) + ": DISCOUNT"
+ return {
+ "intent.py": """from melampus import Check, Contract
+
+PRICE = Contract("Return a nonnegative price", (Check("nonnegative", lambda n: type(n) is int and n >= 0, "Price is a nonnegative integer"),))
+DISCOUNT = Contract("Return a nonnegative integer discounted price", (Check("integer", lambda n: type(n) is int and n >= 0, "Discount is a nonnegative integer"),))
+CONTRACTS = {"""
+ + registry
+ + "}\n",
+ "exercise.py": """from entry import api
+
+for cents in (-100, 0, 250):
+ api.price(cents)
+ api.discount(cents)
+ api.label()
+""",
+ "melampus.toml": 'contracts = "intent"\nprobe = "exercise.py"\nwatch = ["business.py", "entry.py"]\ntimeout = 5\n',
+ }
+
+
+def install_reviewed(root: Path, style: str, second: bool) -> None:
+ for name, content in reviewed(style, second).items():
+ (root / name).write_text(content)
+
+
+def solution(root: Path, style: str, second: bool) -> None:
+ """Reference solution used only by synthetic collection checks."""
+ imports = "from intent import PRICE" + (", DISCOUNT" if second else "") + "\n"
+ if style == "wrapper":
+ source = business(style).replace(
+ "def price(", '@PRICE.instrument(path="pilot:price")\ndef price('
+ )
+ if second:
+ source = source.replace(
+ "def discount(", '@DISCOUNT.instrument(path="pilot:discount")\ndef discount('
+ )
+ (root / "business.py").write_text(imports + "\n" + source)
+ else:
+ source = entry(style)
+ target = (
+ "PricingService()"
+ if style == "class"
+ else "SimpleNamespace(price=price, discount=discount, label=label)"
+ )
+ source = source.replace(
+ "api = " + target,
+ "from melampus import instrument\n"
+ + imports
+ + "\napi = instrument("
+ + target
+ + f", namespace={namespace(style)!r}, contracts={{'price': PRICE"
+ + (", 'discount': DISCOUNT" if second else "")
+ + "})",
+ )
+ (root / "entry.py").write_text(source)
+
+
+def seed_drift(root: Path) -> None:
+ file = root / "business.py"
+ source = file.read_text()
+ if "return max(0, cents)" not in source:
+ raise ValueError("Restore the original price expression before the drift task.")
+ file.write_text(source.replace("return max(0, cents)", "return min(0, cents)", 1))
+
+
+def coverage_questions(style: str) -> list[dict[str, str]]:
+ boundary = {
+ "class": "new PricingService().price(-100) on an UNREGISTERED instance",
+ "module": "calling price imported directly from business.py before registration",
+ "wrapper": "calling the raw implementation via __wrapped__ instead of the wrapper",
+ }
+ return [
+ {
+ "id": "registered",
+ "prompt": "api.price(-100), after integration, with a recording tracer",
+ "expected": "covered",
+ },
+ {
+ "id": "omitted",
+ "prompt": "api.label(), which has no configured contract",
+ "expected": "uncovered",
+ },
+ {
+ "id": "captured",
+ "prompt": "Calling a raw price reference captured BEFORE wrapping",
+ "expected": "uncovered",
+ },
+ {"id": "boundary", "prompt": boundary[style], "expected": "uncovered"},
+ {
+ "id": "missing",
+ "prompt": "Required price AND discount, but only price is exercised. Gate?",
+ "expected": "incomplete",
+ },
+ {
+ "id": "aggregate",
+ "prompt": "Price fails once and passes later in the same scenario. Gate?",
+ "expected": "drift",
+ },
+ ]
diff --git a/examples/pilot_study/study.py b/examples/pilot_study/study.py
new file mode 100644
index 0000000..8273275
--- /dev/null
+++ b/examples/pilot_study/study.py
@@ -0,0 +1,421 @@
+"""Local measurement harness; synthetic answers never count as human feedback."""
+
+from __future__ import annotations
+
+import csv
+import json
+import re
+import threading
+import time
+from collections.abc import Callable
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from melampus.session import Supervisor, hook_decision
+
+from .fixtures import (
+ ORDERS,
+ STYLES,
+ business,
+ coverage_questions,
+ entry,
+ install_reviewed,
+ reviewed,
+ seed_drift,
+)
+
+
+def response(value: str) -> str:
+ if not isinstance(value, str) or not value.strip() or len(value) > 4000:
+ raise ValueError("Provide a nonempty response of at most 4000 characters.")
+ return value.strip()
+
+
+def changed_lines(before: str, after: str) -> dict[str, int]:
+ """LCS additions/deletions; replacement = two lines, CRLF is normalized."""
+
+ def lines(value: str) -> list[str]:
+ return [] if not value else value.replace("\r\n", "\n").removesuffix("\n").split("\n")
+
+ a, b = lines(before), lines(after)
+ if max(len(a), len(b)) > 2000:
+ raise ValueError("Pilot business file exceeds 2000 lines.")
+ previous = [0] * (len(b) + 1)
+ for line in a:
+ current = [0]
+ for j, other in enumerate(b, 1):
+ current.append(previous[j - 1] + 1 if line == other else max(previous[j], current[-1]))
+ previous = current
+ common = previous[-1]
+ return {
+ "added": len(b) - common,
+ "deleted": len(a) - common,
+ "total": len(a) + len(b) - 2 * common,
+ }
+
+
+class PilotStudy:
+ def __init__(
+ self,
+ directory: Path,
+ *,
+ participant: str,
+ rotation: int = 0,
+ mode: str = "participant",
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ if (
+ not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", participant)
+ or type(rotation) is not int
+ or not 0 <= rotation < 6
+ or mode not in {"participant", "synthetic"}
+ ):
+ raise ValueError("Use a pseudonymous ID, rotation 0–5 and participant/synthetic mode.")
+ self.root = directory.resolve()
+ self.file = self.root / "study.json"
+ self.clock = clock
+ self.last_tick: float | None = None
+ self.lock = threading.RLock()
+ if self.file.is_file():
+ self.data = json.loads(self.file.read_text())
+ if any(
+ self.data.get(k) != v
+ for k, v in {
+ "schema": 1,
+ "participant": participant,
+ "rotation": rotation,
+ "mode": mode,
+ }.items()
+ ):
+ raise ValueError(
+ "Resume with the original identity, rotation and mode, or use a new directory."
+ )
+ if self.data.get("timer", {}) and self.data["timer"]["running"]:
+ self.data["timer"]["running"] = False
+ self.data["interruptions"] += 1
+ else:
+ if self.root.exists():
+ raise ValueError("Refusing to overwrite a directory without study.json.")
+ self.root.mkdir(parents=True)
+ self.data: dict[str, Any] = {
+ "schema": 1,
+ "participant": participant,
+ "rotation": rotation,
+ "mode": mode,
+ "created_at": datetime.now(UTC).isoformat(),
+ "order": ORDERS[rotation],
+ "index": 0,
+ "stage": "setup",
+ "timer": None,
+ "interruptions": 0,
+ "results": {},
+ "preference": None,
+ }
+ for style in STYLES:
+ folder = self.root / style
+ folder.mkdir()
+ (folder / "business.py").write_text(business(style))
+ (folder / "entry.py").write_text(entry(style))
+ install_reviewed(folder, style, False)
+ self.data["results"][style] = {
+ **{
+ task: {"passed": False, "elapsed_ms": None, "attempts": []}
+ for task in ("setup", "second", "repair")
+ },
+ "integration_business_lines": None,
+ "second_business_lines": None,
+ "coverage": None,
+ "diagnosis": None,
+ "confusion": None,
+ }
+ self.write_reports()
+
+ @property
+ def style(self) -> str:
+ return str(self.data["order"][self.data["index"]])
+
+ @property
+ def folder(self) -> Path:
+ return self.root / self.style
+
+ @property
+ def result(self) -> dict[str, Any]:
+ return dict_or_raise(self.data["results"][self.style])
+
+ def expect(self, stage: str) -> None:
+ if self.data["stage"] != stage:
+ raise ValueError(f"Expected {stage}; study is at {self.data['stage']}.")
+
+ def save(self) -> None:
+ with self.lock:
+ temporary = self.file.with_suffix(".tmp")
+ temporary.write_text(json.dumps(self.data, indent=2) + "\n")
+ temporary.replace(self.file)
+
+ def tick(self) -> None:
+ with self.lock:
+ timer = self.data["timer"]
+ if self.last_tick is not None and timer and timer["running"]:
+ now = self.clock()
+ timer["elapsed_ms"] += max(0, now - self.last_tick) * 1000
+ self.last_tick = now
+ self.save()
+
+ def start_timer(self) -> None:
+ with self.lock:
+ if self.data["stage"] not in {"setup", "second", "repair"}:
+ raise ValueError("This task is not timed.")
+ if self.data["timer"] is None:
+ self.data["timer"] = {"task": self.data["stage"], "elapsed_ms": 0, "running": False}
+ if not self.data["timer"]["running"]:
+ self.last_tick = self.clock()
+ self.data["timer"]["running"] = True
+ self.save()
+
+ def stop_timer(self) -> int:
+ self.tick()
+ elapsed = round(self.data["timer"]["elapsed_ms"])
+ self.data["timer"] = None
+ self.last_tick = None
+ return elapsed
+
+ def pause(self) -> None:
+ with self.lock:
+ self.tick()
+ if self.data["timer"]:
+ self.data["timer"]["running"] = False
+ self.last_tick = None
+ self.write_reports()
+
+ def check(self) -> dict[str, Any]:
+ stage = self.data["stage"]
+ if (
+ stage not in {"setup", "second", "repair"}
+ or not self.data["timer"]
+ or not self.data["timer"]["running"]
+ ):
+ raise ValueError("Start a timed task before checking.")
+ second = stage != "setup"
+ try:
+ changed = [
+ name
+ for name, content in reviewed(self.style, second).items()
+ if (self.folder / name).read_text() != content
+ ]
+ report = (
+ {
+ "exit_code": 2,
+ "protected_changed": changed,
+ "message": "Restore the reviewed study files before checking.",
+ }
+ if changed
+ else Supervisor(self.folder / "melampus.toml").check()
+ )
+ except (OSError, ValueError, TypeError):
+ report = {"exit_code": 2, "message": "Unable to load study files."}
+ if report["exit_code"] == 0 and report.get("checks", {}).get("passed") != (
+ 6 if second else 3
+ ):
+ report = {
+ **report,
+ "sdk_exit_code": 0,
+ "exit_code": 2,
+ "task_error": "unexpected_check_count",
+ "message": "Register only price in setup; then price and discount. Leave label unconfigured and avoid duplicate wrappers.",
+ }
+ with self.lock:
+ self.tick()
+ self.result[stage]["attempts"].append(
+ {
+ "exit_code": report["exit_code"],
+ "sdk_exit_code": report.get("sdk_exit_code", report["exit_code"]),
+ "elapsed_ms": round(self.data["timer"]["elapsed_ms"]),
+ "report": report,
+ }
+ )
+ if report["exit_code"] == 0:
+ submitted = (self.folder / "business.py").read_text()
+ diff = changed_lines(
+ self.result["setup_business_snapshot"]
+ if stage == "second"
+ else business(self.style),
+ submitted,
+ )
+ self.result[stage].update(passed=True, elapsed_ms=self.stop_timer())
+ if stage == "setup":
+ self.result["integration_business_lines"] = diff
+ self.result["setup_business_snapshot"] = submitted
+ install_reviewed(self.folder, self.style, True)
+ self.data["stage"] = "second"
+ elif stage == "second":
+ self.result["second_business_lines"] = diff
+ self.data["stage"] = "coverage"
+ else:
+ self.data["stage"] = "feedback"
+ self.write_reports()
+ return report
+
+ def answer_coverage(self, answers: list[str]) -> None:
+ with self.lock:
+ self.expect("coverage")
+ questions = coverage_questions(self.style)
+ if len(answers) != len(questions) or any(
+ a not in {"covered", "uncovered", "incomplete", "drift"} for a in answers
+ ):
+ raise ValueError(
+ "Answer all coverage questions with covered/uncovered/incomplete/drift."
+ )
+ items = [
+ {**q, "answer": a, "correct": a == q["expected"]}
+ for q, a in zip(questions, answers, strict=True)
+ ]
+ self.result["coverage"] = {
+ "correct": sum(i["correct"] for i in items),
+ "total": len(items),
+ "items": items,
+ }
+ self.data["stage"] = "diagnosis"
+ self.write_reports()
+
+ def introduce_drift(self) -> dict[str, Any]:
+ self.expect("diagnosis")
+ if self.result.get("drift"):
+ return dict_or_raise(self.result["drift"])
+ if not self.result.get("drift_seeded"):
+ seed_drift(self.folder)
+ self.result["drift_seeded"] = True
+ self.save()
+ supervisor = Supervisor(self.folder / "melampus.toml")
+ report = supervisor.check()
+ if report["exit_code"] != 1:
+ raise ValueError(
+ "Drift must fail the price predicate; restore the original formula/integration and retry."
+ )
+ self.result["drift"] = {
+ "report": report,
+ "blocked": hook_decision({"hook_event_name": "Stop"}, report, supervisor).get(
+ "decision"
+ )
+ == "block",
+ }
+ self.save()
+ return dict_or_raise(self.result["drift"])
+
+ def answer_diagnosis(self, cause: str, explanation: str) -> None:
+ with self.lock:
+ self.expect("diagnosis")
+ if not self.result.get("drift") or cause not in {"result", "network", "missing"}:
+ raise ValueError("Introduce drift first and choose result/network/missing.")
+ self.result["diagnosis"] = {
+ "cause": cause,
+ "correct": cause == "result",
+ "explanation": response(explanation),
+ }
+ self.data["stage"] = "repair"
+ self.write_reports()
+
+ def feedback(self, notes: dict[str, str]) -> None:
+ with self.lock:
+ self.expect("feedback")
+ self.result["confusion"] = {
+ key: response(notes[key]) for key in ("setup", "second", "errors")
+ }
+ self.data["index"] += 1
+ self.data["stage"] = "preference" if self.data["index"] == len(STYLES) else "setup"
+ self.write_reports()
+
+ def finish(self, style: str, reason: str) -> None:
+ with self.lock:
+ self.expect("preference")
+ if style not in (*STYLES, "no-preference"):
+ raise ValueError("Choose wrapper/class/module/no-preference.")
+ self.data["preference"] = {"style": style, "reason": response(reason)}
+ self.data["stage"] = "done"
+ self.data["completed_at"] = datetime.now(UTC).isoformat()
+ self.write_reports()
+
+ def write_reports(self) -> None:
+ with self.lock:
+ self.save()
+ rows = []
+ preference = self.data["preference"]
+ for style in self.data["order"]:
+ r = self.data["results"][style]
+
+ def minutes(task: str, result: dict[str, Any] = r) -> str:
+ value = result[task]["elapsed_ms"]
+ return "" if value is None else f"{value / 60000:.3f}"
+
+ rows.append(
+ {
+ "style": style,
+ "setup_minutes": minutes("setup"),
+ "business_lines_changed": (r["integration_business_lines"] or {}).get(
+ "total", ""
+ ),
+ "second_method_minutes": minutes("second"),
+ "coverage_correct": f"{r['coverage']['correct']}/{r['coverage']['total']}"
+ if r["coverage"]
+ else "",
+ "diagnosis_correct": (r["diagnosis"] or {}).get("correct", ""),
+ "repair_passed": r["repair"]["passed"]
+ if r["repair"]["elapsed_ms"] is not None
+ else "",
+ "repair_minutes": minutes("repair"),
+ "setup_confusion": (r["confusion"] or {}).get("setup", ""),
+ "second_method_confusion": (r["confusion"] or {}).get("second", ""),
+ "error_confusion": (r["confusion"] or {}).get("errors", ""),
+ "preferred": preference["style"] == style if preference else "",
+ "preference_style": preference["style"] if preference else "",
+ "preference_reason": preference["reason"] if preference else "",
+ }
+ )
+ title = (
+ "SYNTHETIC WALKTHROUGH — not participant feedback"
+ if self.data["mode"] == "synthetic"
+ else "Participant pilot feedback"
+ )
+
+ def escape(value: Any) -> str:
+ return str(value).replace("|", "\\|").replace("\n", "
").replace("\r", "")
+
+ table = [
+ "| Measure | " + " | ".join(self.data["order"]) + " |",
+ "| --- | --- | --- | --- |",
+ ]
+ for key in rows[0]:
+ if key != "style":
+ table.append(
+ "| "
+ + key.replace("_", " ")
+ + " | "
+ + " | ".join(escape(row[key]) for row in rows)
+ + " |"
+ )
+ (self.root / "feedback.md").write_text(
+ f"# {title}\n\nParticipant: {self.data['participant']}; rotation: {self.data['rotation']}; state: {self.data['stage']}.\n\n"
+ + "\n".join(table)
+ + "\n\nTask timers include reading, editing and gate execution. Explicit pauses exclude downtime. Unexpected interruptions resume at the last checkpoint (up to one second lost). Business-line changes count additions + deletions; registration-only entry.py edits are excluded. JSON contains attempts, submitted snapshots, quiz answers and explanations. Empty cells are pending. Preference is supplied, never inferred.\n"
+ )
+ with (self.root / "feedback.csv").open("w", newline="") as file:
+ writer = csv.DictWriter(
+ file, fieldnames=["participant", "mode", "rotation", "status", *rows[0]]
+ )
+ writer.writeheader()
+ for row in rows:
+ writer.writerow(
+ {
+ "participant": self.data["participant"],
+ "mode": self.data["mode"],
+ "rotation": self.data["rotation"],
+ "status": self.data["stage"],
+ **row,
+ }
+ )
+
+
+def dict_or_raise(value: Any) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise ValueError("Invalid study state.")
+ return value
diff --git a/examples/sdk-registration/.claude/settings.json b/examples/sdk-registration/.claude/settings.json
new file mode 100644
index 0000000..d086bd0
--- /dev/null
+++ b/examples/sdk-registration/.claude/settings.json
@@ -0,0 +1,8 @@
+{
+ "hooks": {
+ "PreToolUse": [{"hooks": [{"type": "command", "command": "melampus gate --claude --state \"$CLAUDE_PROJECT_DIR/.melampus/session.json\"", "timeout": 30}]}],
+ "PostToolUse": [{"hooks": [{"type": "command", "command": "melampus gate --claude --state \"$CLAUDE_PROJECT_DIR/.melampus/session.json\"", "timeout": 30}]}],
+ "PostToolUseFailure": [{"hooks": [{"type": "command", "command": "melampus gate --claude --state \"$CLAUDE_PROJECT_DIR/.melampus/session.json\"", "timeout": 30}]}],
+ "Stop": [{"hooks": [{"type": "command", "command": "melampus gate --claude --state \"$CLAUDE_PROJECT_DIR/.melampus/session.json\"", "timeout": 30}]}]
+ }
+}
diff --git a/examples/sdk-registration/CLAUDE.md b/examples/sdk-registration/CLAUDE.md
new file mode 100644
index 0000000..1ddbb3b
--- /dev/null
+++ b/examples/sdk-registration/CLAUDE.md
@@ -0,0 +1,14 @@
+# Reviewed SDK registration session
+
+Keep business methods plain in service.py/functions.py. registration.py registers
+selected methods with the exact reviewed Contract objects from intent.py. Keep
+the wrapper style in wrapper.py for comparison; do not stack integration styles.
+Scenarios must call the registered objects. Captured raw functions and other
+instances bypass registration. label() is deliberately unconfigured.
+
+The separate melampus session supervisor blocks progression/completion on drift
+or incomplete evidence. Inspect the function/check identifiers and repair the
+watched implementation with Edit/Write. Leave intent, scenarios, configuration
+and hooks unchanged. Do not restart the supervisor to accept new intent.
+Ask the owner if reviewed intent needs to change. A healthy gate validates only
+required checks on exercised calls, and never proves complete correctness.
diff --git a/examples/sdk-registration/README.md b/examples/sdk-registration/README.md
new file mode 100644
index 0000000..2290cee
--- /dev/null
+++ b/examples/sdk-registration/README.md
@@ -0,0 +1,45 @@
+# Compare decorators, class registration and module boundaries
+
+From the repository root:
+
+```sh
+uv sync --locked --all-extras
+make demo-registration
+```
+
+The command runs the same nonnegative-integer claim through three styles. Each
+style goes healthy → deliberate drift → blocked completion → repaired. Removing
+a registered module wrapper yields incomplete evidence. No model request,
+collector, network export or external account is needed.
+
+| Style | Business source | Setup | Reviewed path |
+| --- | --- | --- | --- |
+| Decorator | `wrapper.py` | `@PRICE.instrument(path=...)` on a function | `wrapper:price` |
+| Class | `service.py` stays plain | `instrument(PricingService(), ...)` in registration.py | `pricing:PricingService.price` |
+| Module boundary | `functions.py` stays plain | Registered SimpleNamespace in registration.py | `pricing:price` |
+
+`label()` is deliberately unconfigured. Call through the registered object;
+original imports and previously captured methods bypass wrappers. Multiple
+instances can use the same reviewed path, but each must be registered.
+
+For a real coding-agent session:
+
+```sh
+source .venv/bin/activate
+cd examples/sdk-registration
+melampus session
+```
+
+In a second terminal, activate that environment, enter the same directory, then
+start Claude Code and enable the included project hooks. Ask it to change the
+service price implementation while keeping reviewed intent/registration intact.
+Reads and scoped Edit/Write repairs remain available on drift; progression and
+completion require fresh healthy evidence. Other agents can use `melampus gate`.
+
+The executable claim checks bounds/types; it does not prove price accuracy.
+Tests can catch the same seeded failure. Melampus adds automatic replay of
+reviewed scenarios and the agent gate, rather than replacing unit tests.
+
+[API and scope](../../docs/SDK-REGISTRATION.md) ·
+[Research and tradeoffs](../../docs/SDK-UX-RESEARCH.md) ·
+[Timed participant study](../pilot_study/README.md)
diff --git a/examples/sdk-registration/exercise.py b/examples/sdk-registration/exercise.py
new file mode 100644
index 0000000..7450515
--- /dev/null
+++ b/examples/sdk-registration/exercise.py
@@ -0,0 +1,8 @@
+from registration import pricing, service
+from wrapper import price
+
+for cents in (-100, 0, 250):
+ price(cents)
+ service.price(cents)
+ pricing.price(cents)
+ pricing.label() # Deliberately unconfigured; this call produces no Melampus check.
diff --git a/examples/sdk-registration/functions.py b/examples/sdk-registration/functions.py
new file mode 100644
index 0000000..73c7fb2
--- /dev/null
+++ b/examples/sdk-registration/functions.py
@@ -0,0 +1,6 @@
+def price(cents: int) -> int:
+ return max(0, cents)
+
+
+def label() -> str:
+ return "cents"
diff --git a/examples/sdk-registration/intent.py b/examples/sdk-registration/intent.py
new file mode 100644
index 0000000..f027e6c
--- /dev/null
+++ b/examples/sdk-registration/intent.py
@@ -0,0 +1,17 @@
+from melampus import Check, Contract
+
+PRICE = Contract(
+ "Return a nonnegative price in cents",
+ (
+ Check(
+ "nonnegative",
+ lambda value: type(value) is int and value >= 0,
+ "Price is a nonnegative integer.",
+ ),
+ ),
+)
+CONTRACTS = {
+ "wrapper:price": PRICE,
+ "pricing:PricingService.price": PRICE,
+ "pricing:price": PRICE,
+}
diff --git a/examples/sdk-registration/melampus.toml b/examples/sdk-registration/melampus.toml
new file mode 100644
index 0000000..e01cdb9
--- /dev/null
+++ b/examples/sdk-registration/melampus.toml
@@ -0,0 +1,5 @@
+contracts = "intent"
+probe = "exercise.py"
+watch = ["service.py", "functions.py", "wrapper.py", "registration.py"]
+protect = [".claude/settings.json", "CLAUDE.md"]
+timeout = 5
diff --git a/examples/sdk-registration/registration.py b/examples/sdk-registration/registration.py
new file mode 100644
index 0000000..dc8a4a9
--- /dev/null
+++ b/examples/sdk-registration/registration.py
@@ -0,0 +1,14 @@
+from types import SimpleNamespace
+
+from functions import label, price
+from intent import PRICE
+from service import PricingService
+
+from melampus import instrument
+
+service = instrument(
+ PricingService(), namespace="pricing:PricingService", contracts={"price": PRICE}
+)
+pricing = instrument(
+ SimpleNamespace(price=price, label=label), namespace="pricing", contracts={"price": PRICE}
+)
diff --git a/examples/sdk-registration/service.py b/examples/sdk-registration/service.py
new file mode 100644
index 0000000..4271fe0
--- /dev/null
+++ b/examples/sdk-registration/service.py
@@ -0,0 +1,6 @@
+class PricingService:
+ def __init__(self, fee: int = 0) -> None:
+ self._fee = fee
+
+ def price(self, cents: int) -> int:
+ return max(0, cents) + self._fee
diff --git a/examples/sdk-registration/wrapper.py b/examples/sdk-registration/wrapper.py
new file mode 100644
index 0000000..8b75710
--- /dev/null
+++ b/examples/sdk-registration/wrapper.py
@@ -0,0 +1,6 @@
+from intent import PRICE
+
+
+@PRICE.instrument(path="wrapper:price")
+def price(cents: int) -> int:
+ return max(0, cents)
diff --git a/scripts/check_dist.py b/scripts/check_dist.py
index 2629829..3996de5 100644
--- a/scripts/check_dist.py
+++ b/scripts/check_dist.py
@@ -29,6 +29,7 @@ def main() -> None:
"melampus/watcher.py",
"melampus/session.py",
"melampus/contracts.py",
+ "melampus/registration.py",
"melampus/_probe.py",
):
assert required in names, required
@@ -50,6 +51,13 @@ def main() -> None:
"examples/agent-session/exercise.py",
"docs/AGENT-SESSION.md",
"scripts/demo_agent_session.py",
+ "examples/sdk-registration/.claude/settings.json",
+ "examples/sdk-registration/registration.py",
+ "examples/pilot_study/study.py",
+ "docs/SDK-REGISTRATION.md",
+ "docs/SDK-UX-RESEARCH.md",
+ "scripts/demo_registration.py",
+ "scripts/demo_pilot.py",
):
assert any(name.endswith("/" + suffix) for name in names), suffix
with tempfile.TemporaryDirectory(prefix="melampus-dist-") as temporary:
@@ -83,7 +91,7 @@ def main() -> None:
str(wheel),
"python",
"-c",
- "import melampus; from melampus import Check, Policy, instrumented; print(melampus.__version__)",
+ "import melampus; from melampus import Check, Contract, Policy, instrument, instrumented; print(melampus.__version__)",
],
cwd=temp,
env=env,
@@ -95,6 +103,25 @@ def main() -> None:
env=env,
check=True,
)
+ for script, arguments in (
+ ("demo_registration.py", []),
+ ("demo_pilot.py", ["--demo"]),
+ ):
+ subprocess.run(
+ [
+ "uv",
+ "run",
+ "--no-project",
+ "--with",
+ f"melampus[session] @ {wheel.as_uri()}",
+ "python",
+ str(ROOT / "scripts" / script),
+ *arguments,
+ ],
+ cwd=temp,
+ env=env,
+ check=True,
+ )
subprocess.run(
[
"uv",
diff --git a/scripts/demo_pilot.py b/scripts/demo_pilot.py
new file mode 100644
index 0000000..a8cfc91
--- /dev/null
+++ b/scripts/demo_pilot.py
@@ -0,0 +1,11 @@
+"""Entrypoint also usable outside this checkout with an installed Melampus wheel."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "examples"))
+
+from pilot_study.cli import main # noqa: E402
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/demo_registration.py b/scripts/demo_registration.py
new file mode 100644
index 0000000..1d967c8
--- /dev/null
+++ b/scripts/demo_registration.py
@@ -0,0 +1,54 @@
+"""Compare decorator, class and module-boundary styles using fresh probes."""
+
+import shutil
+import tempfile
+from pathlib import Path
+
+from melampus.session import Supervisor, hook_decision
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main() -> None:
+ with tempfile.TemporaryDirectory(prefix="melampus-registration-") as temporary:
+ root = Path(temporary)
+ shutil.copytree(
+ ROOT / "examples/sdk-registration",
+ root,
+ dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("__pycache__", ".melampus"),
+ )
+ supervisor = Supervisor(root / "melampus.toml")
+ healthy = supervisor.check()
+ assert healthy["exit_code"] == 0 and healthy["checks"] == {"passed": 9}, healthy
+ for file, path in (
+ ("wrapper.py", "wrapper:price"),
+ ("service.py", "pricing:PricingService.price"),
+ ("functions.py", "pricing:price"),
+ ):
+ source = root / file
+ original = source.read_text()
+ source.write_text(original.replace("max(0, cents)", "min(0, cents)"))
+ report = supervisor.check()
+ assert report["exit_code"] == 1, report
+ assert {item["function"] for item in report["findings"]} == {path}, report
+ assert (
+ hook_decision({"hook_event_name": "Stop"}, report, supervisor)["decision"]
+ == "block"
+ )
+ source.write_text(original)
+ assert supervisor.check()["exit_code"] == 0
+ print(f"{file}: healthy → drift at {path} → blocked completion → repaired")
+ registration = root / "registration.py"
+ original = registration.read_text()
+ registration.write_text(original + "\npricing.price = price\n")
+ report = supervisor.check()
+ assert report["exit_code"] == 2 and "pricing:price/nonnegative" in report["missing"], report
+ registration.write_text(original)
+ assert supervisor.check()["exit_code"] == 0
+ print("Removed module wrapper: incomplete required evidence, never healthy.")
+ print("Registration comparison passed; no model request or network export.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/site/index.html b/site/index.html
index 0c48c4d..0ab7a82 100644
--- a/site/index.html
+++ b/site/index.html
@@ -4,7 +4,7 @@
-
OPEN-SOURCE ALPHA · v0.1.0
+OPEN-SOURCE ALPHA · v0.2.0
Melampus runs beside an AI coding session. When generated code drifts, it turns @@ -35,14 +35,14 @@
One recorded local run; timing is illustrative, not a performance claim.
+One recorded 0.1.0 local run; timing is illustrative, not a performance claim. The decorator example remains supported in 0.2.0.
Healthy work proceeds. Drift or missing evidence returns the session to repair.
melampus session \
- --config examples/agent-session/melampus.ymlclaude
+ TERMINAL A · SUPERVISORcd examples/sdk-registration
+melampus session
+ TERMINAL B · CODING AGENTcd examples/sdk-registration
+claude
# Codex or another agent can use the same gate
TRY THE ALPHA
-The package is available as a verified wheel on the v0.1.0 GitHub release. Production PyPI publishing is still being configured.
+Version 0.2.0 lets business methods stay plain: register selected class methods or grouped functions once at application setup. Native decorators remain a familiar option for a few functions.
+Download the validated wheel or sdist from the GitHub alpha release. PyPI publication uses a separate Trusted Publisher workflow. The local pilot compares integration styles; human preference remains unmeasured.
git clone https://github.com/melampus-org/melampus-python.git
cd melampus-python
-uv sync --all-extras
-uv run python examples/agent-session/compare_with_unit_tests.py
+uv sync --locked --all-extras
+make demo-registration
+make demo-pilot # synthetic collection walkthrough