From e9959e8702cfdeb0a9b1314a661bcb9f7dbf92f9 Mon Sep 17 00:00:00 2001 From: Melampus Admin Date: Thu, 1 Oct 2026 23:30:36 +0700 Subject: [PATCH 1/3] feat: port SDK registration and onboarding pilot from TypeScript alpha --- .gitignore | 2 + CHANGELOG.md | 21 + Makefile | 9 +- README.md | 51 ++- docs/AGENT-SESSION.md | 8 + docs/RELEASE.md | 15 + docs/SDK-REGISTRATION.md | 153 +++++++ docs/SDK-UX-RESEARCH.md | 67 +++ docs/adr/0009-explicit-sdk-registration.md | 38 ++ examples/pilot_study/README.md | 106 +++++ examples/pilot_study/__init__.py | 1 + examples/pilot_study/cli.py | 198 ++++++++ examples/pilot_study/fixtures.py | 154 +++++++ examples/pilot_study/study.py | 421 ++++++++++++++++++ .../sdk-registration/.claude/settings.json | 8 + examples/sdk-registration/CLAUDE.md | 14 + examples/sdk-registration/README.md | 45 ++ examples/sdk-registration/exercise.py | 8 + examples/sdk-registration/functions.py | 6 + examples/sdk-registration/intent.py | 17 + examples/sdk-registration/melampus.toml | 5 + examples/sdk-registration/registration.py | 14 + examples/sdk-registration/service.py | 6 + examples/sdk-registration/wrapper.py | 6 + scripts/check_dist.py | 29 +- scripts/demo_pilot.py | 11 + scripts/demo_registration.py | 54 +++ src/melampus/__init__.py | 11 +- src/melampus/_probe.py | 3 +- src/melampus/contracts.py | 3 +- src/melampus/registration.py | 113 +++++ src/melampus/sdk.py | 27 +- tests/test_agent_session.py | 4 +- tests/test_pilot_study.py | 194 ++++++++ tests/test_registration.py | 249 +++++++++++ tests/test_registration_session.py | 103 +++++ tests/types/public_api.py | 36 ++ 37 files changed, 2189 insertions(+), 21 deletions(-) create mode 100644 docs/SDK-REGISTRATION.md create mode 100644 docs/SDK-UX-RESEARCH.md create mode 100644 docs/adr/0009-explicit-sdk-registration.md create mode 100644 examples/pilot_study/README.md create mode 100644 examples/pilot_study/__init__.py create mode 100644 examples/pilot_study/cli.py create mode 100644 examples/pilot_study/fixtures.py create mode 100644 examples/pilot_study/study.py create mode 100644 examples/sdk-registration/.claude/settings.json create mode 100644 examples/sdk-registration/CLAUDE.md create mode 100644 examples/sdk-registration/README.md create mode 100644 examples/sdk-registration/exercise.py create mode 100644 examples/sdk-registration/functions.py create mode 100644 examples/sdk-registration/intent.py create mode 100644 examples/sdk-registration/melampus.toml create mode 100644 examples/sdk-registration/registration.py create mode 100644 examples/sdk-registration/service.py create mode 100644 examples/sdk-registration/wrapper.py create mode 100644 scripts/demo_pilot.py create mode 100644 scripts/demo_registration.py create mode 100644 src/melampus/registration.py create mode 100644 tests/test_pilot_study.py create mode 100644 tests/test_registration.py create mode 100644 tests/test_registration_session.py create mode 100644 tests/types/public_api.py 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..dc16a9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 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..db5d541 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ 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 is in development; no PyPI release is claimed here.** 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 +57,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 +71,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/docs/AGENT-SESSION.md b/docs/AGENT-SESSION.md index 311bc4f..ffbbdbb 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 development) + +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..ca5904f 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -1,5 +1,20 @@ # First release: 0.1.0 alpha +## Next alpha: registration and onboarding + +The 0.2.0 development branch mirrors TypeScript 0.2.0's explicit class/module +registration and measured pilot, adapted to Python method binding and native +decorators. The package version remains 0.1.0 until a reviewed release bump. +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. + ## Scope and evidence The primary product is a local AI coding-session supervisor: reviewed SDK diff --git a/docs/SDK-REGISTRATION.md b/docs/SDK-REGISTRATION.md new file mode 100644 index 0000000..f2af116 --- /dev/null +++ b/docs/SDK-REGISTRATION.md @@ -0,0 +1,153 @@ +# Choose the integration style that fits your code + +The 0.2.0 development branch adds `instrument` for existing service instances +and module boundaries. The 0.1.0 artifact supports the existing function +decorators. No PyPI publication is implied by these docs. + +| 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..c0cc0b6 --- /dev/null +++ b/docs/SDK-UX-RESEARCH.md @@ -0,0 +1,67 @@ +# Python SDK onboarding: evidence and design decisions + +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..e04d7b7 --- /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 the 0.2.0 development branch (2026-10-01). + +## 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/src/melampus/__init__.py b/src/melampus/__init__.py index 4e4ec4e..e857a0c 100644 --- a/src/melampus/__init__.py +++ b/src/melampus/__init__.py @@ -3,7 +3,16 @@ from importlib.metadata import version from .contracts import Contract +from .registration import instrument from .sdk import DEFAULT_POLICY, Check, Policy, instrumented __version__ = version("melampus") -__all__ = ["Check", "Contract", "Policy", "DEFAULT_POLICY", "instrumented", "__version__"] +__all__ = [ + "Check", + "Contract", + "Policy", + "DEFAULT_POLICY", + "instrument", + "instrumented", + "__version__", +] diff --git a/src/melampus/_probe.py b/src/melampus/_probe.py index 5c43939..52707c6 100644 --- a/src/melampus/_probe.py +++ b/src/melampus/_probe.py @@ -54,8 +54,7 @@ def validate( if contract is None: return if ( - path in declarations - or intent != contract.intent + intent != contract.intent or assumptions != contract.assumptions or len(checks) != len(contract.checks) or any(a is not b for a, b in zip(checks, contract.checks, strict=True)) diff --git a/src/melampus/contracts.py b/src/melampus/contracts.py index ef4d52f..a9717da 100644 --- a/src/melampus/contracts.py +++ b/src/melampus/contracts.py @@ -25,11 +25,12 @@ class Contract: assumptions: tuple[str, ...] = () def instrument( - self, *, generator: str = "unspecified" + self, *, generator: str = "unspecified", path: str | None = None ) -> Callable[[Callable[P, R]], Callable[P, R]]: return instrumented( intent=self.intent, checks=self.checks, assumptions=self.assumptions, generator=generator, + path=path, ) diff --git a/src/melampus/registration.py b/src/melampus/registration.py new file mode 100644 index 0000000..c77225e --- /dev/null +++ b/src/melampus/registration.py @@ -0,0 +1,113 @@ +"""Explicit, per-object registration without changing classes or evaluating properties.""" + +from __future__ import annotations + +import inspect +from collections.abc import Mapping +from types import ( + GetSetDescriptorType, + MemberDescriptorType, + MethodType, + ModuleType, + SimpleNamespace, +) +from typing import Any, TypeVar + +from opentelemetry.trace import Tracer + +from .contracts import Contract +from .sdk import Policy, instrumented + +T = TypeVar("T") +_MARKER = "_melampus_registration" + + +def instrument( + target: T, + *, + namespace: str, + contracts: Mapping[str, Contract], + generator: str = "unspecified", + policy: Policy | None = None, + tracer: Tracer | None = None, +) -> T: + """Register selected methods on an ordinary instance, module or SimpleNamespace. + + Return the same object with its type preserved. Register before sharing it or + capturing methods. Previously captured functions bypass the wrappers. + Properties, custom attribute hooks, class/static methods, classes themselves, + slot-only objects and generator methods are intentionally unsupported. + """ + if ( + not isinstance(namespace, str) + or not namespace + or not namespace.isprintable() + or namespace.count(":") > 1 + or any(not part for part in namespace.split(":")) + ): + raise ValueError("namespace must be module or module:Class with nonempty parts") + if not isinstance(contracts, Mapping) or not contracts: + raise TypeError("contracts must be a nonempty method-to-Contract mapping") + cls = type(target) + if inspect.isclass(target) or inspect.isroutine(target): + raise TypeError("register an instance or module, not a class or function") + if cls not in (ModuleType, SimpleNamespace) and ( + cls.__getattribute__ is not object.__getattribute__ + or cls.__setattr__ is not object.__setattr__ + or inspect.getattr_static(cls, "__getattr__", None) is not None + ): + raise TypeError("custom attribute hooks are unsupported; use a plain boundary object") + dictionary_descriptor = next( + (base.__dict__["__dict__"] for base in cls.__mro__ if "__dict__" in base.__dict__), None + ) + if dictionary_descriptor is not None and not isinstance( + dictionary_descriptor, (GetSetDescriptorType, MemberDescriptorType) + ): + raise TypeError("custom __dict__ descriptors are unsupported") + try: + attributes: dict[str, Any] = object.__getattribute__(target, "__dict__") + except AttributeError as exc: + raise TypeError( + "target requires a writable __dict__; slot-only objects are unsupported" + ) from exc + if type(attributes) is not dict: + raise TypeError("target requires a writable instance or module dictionary") + if _MARKER in attributes: + raise TypeError("object is already instrumented; register all selected methods once") + + plan: dict[str, Any] = {} + for name, contract in contracts.items(): + if not isinstance(name, str) or not name.isidentifier() or name.startswith("_"): + raise TypeError("contract keys must name public methods") + if not isinstance(contract, Contract): + raise TypeError(f"contract for {name} must be a reviewed Contract") + # Static inspection never invokes a property or user descriptor. + descriptor = inspect.getattr_static(target, name, None) + if inspect.isdatadescriptor(descriptor): + raise TypeError(f"method {name} uses an unsupported descriptor") + if name in attributes: + function = attributes[name] + elif inspect.isfunction(descriptor): + function = MethodType(descriptor, target) + else: + raise TypeError(f"method {name} is missing or uses an unsupported descriptor") + if not (inspect.isfunction(function) or inspect.ismethod(function)): + raise TypeError(f"method {name} must be a Python function or bound method") + if getattr(function, "_melampus_wrapped", False): + raise TypeError(f"method {name} is already instrumented; choose one integration style") + path = f"{namespace}{'.' if ':' in namespace else ':'}{name}" + wrapped = instrumented( + intent=contract.intent, + checks=contract.checks, + assumptions=contract.assumptions, + generator=generator, + policy=policy, + tracer=tracer, + path=path, + )(function) + plan[name] = wrapped + # Validate every entry before changing ordinary dictionary entries. Shared + # class attributes stay untouched; no property setters are evaluated. + attributes.update(plan) + attributes[_MARKER] = True + return target diff --git a/src/melampus/sdk.py b/src/melampus/sdk.py index 44aaf5a..a447a3e 100644 --- a/src/melampus/sdk.py +++ b/src/melampus/sdk.py @@ -148,6 +148,7 @@ def instrumented( policy: Policy | None = None, tracer: Tracer | None = None, capture_content: bool = False, + path: str | None = None, ) -> Callable[[Callable[P, R]], Callable[P, R]]: """Declare intent and evaluate checks on sync or async function return values. @@ -156,6 +157,14 @@ def instrumented( """ if capture_content: raise NotImplementedError("content capture is not supported in schema 0.1.0") + if path is not None and ( + not isinstance(path, str) + or not 1 <= len(path) <= 256 + or not path.isprintable() + or path.count(":") != 1 + or any(not part for part in path.split(":")) + ): + raise ValueError("path must be module:qualified_name, at most 256 printable characters") if not isinstance(intent, str) or not intent: raise ValueError("intent must be nonempty text") if not IDENTIFIER.fullmatch(generator): @@ -183,16 +192,18 @@ def instrumented( def decorate(function: Callable[P, R]) -> Callable[P, R]: if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function): raise TypeError("generator functions are not supported") - path = f"{function.__module__}:{function.__qualname__}" + selected_path = ( + path if path is not None else f"{function.__module__}:{function.__qualname__}" + ) if _declaration_validator is not None: - _declaration_validator(path, intent, frozen_checks, tuple(assumptions)) - if len(path) > 256 or not path.isprintable(): + _declaration_validator(selected_path, intent, frozen_checks, tuple(assumptions)) + if len(selected_path) > 256 or not selected_path.isprintable(): raise ValueError("function path must contain at most 256 printable characters") - attributes = {**declaration, sc.FUNCTION: path} + attributes = {**declaration, sc.FUNCTION: selected_path} def start() -> Any: return selected_tracer.start_as_current_span( - path, + selected_path, attributes=attributes, record_exception=False, set_status_on_exception=False, @@ -209,9 +220,10 @@ async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any: span.set_status(Status(StatusCode.ERROR)) raise if frozen_checks and span.is_recording(): - _evaluate(span, frozen_checks, result, path, selected_policy) + _evaluate(span, frozen_checks, result, selected_path, selected_policy) return result + async_wrapper.__dict__["_melampus_wrapped"] = True return cast(Callable[P, R], async_wrapper) @wraps(function) @@ -223,9 +235,10 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: span.set_status(Status(StatusCode.ERROR)) raise if frozen_checks and span.is_recording(): - _evaluate(span, frozen_checks, result, path, selected_policy) + _evaluate(span, frozen_checks, result, selected_path, selected_policy) return result + wrapper.__dict__["_melampus_wrapped"] = True return wrapper return decorate diff --git a/tests/test_agent_session.py b/tests/test_agent_session.py index 2b0ed5e..af231f0 100644 --- a/tests/test_agent_session.py +++ b/tests/test_agent_session.py @@ -419,7 +419,9 @@ def test_contract_and_execution_failures_are_incomplete(project, mutation): replace(project, "return min(10000, max(0, cents))", "import os; os._exit(0)") else: with (project / "pricing.py").open("a") as f: - f.write("\n@PRICE.instrument()\ndef price(cents):\n return 0\n") + f.write( + '\nfrom melampus import instrumented\n@instrumented(intent="Changed intent", checks=PRICE.checks)\ndef price(cents):\n return 0\n' + ) report = Supervisor(project / "melampus.toml").check() assert report["exit_code"] == 2, report diff --git a/tests/test_pilot_study.py b/tests/test_pilot_study.py new file mode 100644 index 0000000..3e71edf --- /dev/null +++ b/tests/test_pilot_study.py @@ -0,0 +1,194 @@ +import csv +import importlib.util +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +# Load examples as a package without putting the source SDK on sys.path. Installed +# wheel smoke tests use the same package with a separate working directory. +spec = importlib.util.spec_from_file_location( + "pilot_study", + ROOT / "examples/pilot_study/__init__.py", + submodule_search_locations=[str(ROOT / "examples/pilot_study")], +) +package = importlib.util.module_from_spec(spec) +sys.modules["pilot_study"] = package +spec.loader.exec_module(package) + +from pilot_study.cli import run_synthetic # noqa: E402 +from pilot_study.fixtures import ORDERS, STYLES, coverage_questions, solution # noqa: E402 +from pilot_study.study import PilotStudy, changed_lines # noqa: E402 + + +def test_synthetic_all_seven_measures_and_three_styles(tmp_path): + study = PilotStudy(tmp_path / "demo", participant="demo", mode="synthetic") + run_synthetic(study) + assert study.data["stage"] == "done" + assert "SYNTHETIC" in (study.root / "feedback.md").read_text() + assert study.data["preference"]["style"] == "no-preference" + for style in STYLES: + r = study.data["results"][style] + for task in ("setup", "second", "repair"): + assert r[task]["passed"] and r[task]["elapsed_ms"] >= 0 + assert len(r[task]["attempts"]) == 2 + assert r["coverage"]["correct"] == 6 + assert r["diagnosis"]["correct"] and r["diagnosis"]["explanation"] + assert r["drift"]["blocked"] and r["confusion"]["errors"] + assert ( + r["integration_business_lines"]["total"] > 0 + if style == "wrapper" + else r["integration_business_lines"]["total"] == 0 + ) + assert ( + r["second_business_lines"]["total"] > 0 + if style == "wrapper" + else r["second_business_lines"]["total"] == 0 + ) + with (study.root / "feedback.csv").open() as file: + rows = list(csv.DictReader(file)) + assert len(rows) == 3 + assert all( + r["mode"] == "synthetic" and r["status"] == "done" and r["coverage_correct"] == "6/6" + for r in rows + ) + state = json.loads((study.root / "study.json").read_text()) + assert all(state["results"][s]["setup_business_snapshot"] for s in STYLES) + + +def test_pause_resume_and_interruption_exclude_downtime(tmp_path): + clock = [0] + kwargs = dict(participant="p01", clock=lambda: clock[0]) + study = PilotStudy(tmp_path / "p01", **kwargs) + study.start_timer() + clock[0] = 60 + study.pause() + assert study.data["timer"]["elapsed_ms"] == 60000 + clock[0] = 500 + study = PilotStudy(tmp_path / "p01", **kwargs) + study.start_timer() + clock[0] = 510 + study.tick() # emulate the last checkpoint before an unexpected termination + clock[0] = 1000 + study = PilotStudy(tmp_path / "p01", **kwargs) + assert study.data["interruptions"] == 1 + assert study.data["timer"]["elapsed_ms"] == 70000 + study.start_timer() + solution(study.folder, study.style, False) + assert study.check()["exit_code"] == 0 + assert study.data["results"]["wrapper"]["setup"]["elapsed_ms"] == 70000 + + +@pytest.mark.parametrize( + "mutation", ["protected", "missing", "early_second", "extra_label", "double_wrapper"] +) +def test_study_rejects_invalid_task_protocol(tmp_path, mutation): + study = PilotStudy(tmp_path / "study", participant="p01", rotation=4) + study.start_timer() + solution(study.folder, "module", mutation == "early_second") + if mutation == "protected": + intent = study.folder / "intent.py" + intent.write_text(intent.read_text() + "\n# changed\n") + elif mutation == "missing": + (study.folder / "intent.py").unlink() + elif mutation == "extra_label": + entry = study.folder / "entry.py" + entry.write_text( + entry.read_text() + .replace( + "from melampus import instrument", + "from melampus import instrument, Contract, Check\nLABEL = Contract('label', (Check('present', lambda n: True, 'present'),))", + ) + .replace("'price': PRICE", "'price': PRICE, 'label': LABEL") + ) + elif mutation == "double_wrapper": + entry = study.folder / "entry.py" + entry.write_text( + entry.read_text() + "\napi.price = PRICE.instrument(path='pilot:price')(api.price)\n" + ) + report = study.check() + assert report["exit_code"] == 2, report + assert study.data["stage"] == "setup" + if mutation in {"early_second", "extra_label", "double_wrapper"}: + assert report["task_error"] == "unexpected_check_count" and report["sdk_exit_code"] == 0 + + +def test_wrong_answers_and_no_preference_are_not_rewritten(tmp_path): + study = PilotStudy(tmp_path / "study", participant="p01") + for style in STYLES: + study.start_timer() + solution(study.folder, style, False) + assert study.check()["exit_code"] == 0 + study.start_timer() + solution(study.folder, style, True) + assert study.check()["exit_code"] == 0 + answers = [q["expected"] for q in coverage_questions(style)] + answers[0] = "uncovered" + study.answer_coverage(answers) + study.introduce_drift() + study.answer_diagnosis("network", "I incorrectly thought this was transport.") + study.start_timer() + business = study.folder / "business.py" + business.write_text(business.read_text().replace("min(0, cents)", "max(0, cents)", 1)) + assert study.check()["exit_code"] == 0 + assert not study.result["diagnosis"]["correct"] + assert study.result["coverage"]["correct"] == 5 + study.feedback(dict.fromkeys(("setup", "second", "errors"), "none")) + study.finish("no-preference", "All fit different use cases.") + assert study.data["preference"]["style"] == "no-preference" + + +def test_rotations_identity_guard_and_completed_preservation(tmp_path): + assert len({tuple(order) for order in ORDERS}) == 6 + for i, order in enumerate(ORDERS): + study = PilotStudy(tmp_path / f"p{i}", participant=f"p{i}", rotation=i) + assert tuple(study.data["order"]) == order + with pytest.raises(ValueError, match="original identity"): + PilotStudy(study.root, participant="different", rotation=i) + with pytest.raises(ValueError, match="overwrite"): + PilotStudy(tmp_path, participant="p01") + for kwargs in ( + {"participant": "../escape"}, + {"participant": "p", "rotation": 6}, + {"participant": "p", "mode": "bad"}, + ): + with pytest.raises(ValueError): + PilotStudy(tmp_path / "invalid", **kwargs) + + +@pytest.mark.parametrize( + "before,after,expected", + [("a\nb\n", "a\nc\n", 2), ("a\r\n", "a\n", 0), ("", "a\n", 1), ("a\n", "", 1)], +) +def test_line_changes_have_defined_semantics(before, after, expected): + assert changed_lines(before, after)["total"] == expected + + +def test_interactive_pause_resume_and_lock(tmp_path): + directory = tmp_path / "study" + command = [ + sys.executable, + str(ROOT / "scripts/demo_pilot.py"), + "--participant", + "p01", + "--dir", + str(directory), + ] + first = subprocess.run(command, input="pause\n", capture_output=True, text=True, timeout=10) + assert first.returncode == 0 and "Paused" in first.stdout, first.stderr + state = json.loads((directory / "study.json").read_text()) + assert state["stage"] == "setup" and not state["timer"]["running"] + solution(directory / "wrapper", "wrapper", False) + resumed = subprocess.run( + command, input="check\npause\n", capture_output=True, text=True, timeout=10 + ) + assert resumed.returncode == 0 and "Gate 0" in resumed.stdout, resumed.stderr + assert json.loads((directory / "study.json").read_text())["stage"] == "second" + lock = directory.with_name(directory.name + ".lock") + lock.write_text("existing runner") + locked = subprocess.run(command, input="pause\n", capture_output=True, text=True, timeout=10) + assert locked.returncode != 0 and "runner lock" in locked.stderr + assert lock.exists() diff --git a/tests/test_registration.py b/tests/test_registration.py new file mode 100644 index 0000000..c058267 --- /dev/null +++ b/tests/test_registration.py @@ -0,0 +1,249 @@ +import asyncio +import inspect +from dataclasses import dataclass +from types import ModuleType, SimpleNamespace + +import pytest + +from melampus import Check, Contract, Policy, instrument, instrumented + +PRICE = Contract("Return a nonnegative price", (Check("nonnegative", lambda n: n >= 0, "n >= 0"),)) + + +class Base: + def price(self, cents: int, *, fee: int = 0) -> int: + """Price with instance state.""" + return max(0, cents) + self._fee + fee + + +@dataclass +class Service(Base): + _fee: int = 2 + + def quote(self, cents: int) -> int: + return self.price(cents) + + async def async_price(self, cents: int) -> int: + await asyncio.sleep(0) + return self.price(cents) + + +def attrs(exporter): + return [span.attributes for span in exporter.get_finished_spans()] + + +def test_inherited_method_binding_signature_identity_and_unhashable_target(telemetry): + tracer, exporter = telemetry + service, other = Service(), Service(5) + original = service.price + returned = instrument( + service, namespace="pricing:Service", contracts={"price": PRICE}, tracer=tracer + ) + assert returned is service + assert inspect.signature(service.price) == inspect.signature(original) + assert service.price.__name__ == original.__name__ + assert service.price.__doc__ == original.__doc__ + assert service.price(-10, fee=3) == 5 + assert original(-10) == 2 # captured bound method bypasses + assert other.price(-10) == 5 # no class mutation + assert Base.price(service, -10) == 2 # direct class call bypasses + assert "price" not in Service.__dict__ and "price" not in vars(other) + assert len(attrs(exporter)) == 1 + assert attrs(exporter)[0]["code_artifact.function"] == "pricing:Service.price" + assert attrs(exporter)[0]["code_artifact.check.results"] == ("passed",) + with pytest.raises(TypeError, match="already instrumented"): + instrument(service, namespace="pricing", contracts={"price": PRICE}) + + +def test_async_methods_and_internal_calls_use_registered_instance(telemetry): + tracer, exporter = telemetry + service = instrument( + Service(), + namespace="pricing:Service", + contracts={"price": PRICE, "async_price": PRICE}, + tracer=tracer, + ) + assert inspect.iscoroutinefunction(service.async_price) + assert asyncio.run(service.async_price(-10)) == 2 + assert service.quote(-10) == 2 + assert [a["code_artifact.function"] for a in attrs(exporter)] == [ + "pricing:Service.price", + "pricing:Service.async_price", + "pricing:Service.price", + ] + + +@pytest.mark.parametrize("kind", [SimpleNamespace, lambda: ModuleType("pricing")]) +def test_own_functions_modules_captured_references_and_omitted_methods(telemetry, kind): + tracer, exporter = telemetry + target = kind() + target.price = lambda cents: max(0, cents) + target.label = lambda: "cents" + original = target.price + instrument(target, namespace="pricing", contracts={"price": PRICE}, tracer=tracer) + assert target.price(-10) == 0 and target.label() == "cents" + assert original(-10) == 0 + assert len(attrs(exporter)) == 1 + assert attrs(exporter)[0]["code_artifact.function"] == "pricing:price" + + +def test_policy_uses_explicit_registered_path(telemetry): + tracer, exporter = telemetry + policy = Policy(disabled_paths=["pricing:Service.price"]) + instrument( + Service(), + namespace="pricing:Service", + contracts={"price": PRICE}, + policy=policy, + tracer=tracer, + ).price(1) + assert attrs(exporter)[0]["code_artifact.check.results"] == ("disabled",) + + +def test_failure_and_async_exception_cancel_preserve_application_behavior(telemetry): + tracer, exporter = telemetry + original = ValueError("private exception") + + class Broken: + def price(self): + return -1 + + async def fail(self): + raise original + + async def cancel(self): + raise asyncio.CancelledError() + + target = instrument( + Broken(), + namespace="pricing:Broken", + contracts={k: PRICE for k in ("price", "fail", "cancel")}, + tracer=tracer, + ) + assert target.price() == -1 + with pytest.raises(ValueError) as caught: + asyncio.run(target.fail()) + assert caught.value is original + with pytest.raises(asyncio.CancelledError): + asyncio.run(target.cancel()) + assert attrs(exporter)[0]["code_artifact.check.results"] == ("failed",) + assert all(not s.events for s in exporter.get_finished_spans()) + + +def test_descriptors_are_never_evaluated_and_validation_is_atomic(): + touched = [] + + class Properties(Service): + @property + def secret(self): + touched.append(True) + raise AssertionError("property evaluated") + + @staticmethod + def static(): + return 0 + + @classmethod + def class_method(cls): + return 0 + + for key in ("secret", "static", "class_method", "missing"): + target = Properties() + with pytest.raises(TypeError): + instrument(target, namespace="pricing", contracts={"price": PRICE, key: PRICE}) + assert "price" not in vars(target) + # A failed plan has not marked the object as registered. + instrument(target, namespace="pricing", contracts={"price": PRICE}) + assert not touched + + +def test_shadowed_data_and_dictionary_descriptors_are_rejected_without_execution(): + touched = [] + + class Shadow(Service): + @property + def price(self): + touched.append(True) + return lambda: 0 + + target = Shadow() + vars(target)["price"] = lambda: 0 + with pytest.raises(TypeError, match="unsupported descriptor"): + instrument(target, namespace="pricing", contracts={"price": PRICE}) + + class Dictionary: + @property + def __dict__(self): + touched.append(True) + return {} + + with pytest.raises(TypeError, match="custom __dict__"): + instrument(Dictionary(), namespace="pricing", contracts={"price": PRICE}) + assert not touched + + +@pytest.mark.parametrize("namespace", ["", ":", "a:", ":b", "a:b:c", "a\n", "x" * 256, None]) +def test_invalid_namespace_or_derived_path(namespace): + target = Service() + with pytest.raises(ValueError): + instrument(target, namespace=namespace, contracts={"price": PRICE}) + assert "price" not in vars(target) + + +@pytest.mark.parametrize( + "contracts", [{}, {"missing": PRICE}, {"price": "bad"}, {"_private": PRICE}, {1: PRICE}, []] +) +def test_invalid_contract_maps(contracts): + with pytest.raises(TypeError): + instrument(Service(), namespace="pricing", contracts=contracts) + + +def test_unsupported_targets_and_nested_wrappers(): + class Slots: + __slots__ = () + + class Dynamic: + def __getattr__(self, key): + raise AssertionError("lookup invoked") + + class Frozen: + def __setattr__(self, key, value): + raise AssertionError("setter invoked") + + for target in (None, {}, [], Service, lambda: 0, Slots(), Dynamic(), Frozen()): + with pytest.raises(TypeError): + instrument(target, namespace="pricing", contracts={"price": PRICE}) + + wrapped = SimpleNamespace(price=PRICE.instrument()(lambda: 0)) + with pytest.raises(TypeError, match="already instrumented"): + instrument(wrapped, namespace="pricing", contracts={"price": PRICE}) + + def generator(): + yield 1 + + async def async_generator(): + yield 1 + + for function in (generator, async_generator, 1, object()): + with pytest.raises(TypeError): + instrument( + SimpleNamespace(price=function), namespace="pricing", contracts={"price": PRICE} + ) + + +def test_explicit_decorator_path_and_nonrecording_behavior(telemetry): + tracer, exporter = telemetry + price = PRICE.instrument(path="pricing:price")(lambda: 0) + assert price() == 0 # API-only default provider is non-recording in this process + assert not attrs(exporter) + price = instrumented( + intent=PRICE.intent, checks=PRICE.checks, tracer=tracer, path="pricing:price" + )(lambda: 0) + assert price() == 0 + assert attrs(exporter)[0]["code_artifact.function"] == "pricing:price" + + +@pytest.mark.parametrize("path", ["", "pricing", "a:", ":b", "a:b:c", "a:b\n", "a:" + "b" * 255, 1]) +def test_explicit_path_is_validated(path): + with pytest.raises(ValueError): + instrumented(intent="price", path=path) diff --git a/tests/test_registration_session.py b/tests/test_registration_session.py new file mode 100644 index 0000000..62e21ff --- /dev/null +++ b/tests/test_registration_session.py @@ -0,0 +1,103 @@ +import shutil +from pathlib import Path + +import pytest + +from melampus.session import Supervisor, hook_decision + +EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "sdk-registration" + + +@pytest.fixture +def project(tmp_path): + root = tmp_path / "project" + shutil.copytree(EXAMPLE, root, ignore=shutil.ignore_patterns("__pycache__", ".melampus")) + return root + + +def change(root, file, before, after): + path = root / file + original = path.read_text() + assert before in original + path.write_text(original.replace(before, after)) + + +def test_three_styles_drift_gate_and_repair(project): + supervisor = Supervisor(project / "melampus.toml") + healthy = supervisor.check() + assert healthy["exit_code"] == 0 and healthy["checks"] == {"passed": 9}, healthy + change(project, "service.py", "max(0, cents)", "min(0, cents)") + report = supervisor.check() + assert report["exit_code"] == 1 + assert {f["function"] for f in report["findings"]} == {"pricing:PricingService.price"} + assert hook_decision({"hook_event_name": "Stop"}, report, supervisor)["decision"] == "block" + change(project, "service.py", "min(0, cents)", "max(0, cents)") + assert supervisor.check()["exit_code"] == 0 + + +def test_multiple_instances_share_reviewed_path_without_erasing_drift(project): + with (project / "exercise.py").open("a") as file: + file.write(""" +from melampus import instrument +from service import PricingService +from intent import PRICE + +second = instrument(PricingService(fee=-10), namespace="pricing:PricingService", contracts={"price": PRICE}) +second.price(0) +service.price(0) +""") + report = Supervisor(project / "melampus.toml").check() + assert report["exit_code"] == 1 and not report["contract_mismatch"], report + change(project, "exercise.py", "fee=-10", "fee=5") + report = Supervisor(project / "melampus.toml").check() + assert report["exit_code"] == 0, report + + +@pytest.mark.parametrize("bad_first", [True, False]) +def test_conflicting_declaration_stays_incomplete_after_valid_instances(project, bad_first): + conflict = """ +from melampus import Check, Contract, instrument +from service import PricingService + +weakened = Contract("Return a nonnegative price in cents", (Check("nonnegative", lambda n: True, "Price is a nonnegative integer."),)) +instrument(PricingService(), namespace="pricing:PricingService", contracts={"price": weakened}).price(0) +""" + exercise = project / "exercise.py" + original = exercise.read_text() + exercise.write_text(conflict + original if bad_first else original + conflict) + report = Supervisor(project / "melampus.toml").check() + assert report["exit_code"] == 2 and report["contract_mismatch"] == [ + "pricing:PricingService.price" + ], report + + +@pytest.mark.parametrize( + "mutation", ["unregistered", "raw_reference", "missing_call", "suppressed"] +) +def test_registration_bypass_or_suppression_is_incomplete(project, mutation): + if mutation == "unregistered": + change( + project, + "registration.py", + 'PricingService(), namespace="pricing:PricingService", contracts={"price": PRICE}', + 'PricingService(), namespace="other:PricingService", contracts={"price": PRICE}', + ) + elif mutation == "raw_reference": + change( + project, + "exercise.py", + "from registration import pricing, service", + "from registration import pricing, service\nfrom functions import price as raw", + ) + change(project, "exercise.py", "pricing.price(cents)", "raw(cents)") + elif mutation == "missing_call": + change(project, "exercise.py", " service.price(cents)", " pass") + else: + change( + project, + "registration.py", + "from melampus import instrument", + "from melampus import instrument, DEFAULT_POLICY\nDEFAULT_POLICY.configure(disabled_paths=['pricing:PricingService.price'])", + ) + report = Supervisor(project / "melampus.toml").check() + assert report["exit_code"] == 2 and report["missing"], report diff --git a/tests/types/public_api.py b/tests/types/public_api.py new file mode 100644 index 0000000..59d90f3 --- /dev/null +++ b/tests/types/public_api.py @@ -0,0 +1,36 @@ +"""Static assertions: registration and decorators retain ordinary callable types.""" + +from typing import assert_type + +from melampus import Check, Contract, instrument + +PRICE = Contract("nonnegative", (Check("nonnegative", lambda n: n >= 0, "nonnegative"),)) + + +class PricingService: + def price(self, cents: int, *, fee: int = 0) -> int: + return max(0, cents) + fee + + async def async_price(self, cents: int) -> int: + return self.price(cents) + + +service = instrument( + PricingService(), + namespace="pricing:PricingService", + contracts={"price": PRICE, "async_price": PRICE}, +) +assert_type(service, PricingService) +assert_type(service.price(10, fee=1), int) + + +async def async_usage() -> None: + assert_type(await service.async_price(10), int) + + +@PRICE.instrument(path="pricing:price") +def price(cents: int) -> int: + return max(0, cents) + + +assert_type(price(10), int) From 3338da7eb436272134ff84276cdce42608280b59 Mon Sep 17 00:00:00 2001 From: Melampus Admin Date: Fri, 2 Oct 2026 01:00:37 +0700 Subject: [PATCH 2/3] release: accept ADR-0009 and prepare 0.2.0 alpha --- CHANGELOG.md | 2 + README.md | 3 +- VERSION | 2 +- docs/AGENT-SESSION.md | 2 +- docs/RELEASE.md | 51 +++++++++++++--------- docs/SDK-REGISTRATION.md | 4 +- docs/SDK-UX-RESEARCH.md | 5 +++ docs/adr/0009-explicit-sdk-registration.md | 2 +- 8 files changed, 45 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc16a9a..ac1eb39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ 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 diff --git a/README.md b/README.md index db5d541..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.2.0 alpha is in development; no PyPI release is claimed here.** 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. 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 ffbbdbb..e963b87 100644 --- a/docs/AGENT-SESSION.md +++ b/docs/AGENT-SESSION.md @@ -6,7 +6,7 @@ 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 development) +## Registration alternative (0.2.0) For existing services, register reviewed contracts at application setup with `instrument(service, namespace=..., contracts=...)`, keeping business methods diff --git a/docs/RELEASE.md b/docs/RELEASE.md index ca5904f..1470eb7 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -1,10 +1,10 @@ -# First release: 0.1.0 alpha +# Releases and publishing -## Next alpha: registration and onboarding +## 0.2.0 alpha: registration and onboarding -The 0.2.0 development branch mirrors TypeScript 0.2.0's explicit class/module +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. The package version remains 0.1.0 until a reviewed release bump. +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`. @@ -15,7 +15,7 @@ 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. -## Scope and evidence +## 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 @@ -90,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 | | --- | --- | @@ -98,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 index f2af116..a4137d2 100644 --- a/docs/SDK-REGISTRATION.md +++ b/docs/SDK-REGISTRATION.md @@ -1,8 +1,8 @@ # Choose the integration style that fits your code -The 0.2.0 development branch adds `instrument` for existing service instances +Version 0.2.0 adds `instrument` for existing service instances and module boundaries. The 0.1.0 artifact supports the existing function -decorators. No PyPI publication is implied by these docs. +decorators. PyPI publication is separate from GitHub releases. | Your code | Start with | Main tradeoff | | --- | --- | --- | diff --git a/docs/SDK-UX-RESEARCH.md b/docs/SDK-UX-RESEARCH.md index c0cc0b6..8938fe1 100644 --- a/docs/SDK-UX-RESEARCH.md +++ b/docs/SDK-UX-RESEARCH.md @@ -1,5 +1,10 @@ # 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 diff --git a/docs/adr/0009-explicit-sdk-registration.md b/docs/adr/0009-explicit-sdk-registration.md index e04d7b7..1d48452 100644 --- a/docs/adr/0009-explicit-sdk-registration.md +++ b/docs/adr/0009-explicit-sdk-registration.md @@ -1,6 +1,6 @@ # ADR-0009: Explicit registration with native decorator compatibility -Status: accepted for the 0.2.0 development branch (2026-10-01). +Status: accepted for 0.2.0 (2026-10-02), confirmed by the project owner. ## Context From 13fdc592bcac3fbe4811bc793201600102f6a4a7 Mon Sep 17 00:00:00 2001 From: Melampus Admin Date: Fri, 2 Oct 2026 01:06:23 +0700 Subject: [PATCH 3/3] docs: update public site for 0.2.0 onboarding --- site/index.html | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) 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 @@ - Melampus 0.1.0 — keep coding agents aligned + Melampus 0.2.0 — keep coding agents aligned @@ -27,7 +27,7 @@
-

OPEN-SOURCE ALPHA · v0.1.0

+

OPEN-SOURCE ALPHA · v0.2.0

Keep the coding agent
inside the reviewed intent.

Melampus runs beside an AI coding session. When generated code drifts, it turns @@ -35,14 +35,14 @@

Keep the coding agent
inside the reviewed intent.

15
contract evaluations in the demo
0.84s
observed drift detection
1
agent edit to restore the contract
-

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.

@@ -60,9 +60,10 @@

Evidence reaches the agent while the code is still being written.

03

Gate decides

Healthy work proceeds. Drift or missing evidence returns the session to repair.

-
TERMINAL A · SUPERVISOR
melampus session \
-  --config examples/agent-session/melampus.yml
-
TERMINAL B · CODING AGENT
claude
+          
TERMINAL A · SUPERVISOR
cd examples/sdk-registration
+melampus session
+
TERMINAL B · CODING AGENT
cd examples/sdk-registration
+claude
 # Codex or another agent can use the same gate
@@ -115,23 +116,26 @@

The oracle is familiar. The control point is different.

TRY THE ALPHA

-

Run the recorded example on your machine.

-

The package is available as a verified wheel on the v0.1.0 GitHub release. Production PyPI publishing is still being configured.

+

Decorate a function. Register an existing service.

+

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