diff --git a/.github/actions/setup-ci-tools/action.yml b/.github/actions/setup-ci-tools/action.yml
index 8a7c397..bd693e2 100644
--- a/.github/actions/setup-ci-tools/action.yml
+++ b/.github/actions/setup-ci-tools/action.yml
@@ -16,13 +16,13 @@ runs:
steps:
- name: Set up Python
if: inputs.python-version != ''
- uses: actions/setup-python@v6
+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
with:
python-version: ${{ inputs.python-version }}
- name: Cache Python virtualenv
if: inputs.python-version != '' && inputs.python-packages != ''
- uses: actions/cache@v6
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: .venv/ci
key: ${{ runner.os }}-py${{ inputs.python-version }}-venv-${{ hashFiles('.github/actions/setup-ci-tools/action.yml', '.github/workflows/*.yml') }}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..72e2bbd
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,55 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches: [main]
+permissions:
+ contents: read
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ quality:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ python: ["3.11", "3.14"]
+ include:
+ - os: ubuntu-latest
+ python: "3.12"
+ - os: ubuntu-latest
+ python: "3.13"
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7
+ with:
+ version: "0.12.17"
+ python-version: ${{ matrix.python }}
+ enable-cache: true
+ - run: make ci
+ - name: Report equivalent-work and total adoption overhead
+ if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11'
+ run: make benchmark
+ collector:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7
+ with:
+ version: "0.12.17"
+ python-version: "3.11"
+ - run: make dev
+ - run: docker compose -f examples/demo/compose.yaml up -d
+ - name: Wait for collector and verify both sessions
+ run: |
+ for _ in $(seq 1 30); do
+ if curl --silent --output /dev/null http://127.0.0.1:4319/v1/traces; then break; fi
+ sleep 1
+ done
+ uv run --locked python scripts/demo_session.py --collector http://127.0.0.1:4319/v1/traces --watch-host 0.0.0.0 --watch-port 4318
+ - if: always()
+ run: docker compose -f examples/demo/compose.yaml logs
+ - if: always()
+ run: docker compose -f examples/demo/compose.yaml down
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..c1ee770
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,71 @@
+name: Publish Python package
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: Existing validated release tag (for example v0.1.0)
+ required: true
+ type: string
+ registry:
+ description: Destination with a configured trusted publisher
+ required: true
+ default: testpypi
+ type: choice
+ options: [testpypi, pypi]
+permissions:
+ contents: read
+concurrency:
+ group: publish-${{ inputs.registry }}
+ cancel-in-progress: false
+jobs:
+ build:
+ if: github.ref == 'refs/heads/main'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Validate tag input
+ env:
+ RELEASE_TAG: ${{ inputs.tag }}
+ run: '[[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]'
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ ref: ${{ inputs.tag }}
+ fetch-depth: 0
+ - name: Verify release provenance and version
+ env:
+ RELEASE_TAG: ${{ inputs.tag }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ test "$RELEASE_TAG" = "v$(cat VERSION)"
+ git merge-base --is-ancestor HEAD origin/main
+ test "$(gh release view "$RELEASE_TAG" --json isDraft --jq .isDraft)" = false
+ - uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7
+ with:
+ version: "0.12.17"
+ python-version: "3.11"
+ - run: make ci
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: python-distributions
+ path: dist/
+ if-no-files-found: error
+ retention-days: 7
+ publish:
+ needs: build
+ runs-on: ubuntu-latest
+ environment: ${{ inputs.registry }}
+ permissions:
+ id-token: write
+ steps:
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
+ with:
+ name: python-distributions
+ path: dist/
+ - name: Publish to TestPyPI
+ if: inputs.registry == 'testpypi'
+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
+ with:
+ repository-url: https://test.pypi.org/legacy/
+ - name: Publish to PyPI
+ if: inputs.registry == 'pypi'
+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8d9846c..a7a0d7b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,58 +1,51 @@
name: Release
-
-# Merge-side release: on push to main, if VERSION has no matching v* tag yet,
-# create the annotated tag and publish a GitHub Release with auto-assembled notes.
-#
-# Hardening: every action is pinned to an immutable commit SHA (tag in a trailing
-# comment), not a movable @vN tag.
-
on:
push:
branches: [main]
- paths:
- - "VERSION"
- - "CHANGELOG.md"
-
+ paths: [VERSION, CHANGELOG.md]
+ workflow_dispatch:
permissions:
- contents: write
-
+ contents: read
+concurrency:
+ group: release
+ cancel-in-progress: false
jobs:
release:
+ if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
+ permissions:
+ contents: write
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 0
fetch-tags: true
-
- - name: Set up cached CI tools
- uses: ./.github/actions/setup-ci-tools
-
- - name: Tag & release when VERSION has no tag
+ - uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7
+ with:
+ version: "0.12.17"
+ python-version: "3.11"
+ - name: Validate and build before tagging
+ run: make ci
+ - name: Tag and publish validated GitHub artifacts
env:
GH_TOKEN: ${{ github.token }}
run: |
- git config user.name "github-actions[bot]"
+ set -euo pipefail
+ git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
-
ver="$(tr -d '[:space:]' < VERSION)"
- [ -n "$ver" ] || { echo "::error::VERSION is empty"; exit 1; }
+ [[ "$ver" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid VERSION'; exit 1; }
tag="v$ver"
-
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
- echo "$tag already exists — nothing to release."
- exit 0
- fi
-
- prev="$(git tag --list 'v*' | sort -V | tail -1)"
- echo "Releasing $tag (previous: ${prev:-none})"
- if [ -n "$prev" ]; then
- python3 release/_lib/release_notes.py "$ver" --prev-tag "$prev" > notes.md
+ if gh release view "$tag" >/dev/null 2>&1; then
+ echo "$tag already released"
+ exit 0
+ fi
+ test "$(git rev-list -n 1 "$tag")" = "$GITHUB_SHA" || { echo 'Existing tag does not identify this build'; exit 1; }
else
- python3 release/_lib/release_notes.py "$ver" > notes.md
+ uv run --locked python release/_lib/version_check.py --strict
+ git tag -a "$tag" -m "$tag"
+ git push origin "$tag"
fi
-
- git tag -a "$tag" -m "v$ver"
- git push origin "$tag"
- gh release create "$tag" --title "v$ver" --notes-file notes.md
- echo "::notice::Released $tag"
+ uv run --locked python release/_lib/release_notes.py "$ver" > notes.md
+ gh release create "$tag" --verify-tag --prerelease --title "$tag (alpha)" --notes-file notes.md dist/*
diff --git a/.github/workflows/version-guard.yml b/.github/workflows/version-guard.yml
index 6ac3310..83331c4 100644
--- a/.github/workflows/version-guard.yml
+++ b/.github/workflows/version-guard.yml
@@ -52,7 +52,7 @@ jobs:
set -e
- name: Post guard result
- if: steps.changed.outputs.changed == 'true' && always()
+ if: steps.changed.outputs.changed == 'true' && always() && github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
with:
script: |
diff --git a/.gitignore b/.gitignore
index e73faa4..f385dc1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,6 +56,7 @@ ENV/
.claude/settings.local.json
.cursor/settings.local.json
.mcp.local.json
+.melampus/
# macOS
.DS_Store
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..35589a7
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,13 @@
+repos:
+ - repo: local
+ hooks:
+ - id: ruff-check
+ name: ruff check
+ entry: uv run --locked ruff check --fix --exit-non-zero-on-fix
+ language: system
+ types: [python]
+ - id: ruff-format
+ name: ruff format
+ entry: uv run --locked ruff format
+ language: system
+ types: [python]
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 960d355..50ba339 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.1.0] - 2026-09-28
+
+### Added
+
+- Local AI coding-session supervisor, reviewed SDK Contract objects, fresh-process
+ scenario execution, required-check coverage, and revision-bound repair evidence.
+- Agent-neutral gate and synchronous Claude Code hooks that restrict progression
+ and completion during drift/incomplete evidence while permitting scoped repair.
+- Runnable generation/drift/repair example and setup guide; local coding is the
+ first-release focus, with broader service monitoring reserved for expansion.
+- Experimental `code_artifact` schema, generated constants and compatibility fixtures.
+- OTel API-only `instrumented` decorator for synchronous and async functions.
+- Hash-only declarations, predicate results, deterministic check sampling, shared
+ per-process execution limits, and runtime path disabling.
+- Optional OTLP/HTTP protobuf watcher with finite sessions, bounded ingestion,
+ duplicate suppression and explicit incomplete-evidence exit codes.
+- Direct and stock collector demos, test suite, typing, package checks, CI, and
+ separate Trusted Publishing workflow for TestPyPI/PyPI.
+- Apache-2.0 license, quickstart, contribution and release documentation.
+
+### Known limitations
+
+- Alpha wire/API stability; no content capture, gRPC/JSON receiver, or durable backend.
+- Local sessions support macOS/Linux and reviewed executable claims on exercised
+ inputs; they do not infer arbitrary intent or detect all generated-code defects.
+- The founding spec's <3% overhead target remains unmet; see docs/RELEASE.md.
+
## [0.0.0] - 2026-08-22
### Added
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..e04a0d8
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,35 @@
+# Contributing
+
+Use Python 3.11+ and uv. Work on a branch in a dedicated worktree; see CLAUDE.md.
+
+```sh
+uv sync --locked --all-extras
+uv run --locked pre-commit install
+make ci
+```
+
+`make format` changes formatting; `make lint` is read-only. `uv.lock` pins developer
+tools; CI runs the same Make targets. Run `make test` for a focused functional check,
+`make cov` for coverage, and `make benchmark` for overhead measurements.
+`make demo` exercises the local coding-session protocol and repair cycle without
+an LLM request; `make demo-otlp` exercises the optional tracing foundation.
+Subprocess coverage is enabled so disposable scenario runners are measured too.
+
+Wire names originate in `semconv/code_artifact.yaml`. After a reviewed wire change:
+
+```sh
+uv run --locked python scripts/generate_semconv.py
+make semconv
+```
+
+The generator validates against the vendored upstream Weaver JSON Schema and
+checks generated names/docs. Update fixtures and both producer/consumer tests.
+Do not add raw data to telemetry or interpret suppressed checks as passes.
+
+Pull requests should explain the behavior change and show relevant verification.
+Add regression tests for bugs and exercise the installed wheel for packaging changes.
+Keep source compatibility for sync/async calls and avoid configuring global OTel
+providers or exporters inside the library. Licensing follows Apache-2.0.
+
+Version changes go through VERSION and CHANGELOG.md. Never create release tags
+manually; see [release operations](docs/RELEASE.md).
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..2c6f438
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,29 @@
+.PHONY: dev lint typecheck test cov semconv build ci format demo demo-otlp benchmark
+
+dev:
+ uv sync --locked --all-extras
+lint:
+ uv run --locked ruff check .
+ uv run --locked ruff format --check .
+typecheck:
+ uv run --locked mypy -p melampus
+test:
+ uv run --locked pytest
+cov:
+ uv run --locked pytest --cov=melampus --cov-report=term-missing --cov-fail-under=85
+semconv:
+ uv run --locked python scripts/generate_semconv.py --check
+build:
+ uv build --no-build-isolation
+ uv run --locked twine check --strict dist/*
+ uv run --locked python scripts/check_dist.py
+ci: dev semconv lint typecheck cov build
+format:
+ uv run --locked ruff check --fix .
+ uv run --locked ruff format .
+demo:
+ uv run --locked python scripts/demo_agent_session.py
+demo-otlp:
+ uv run --locked python scripts/demo_session.py
+benchmark:
+ uv run --locked python benchmarks/overhead.py
diff --git a/README.md b/README.md
index 36b7f28..55e4fab 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,210 @@
-# melampus-python
+# Melampus
+
+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
+wire schema are experimental. The supervisor needs no SaaS, LLM judge, tracing
+backend, collector, or unit-test framework. Python 3.11+, macOS/Linux.
+
+For a one-command demonstration of detection, agent hook decisions, and recovery:
+`uv sync --locked --all-extras && make demo` (no model request is made).
+
+See the [recorded Claude Code repair](docs/demos/pricing-session/README.md) for a
+visual walkthrough, actual hook logs, source comparison, and commands to record
+the same example with your own agent account.
+
+## Start beside your coding agent
+
+```text
+Reviewed intent + SDK checks + executable scenario
+ ↓
+Agent writes instrumented code → local supervisor executes fresh code
+ ↑ ↓
+ └──── repair ← drift / missing evidence
+ ↓
+ healthy → continue the next change
+```
+
+From this checkout, install the session dependencies and activate the same
+environment in both terminals:
+
+```sh
+uv sync --locked --all-extras
+source .venv/bin/activate
+cd examples/agent-session
+melampus session
+```
+
+In another terminal, activate that environment, enter `examples/agent-session`,
+and start `claude`. The example includes reviewed contracts, an input scenario,
+agent instructions, and synchronous hooks. Review/enable the project hooks in
+Claude Code before using them. Ask it to change `pricing.py`; it must preserve
+the imported SDK contract. The supervisor polls source changes every 0.5 seconds
+and checks the current revision again at each hook boundary.
+
+Drift blocks shell/other progression tools and completion while leaving reads
+and scoped Edit/Write repairs available. The gate reopens after fresh healthy
+evidence. Removed instrumentation, skipped required checks, timeouts, crashes,
+changed contracts, and a dead supervisor cannot count as a pass.
+
+**Start here:** [setup and repair walkthrough](examples/agent-session/README.md) ·
+[agent integration, limits, and test/CI comparison](docs/AGENT-SESSION.md).
+
+This detects violations of **reviewed executable claims on exercised inputs**.
+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
+
+Keep the reviewed definition in `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:price": PRICE}
+```
+
+The agent writes `pricing.py`:
+
+```python
+from intent import PRICE
+
+
+@PRICE.instrument(generator="claude-code")
+def price(cents: int) -> int:
+ return max(0, cents)
+```
+
+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.
+
+## Optional OTLP foundation demo
+
+Requires Python 3.11+ and [uv](https://docs.astral.sh/uv/getting-started/installation/).
+From this repository:
+
+```sh
+uv sync --locked --all-extras
+make demo-otlp
+```
+
+This lower-level demo starts a finite watcher session, sends real OTLP from a healthy call,
+then repeats with a seeded failure. It verifies zero healthy findings, exactly
+one drift finding, and the corresponding exit codes. The watcher prints the
+function, rule ID, contract hash, predicate result, and trace/span references.
+
+To install from source without uv:
+
+```sh
+python -m pip install '.[watch,demo]'
+python scripts/demo_session.py
+```
+
+## Instrument a function
+
+```python
+from melampus import Check, instrumented
+
+
+@instrumented(
+ intent="Return a nonnegative price in cents",
+ checks=[Check("nonnegative", lambda result: result >= 0, contract="Result is nonnegative")],
+)
+def price():
+ return 1200
+```
+
+Configure your application's OTel tracer provider and exporter as usual; the
+library only uses the OTel API. See [the executable demo](https://github.com/melampus-org/melampus-python/blob/main/examples/demo/service.py)
+for a complete configuration. Without a recording tracer, no checks run.
+Ordinary and async functions are supported; generators are rejected.
+
+A check receives the successful return value and must return exactly `bool`.
+Use pure, fast synchronous predicates. Failed checks and ordinary check exceptions
+do not alter the application's return value. Application exceptions and async
+cancellation propagate unchanged. Python predicates are not sandboxed.
+
+## Watch a test or canary session
+
+```sh
+melampus watch --duration 30
+# In another terminal, send and flush OTLP/HTTP traces to:
+# http://127.0.0.1:4318/v1/traces
+```
+
+The optional `watch` extra provides the protobuf receiver. `/healthz` indicates
+readiness. The default interface is loopback; `--port 0` chooses a free port.
+The duration starts at readiness. Producers must flush and collectors must drain
+before it expires. Without a duration, Ctrl-C ends the session and prints its summary.
+
+| Exit | Meaning |
+| --- | --- |
+| 0 | At least one evaluated check; no failures or incomplete evidence |
+| 1 | One or more failed checks |
+| 2 | No evaluated checks, check errors, invalid/unknown telemetry, capacity exhaustion, or other incomplete evidence |
+
+Exit 2 takes precedence over drift. Suppressed checks never count as passes.
+A healthy summary only describes the checks that were actually observed; it does
+not prove all paths ran. Duplicate span deliveries are ignored within one session.
+
+For the stock collector route, see [the collector demo](https://github.com/melampus-org/melampus-python/blob/main/examples/demo/README.md).
+
+## Privacy and cost controls
+
+Melampus exports SHA-256 declarations and bounded identifiers/results. It never
+captures arguments, raw return values, intent prose, or exception messages.
+`capture_content=True` is unsupported and raises immediately. Hashes are
+identifiers, **not anonymization**; function/check names are visible metadata.
+Other instrumentation and application exporters remain your responsibility.
+
+```python
+from melampus import Check, Policy, instrumented
+
+policy = Policy(checks_per_second=100)
+
+
+@instrumented(
+ intent="Return a valid result",
+ policy=policy,
+ checks=[Check("valid", lambda result: result >= 0, "Result is nonnegative", sample=0.1)],
+)
+def compute():
+ return 1
+
+
+# Runtime operator control; use the emitted module:qualified_name exactly.
+policy.configure(checks_per_second=100, disabled_paths=["my_app:compute"])
+```
+
+Share one Policy across functions to share a **per-process**, one-second fixed-window
+execution limit. By default all functions share `DEFAULT_POLICY` with no limit.
+This limits check counts, not CPU time or aggregate cost across worker processes.
+Sampling can miss rare failures. OTel sampling and attribute limits also affect visibility.
+
+## Status and development
+
+The original **<3% checks-off overhead target is not yet met** against a bare
+recording OTel span. The alpha distinguishes wrapper overhead from the cost of
+carrying declarations, using an equivalent manual span as the wrapper baseline.
+See [release evidence and limitations](https://github.com/melampus-org/melampus-python/blob/main/docs/RELEASE.md).
+There is no claim that this alpha is ready for unrestricted production exposure.
+
+```sh
+make ci # locked dependencies, semconv, lint, typing, coverage, package checks
+make benchmark # report actual latency; not a noise-sensitive CI pass/fail gate
+```
+
+[Contributing](https://github.com/melampus-org/melampus-python/blob/main/CONTRIBUTING.md) · [Security](https://github.com/melampus-org/melampus-python/blob/main/SECURITY.md) ·
+[Wire attributes](https://github.com/melampus-org/melampus-python/blob/main/semconv/README.md) · [First-release contract](https://github.com/melampus-org/melampus-python/blob/main/docs/adr/0006-first-release-contract.md) ·
+[Founding spec](https://github.com/melampus-org/melampus-python/blob/main/docs/SPEC.md)
+
+Licensed under [Apache-2.0](https://github.com/melampus-org/melampus-python/blob/main/LICENSE).
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..db6e0c7
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,35 @@
+# Security
+
+The primary workflow runs reviewed local scenarios alongside a coding agent.
+Scenarios and generated implementations run with the user's permissions; the
+fresh process is not a sandbox. Use deterministic local inputs and avoid
+production credentials or destructive side effects. The supervisor bounds each
+run and terminates its process group, but cannot control deliberately detached
+children or external side effects.
+
+The local session gate uses a per-session token and loopback binding. Its state
+file is owner-readable/writable. This protects against accidental cross-session
+requests, not a hostile process running as the same user. Hook enforcement
+requires enabled synchronous hooks and a cooperative agent; it is not an OS
+security boundary. Missing/stale evidence blocks normal progression.
+
+The optional OTLP path supports local/CI observation and trusted-network collector forwarding.
+The watcher has no authentication or TLS and is not a durable tracing backend.
+Keep its default loopback bind; secure any remote deployment outside this process.
+
+Requests and decompressed payloads are capped at 1 MiB; session deduplication is
+capped at 100,000 spans by default. These bounds do not make the Python HTTP server
+suitable for hostile public traffic. Exceeding capacity makes the session incomplete.
+
+Checks execute ordinary Python in the application process. They must be trusted,
+pure, fast, synchronous code. A check can mutate an object or block indefinitely;
+Melampus cannot prevent that. The execution budget limits count, not runtime.
+
+Hashes are not anonymization. Function paths, check IDs and generator labels are
+visible. Avoid sensitive identifiers. SDK checks never capture application values
+or exception text, but other OTel instrumentation may do so.
+
+For a suspected vulnerability, use GitHub's private vulnerability reporting if
+enabled for this repository. Otherwise contact the maintainers privately through
+their GitHub profiles before sharing details; do not put exploit details or secrets
+in a public issue. Only the latest alpha is maintained until a stable policy exists.
diff --git a/VERSION b/VERSION
index 77d6f4c..6e8bf73 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.0
+0.1.0
diff --git a/benchmarks/overhead.py b/benchmarks/overhead.py
new file mode 100644
index 0000000..38f964f
--- /dev/null
+++ b/benchmarks/overhead.py
@@ -0,0 +1,83 @@
+"""Compare equivalent OTel work and also report the total declaration cost."""
+
+from __future__ import annotations
+
+import json
+import platform
+import statistics
+import timeit
+
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+
+from melampus import instrumented
+
+
+def build_operation(tracer):
+ @instrumented(intent="Return one", tracer=tracer)
+ def operation():
+ return 1
+
+ return operation
+
+
+def main():
+ # Capture exactly the declaration that the decorated operation emits. The
+ # capture provider is shut down before measurement; timed spans have no exporter.
+ capture = TracerProvider()
+ exporter = InMemorySpanExporter()
+ capture.add_span_processor(SimpleSpanProcessor(exporter))
+ build_operation(capture.get_tracer("capture"))()
+ sample = exporter.get_finished_spans()[0]
+ attributes, name = dict(sample.attributes), sample.name
+ capture.shutdown()
+
+ provider = TracerProvider()
+ tracer = provider.get_tracer("benchmark")
+ decorated = build_operation(tracer)
+
+ def bare():
+ with tracer.start_as_current_span(
+ name, record_exception=False, set_status_on_exception=False
+ ):
+ return 1
+
+ def equivalent():
+ with tracer.start_as_current_span(
+ name, attributes=attributes, record_exception=False, set_status_on_exception=False
+ ):
+ return 1
+
+ cases = [("bare", bare), ("equivalent", equivalent), ("instrumented", decorated)]
+ samples = {name: [] for name, _ in cases}
+ for round_number in range(15):
+ # Rotate measurement order to reduce drift bias; retain all raw rounds.
+ offset = round_number % len(cases)
+ for label, function in cases[offset:] + cases[:offset]:
+ samples[label].append(timeit.timeit(function, number=20_000) / 20_000 * 1e6)
+ median = {name: statistics.median(values) for name, values in samples.items()}
+ total_overhead = (median["instrumented"] / median["bare"] - 1) * 100
+ wrapper_overhead = (median["instrumented"] / median["equivalent"] - 1) * 100
+ print(
+ json.dumps(
+ {
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ "median_us": median,
+ "rounds_us": samples,
+ "total_overhead_percent": total_overhead,
+ "wrapper_overhead_percent": wrapper_overhead,
+ "original_bare_span_target_percent": 3.0,
+ "original_bare_span_target_met": total_overhead < 3.0,
+ "alpha_equivalent_span_target_percent": 3.0,
+ "alpha_equivalent_span_target_met": wrapper_overhead < 3.0,
+ },
+ indent=2,
+ )
+ )
+ provider.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/AGENT-SESSION.md b/docs/AGENT-SESSION.md
new file mode 100644
index 0000000..311bc4f
--- /dev/null
+++ b/docs/AGENT-SESSION.md
@@ -0,0 +1,192 @@
+# Keep generated code inside reviewed intent
+
+Melampus 0.1.0 focuses on the **local coding loop**. A dedicated supervisor runs
+beside the agent, observes source changes, exercises the actual implementation,
+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.
+
+## What you review, and what the agent writes
+
+1. **Approve intent once.** Put a small set of `Contract` objects in a Python
+ module. Each carries intent prose, optional assumptions, and pure synchronous
+ `Check` predicates over successful return values. Export `CONTRACTS`, mapping
+ exact `module:qualified_name` identifiers to those objects. Use unsampled
+ checks. Predicates must express meaningful behavior, not simply return True.
+2. **Provide executable inputs.** Write a short scenario that imports real entry
+ points and calls them with representative/boundary inputs. Assertions live
+ in the SDK contracts; the scenario need not duplicate them as unit tests.
+ Review any fixtures and helper modules the scenario depends on too.
+3. **Define the scope.** List source files/directories in `watch`. Include every
+ local dependency whose changes can affect the scenario, including data/config
+ inputs. List reviewed helper files in `protect`. Contract module, scenario,
+ and configuration are protected automatically. State the allowed scope in
+ the agent's instructions.
+4. **Start the supervisor.** Run `melampus session` in a dedicated terminal.
+ At startup it pins hashes of reviewed files. Each changed revision starts
+ a fresh interpreter, with an always-on tracer and synchronous local evidence
+ collection. It runs no LLM and requires no tracing server.
+5. **Start the agent with hooks.** The agent imports the approved contract and
+ generates functions using `@CONTRACT.instrument()`. The included Claude Code
+ settings request current evidence before/after tools and before completion.
+ Verify that the hooks are enabled; instructions alone are not enforcement.
+6. **Repair immediately on evidence.** A failed predicate identifies its
+ function/check and trace reference. Read the contract, repair the watched
+ implementation with Edit/Write, and let the supervisor rerun. Only a current
+ healthy result permits normal progression. Escalate a mistaken contract or
+ three unsuccessful repairs to the owner; never weaken claims to get green.
+
+See the [runnable example](../examples/agent-session/README.md).
+
+## Minimal configuration
+
+`melampus.toml` lives in the project root; paths resolve from that directory:
+
+```toml
+contracts = "intent" # intent.py exports CONTRACTS; a root-level module
+probe = "exercise.py" # calls real entry points with reviewed inputs
+watch = ["src", "config.json"]
+python_paths = [".", "src"] # defaults to ["."]
+protect = ["fixtures.py", ".claude/settings.json", "CLAUDE.md"]
+timeout = 5 # >0 and <=10 seconds, includes interpreter startup
+```
+
+Watched directories are recursive. VCS, virtualenv, Melampus state, bytecode,
+and common tool-cache directories are ignored. Prefer a focused source scope
+over watching a whole repository with generated assets. All paths stay inside
+the project root. The first session implementation supports macOS/Linux.
+
+Start one supervisor per worktree, with a separate state file for each:
+
+```sh
+melampus session --config melampus.toml --state .melampus/session.json
+melampus gate --state .melampus/session.json
+```
+
+The second command queries the live supervisor and returns JSON plus exit
+0 (healthy), 1 (drift), or 2 (incomplete). It never trusts a saved green report.
+The state file holds a local port and a per-session token, has owner-only
+permissions, and is removed on Ctrl-C. A lock prevents two supervisors claiming
+the same state file. Stop and restart only after owner review when contracts
+or scenarios intentionally change. Different worktrees need independent setup.
+
+## How the loop decides
+
+```mermaid
+flowchart LR
+ I[Reviewed SDK contract] --> A[Agent edits implementation]
+ A --> S[Source snapshot]
+ S --> E[Fresh interpreter executes scenario]
+ E --> D{All required checks observed?}
+ D -->|No / error / stale| R[Restrict session to repair]
+ D -->|Yes| V{Any predicate failed?}
+ V -->|Yes| R
+ V -->|No| C[Allow progression]
+ R --> A
+ C --> A
+```
+
+| Evidence | State | Agent action |
+| --- | --- | --- |
+| Every required function/check observed; all pass | Healthy / 0 | Continue within the approved scope |
+| At least one failed predicate | Drift / 1 | Inspect named contract and repair implementation |
+| Missing decorator/function/check, suppression, errors, timeout, stale revision, changed reviewed files, unavailable supervisor | Incomplete / 2 | Repair or request owner help; no success claim |
+
+Incomplete takes precedence over drift. Evidence is scoped to the observed
+source revision. Changes during execution invalidate that run. Required checks
+cannot be hidden by unrelated passing checks. The runner validates identity of
+the reviewed predicate objects at decoration time, not just their names/text.
+It uses fresh bytecode paths so quick, same-size edits do not reuse stale imports.
+
+## Claude Code: what is actually blocked
+
+Install the example `.claude/settings.json` entries into your existing settings
+without replacing unrelated hooks. Activate the environment containing Melampus
+before launching Claude, or use the absolute path to its executable in each
+hook command. Keep the hook timeout at 30 seconds; Melampus's client deadline is
+25 seconds and each scenario is capped at 10 seconds. Do not use async hooks.
+
+| Hook | Result while drift/incomplete |
+| --- | --- |
+| `PreToolUse` | Deny shell, delegation, and other progression tools. Allow Read/Grep/Glob/AskUserQuestion and Edit/Write only within watched implementation paths. |
+| `PostToolUse` | Return block feedback with evidence so the next action addresses repair. The completed edit has already happened. |
+| `PostToolUseFailure` | Inject current repair evidence after a failed tool call. |
+| `Stop` | Block successful completion until evidence is healthy. |
+
+Direct Edit/Write outside the watched scope is denied even when healthy. Reviewed
+files are never repair targets. A healthy shell command can still change a
+protected file; the next observation then marks the session incomplete.
+
+These choices follow the [Claude Code hook protocol](https://code.claude.com/docs/en/hooks).
+The integration is a cooperative development guardrail, not a security sandbox.
+An agent or user with OS access can disable hooks, tamper with the package,
+forge evidence, or restart the session. Hook host timeouts/misconfiguration can
+also prevent enforcement; the host's lifecycle remains authoritative. Already
+running or parallel tools are not retroactively canceled. Use one coding agent
+per scoped worktree for the alpha. The supervisor does not interrupt model tokens
+mid-generation; detection begins after a file changes and its scenario executes.
+
+## Other agents and automation
+
+`melampus gate` is the agent-neutral boundary. A controller calls it before
+allowing the next operation, after an edit, and before accepting completion:
+
+```text
+gate=0 → permit next scoped action
+gate=1 or 2 → permit inspection/repair only → edit → gate again
+```
+
+That controller must honor the return code, preserve repair access, and feed
+the JSON report back to its model. An instruction to "remember to run the gate"
+does not guarantee enforcement. Only the Claude Code hook adapter is bundled
+in this alpha; no native Codex/other-agent hook integration is claimed.
+
+## How this differs from tests and CI
+
+| Question | Unit/property tests | CI | Melampus local session |
+| --- | --- | --- | --- |
+| What is it? | Executable assertions about behavior | An orchestrator for checks | An orchestrator for reviewed SDK contracts and repair feedback |
+| When does it run? | Whenever invoked, including on every edit | Usually on push/PR; configurable | On watched changes and synchronous agent boundaries |
+| Where is expected behavior? | Test oracle/assertions | In tools it invokes | Frozen contract objects imported by generated functions |
+| Does it need exercised inputs? | Yes | Depends on its checks | Yes: short scenarios drive real code |
+| What stops the agent? | A separate hook/controller | Often only merge gates | Bundled Claude hooks restrict progression until repair passes |
+| Can AI produce weak assertions? | Yes | Inherits that weakness | Yes: independent contract/scenario review remains necessary |
+| Main strength | Broad, mature correctness techniques | Reproducible team-wide checks | Fast local feedback with checks attached to generated units |
+| Main cost | Maintaining assertions and fixtures | Runtime/queue and integration cost | Contract setup, scenario latency, explicit scope, hook integration |
+
+Melampus uses the same fundamental idea of an executable oracle. Existing tests
+with good hooks can catch many of the same failures; Melampus does not have a
+special ability to know intent. Its contribution is a reusable contract-carrying
+SDK plus the local enforcement/repair loop and explicit missing-evidence state.
+It reduces duplicate assertion code when the same contract travels with the
+function. It does not remove the need to review the oracle, exercise behavior,
+or retain valuable tests, static checks, and CI.
+
+Run `python examples/agent-session/compare_with_unit_tests.py` for a controlled
+comparison. It demonstrates both sides: contract-equivalent boundary tests catch
+the same bad return value when invoked, while removing instrumentation leaves all
+behavioral tests green but makes Melampus report incomplete evidence and deny the
+next agent action.
+
+## What a green session cannot establish
+
+- Intent prose is descriptive; predicates define the checked claims. A constant
+ zero can pass a "nonnegative price" check. Add meaningful approved claims for
+ actual pricing correctness; generating more weak checks does not help.
+- Required targets must be listed. Unlisted functions, unexercised branches,
+ incorrect architecture, readability, dependency bloat, and security issues
+ outside the declared checks can remain undetected.
+- Checks currently inspect return values only, not call arguments or arbitrary
+ side effects. They are ordinary Python code and may themselves be wrong.
+- Scenarios run with the user's permissions and inherited environment. Use
+ local deterministic fixtures and no production credentials or destructive
+ side effects. Timeouts terminate the scenario's process group; deliberately
+ detached children and externally started programs are outside supervision.
+- Only watched/protected file content changes invalidate cached results.
+ External service state, environment changes, and nondeterminism need a new
+ session or stronger scenario design. Hashes do not prove complete coverage.
+
+For adoption, start with a few critical generated functions, review their
+contracts, seed known bad implementations to prove detection, and measure actual
+repair iterations and missed defects. No reduction in review time or defect rate
+is claimed without pilot evidence.
diff --git a/docs/RELEASE.md b/docs/RELEASE.md
new file mode 100644
index 0000000..f4fb0c9
--- /dev/null
+++ b/docs/RELEASE.md
@@ -0,0 +1,109 @@
+# First release: 0.1.0 alpha
+
+## 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
+Claude Code hooks that restrict progression until the implementation is repaired.
+See [ADR-0008](adr/0008-local-agent-session-first.md) and the
+[setup guide](AGENT-SESSION.md). Service monitoring is later expansion.
+
+The implementation also covers the frozen schema, synchronous/async decorator,
+privacy rules, sampled checks, per-process execution limits, OTLP/HTTP watcher,
+finite CI sessions, and direct/stock-collector demos. It does not implement raw-content capture,
+LLM judges, distributed budgets, gRPC/JSON OTLP reception, or a production backend.
+
+Verification commands:
+
+```sh
+make ci
+make demo
+make demo-otlp
+make benchmark
+# With a stock collector running:
+uv run --locked python scripts/demo_session.py \
+ --collector http://127.0.0.1:4319/v1/traces --watch-port 4318
+```
+
+The initial 60-test suite also passed against the declared OTel 1.25.0 minimum using
+the built wheel in an isolated Python 3.11 environment.
+
+The earlier SDK/watcher baseline had 61 tests and 93.6% coverage. The agent-session
+revision adds real-process integration checks for drift/repair, hook decisions,
+missing instrumentation, predicate substitution, omitted targets, suppression,
+rapid edits, stale runs, protected files, timeouts, process death and session
+ownership. Coverage includes disposable subprocesses. Current validation results
+are recorded in the PR; the earlier baseline's green CI is not evidence for a
+new revision. `make ci` also exercises the local session from an externally
+installed wheel.
+
+Local integration passed both healthy (zero findings, exit 0) and drift (one finding,
+exit 1) with the real OTel Python HTTP exporter, directly and through the official
+Collector Contrib 0.161.0 native binary. The binary SHA-256 was verified against
+its upstream release checksum. Docker was not running locally; the GitHub CI collector job passed the Compose demo.
+All eight checks passed on the earlier implementation commit, including Linux Python
+3.11–3.14, macOS Python 3.11/3.14, the version guard, and the collector integration.
+
+**Performance limitation:** an initial macOS ARM64 / Python 3.11 recording-span
+benchmark measured 4.74 μs for a bare OTel span and 8.02 μs for an instrumented
+call with no checks (~3.28 μs / 69% extra). This is a local microbenchmark, not a
+production SLA. The founding spec's <3% target remains **unmet**. The benchmark
+reports it explicitly; CI does not hide the failure behind a noisy timing gate.
+The alpha accepts this documented declaration cost under
+[ADR-0007](adr/0007-alpha-performance-baseline.md), which revises the SDK-overhead
+comparison to equivalent manual OTel work while retaining the total-cost metric.
+The equivalent-work experiment measured 8.09 μs manually versus 8.05 μs with
+Melampus (indistinguishable within noise). No claim of satisfying the original
+bare-span target should appear in release announcements.
+
+The first release review must confirm the name `melampus` and its PyPI ownership.
+Both `melampus` and `melampus-python` returned 404 from PyPI during preparation;
+that does not reserve either name. The import name and documented distribution
+are `melampus`.
+
+## Version and GitHub release
+
+`VERSION` is the single package version source, consumed by Hatchling. Prepare a
+reviewed change with its matching CHANGELOG entry. Main merges affecting VERSION
+or CHANGELOG invoke release.yml, which runs `make ci` **before** creating an
+annotated tag and GitHub alpha release containing wheel and sdist artifacts.
+Do not create tags manually. A manual rerun repairs a missing release only if the
+existing tag identifies the current build. Already published releases are left alone.
+
+PyPI publication is a separate manual workflow because bot-created GitHub release
+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:
+
+| Field | Value |
+| --- | --- |
+| Project name | `melampus` |
+| Owner | `melampus-org` |
+| Repository | `melampus-python` |
+| Workflow filename | `publish.yml` |
+| Environment | `testpypi` on TestPyPI; `pypi` on 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/)
+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.
+
+## 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.
+
+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/SPEC.md b/docs/SPEC.md
index dac041c..f743117 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -1,6 +1,17 @@
# melampus-python — Founding Spec
-Status: Draft v0.1 · License: Apache-2.0 · Python 3.11+ · OTel SDK ≥ 1.25
+Status: Implementation baseline for 0.1.0 alpha · License: Apache-2.0 · Python 3.11+ · OTel API ≥ 1.25
+
+The first-release product is the **local agent generation → evidence → repair loop**
+defined in [ADR-0008](adr/0008-local-agent-session-first.md). Start with
+[the agent-session guide](AGENT-SESSION.md). Its dedicated process watches edits,
+executes SDK-instrumented code, and gates agent progression on fresh evidence.
+Production/service monitoring is later expansion.
+
+[ADR-0006](adr/0006-first-release-contract.md) defines the underlying SDK/wire
+contract. The original hackathon proposal below is retained as historical context;
+its deferral of live generation hooks is superseded by ADR-0008. Its broader
+pilot targets are not claims about current coverage or detection capability.
## Problem
@@ -49,17 +60,17 @@ network calls of its own, and is accepted by an unmodified OTLP collector.
**US-2 — Privacy by default (P1).**
*Given* the default hash-only mode, *when* a span is exported, *then* no intent
or assumption text appears on the wire — only content hashes and metadata.
-*Given* content capture is explicitly opted in, *when* a span is exported,
-*then* intent text is emitted as a span event (never as a span attribute).
+In 0.1.0, requesting content capture fails at decoration time. Opted-in content
+events remain post-MVP.
**US-3 — Checks are sampled; declarations are not (P1).**
*Given* a check configured with sample rate `r`, *when* the function is called
-N times (N large), *then* the check body executes on ≈ r·N calls, while 100% of
-spans carry the declaration attributes and the per-span record of whether the
-check ran.
+N times (N large), *then* the check body executes on ≈ r·N calls, while every recording
+span is given declaration attributes and per-check results. OTel sampling,
+attribute limits, and export failures still bound what the watcher receives.
**US-4 — Budget exhaustion degrades gracefully (P1).**
-*Given* the per-service check budget is exhausted, *when* an instrumented
+*Given* the per-process check execution budget is exhausted, *when* an instrumented
function is called, *then* check bodies are skipped, the span still carries all
declaration attributes, and it is marked check-suppressed with reason `budget`.
@@ -67,16 +78,17 @@ declaration attributes, and it is marked check-suppressed with reason `budget`.
*Given* a service emitting instrumented spans through a standard collector and
the watcher consuming OTLP, *when* a seeded drift occurs (runtime value
violates a declared check), *then* the watcher reports a finding within 60
-seconds naming the function, the declared contract, the observed value, the
-violated rule, and a span reference.
+seconds naming the function, the declared contract, the observed predicate result, the
+violated rule ID, and a span reference.
**US-6 — Zero-infrastructure drift report (P2).**
*Given* a repo with instrumented code and the provided docker-compose (stock
OTel Collector), *when* `melampus watch` runs during a test or canary session,
-*then* a human-readable drift report prints to the terminal, with exit code
-non-zero iff findings exist — usable as a CI gate.
+*then* a human-readable drift report prints to the terminal. A finite session
+exits 0 for evaluated healthy checks, 1 for drift, and 2 for incomplete/error
+evidence. Producers flush and collectors drain before the session deadline.
-## MVP cut line — the 5-minute hackathon demo
+## Historical MVP cut line — superseded for the 0.1.0 product by ADR-0008
The demo shows exactly this, in order:
@@ -85,8 +97,8 @@ The demo shows exactly this, in order:
instrumented" without a live-generation risk.
2. A small pre-written Python service whose handlers are decorated with
`@instrumented`, declaring intent (hash-only) and two deterministic checks.
-3. `docker compose up`: a stock `otel-collector` (contrib image, unmodified
- config) receiving OTLP.
+3. `docker compose up`: a stock `otel-collector` (contrib image, stock components
+ with the supplied fan-out configuration) receiving OTLP.
4. Healthy traffic → spans with `code_artifact.*` attributes shown landing.
5. **Seed the drift:** flip an input flag so runtime behavior violates a
declared check.
@@ -102,7 +114,7 @@ demo assets (service + docker-compose + drift seeder).
**Out of MVP (post-hackathon):** live generation-side skill/hook; LLM judge
enrichment (openai-compatible, optional, degrades gracefully); dashboard; VS
Code extension; full token-bucket budget accounting; metrics/logs signals
-beyond spans; content-capture mode beyond the flag existing.
+beyond spans; content-capture mode (the reserved flag rejects enablement).
## Non-goals
@@ -121,8 +133,11 @@ protocol, no custom backend, no phone-home.
- **Watcher precision on seeded drift:** in the demo, 100% of seeded drifts
detected with zero findings on healthy traffic; pilot target precision
≥ 0.95 on a seeded-drift corpus.
-- **Overhead:** an instrumented call with checks off adds < 3% latency versus
- a plain OTel span (microbenchmark kept in CI).
+- **Alpha SDK overhead:** with checks off, target < 3% versus a manual OTel span
+ carrying the same declarations and privacy settings. Report total cost versus
+ a bare span separately; the original < 3% bare-span ambition remains unmet.
+ See [ADR-0007](adr/0007-alpha-performance-baseline.md) for the explicit revision
+ and evidence; the microbenchmark is kept in CI.
## Verification
diff --git a/docs/adr/0002-span-attributes-vs-events-split.md b/docs/adr/0002-span-attributes-vs-events-split.md
index df84a2f..6e69c61 100644
--- a/docs/adr/0002-span-attributes-vs-events-split.md
+++ b/docs/adr/0002-span-attributes-vs-events-split.md
@@ -30,7 +30,7 @@ emitted at all. No prose ever appears in a span attribute.
## Consequences
- The queryable core stays cheap and safe: backends can index and alert on
- every attribute without cardinality or PII risk, and the hash still allows
+ every attribute with bounded values (hashes and identifiers still carry cardinality and disclosure risk), and the hash still allows
exact-match joins back to source artifacts.
- Standard collector processors (`filter`, `transform`) can drop or redact the
content events without touching the attributes — privacy controls compose
diff --git a/docs/adr/0003-decorator-sdk-over-codegen.md b/docs/adr/0003-decorator-sdk-over-codegen.md
index daed09a..505fb6b 100644
--- a/docs/adr/0003-decorator-sdk-over-codegen.md
+++ b/docs/adr/0003-decorator-sdk-over-codegen.md
@@ -37,7 +37,8 @@ reviews like any other line.
wrapper stale) cannot occur.
- Cost: per-call runtime overhead lands on us to control. The no-op/checks-off
fast path must stay under the spec's <3% overhead budget, enforced by a
- CI microbenchmark.
+ CI microbenchmark. [ADR-0007](0007-alpha-performance-baseline.md) clarifies
+ the alpha comparison baseline and reports the total cost separately.
- Granularity is function-shaped. Module- or block-level declarations are
awkward as decorators; we accept this for MVP and will revisit only with
concrete demand.
diff --git a/docs/adr/0004-watcher-as-otlp-consumer.md b/docs/adr/0004-watcher-as-otlp-consumer.md
index 95ae756..0f26fa6 100644
--- a/docs/adr/0004-watcher-as-otlp-consumer.md
+++ b/docs/adr/0004-watcher-as-otlp-consumer.md
@@ -33,9 +33,9 @@ processors, no required collector at all.
is config, not a rebuild, and works identically with vendor collector
distributions users cannot recompile.
- The watcher stays out of the telemetry hot path. A slow rule — or, later, a
- slow LLM enrichment call — delays a finding, never a span reaching the
- user's real backend. This isolation is what makes the LLM path safely
- optional and air-gap-degradable.
+ slow LLM enrichment call — can delay a finding. Independent exporter queues reduce interference with
+ the real backend, but finite queues and collector backpressure mean absolute
+ isolation is not guaranteed. The demo uses short batches and bounded retries.
- We stay in Python: one language across SDK and watcher, and the rules engine
can share the semconv-generated constants from ADR-0001.
- Cost: one more deployable and one more OTLP hop; the watcher sees only what
diff --git a/docs/adr/0005-check-sampling-and-budget-model.md b/docs/adr/0005-check-sampling-and-budget-model.md
index 343f0b3..fbbf7bf 100644
--- a/docs/adr/0005-check-sampling-and-budget-model.md
+++ b/docs/adr/0005-check-sampling-and-budget-model.md
@@ -22,7 +22,7 @@ Cost control has two layers plus an override:
1. **Per-check sample rate** (`sample=0.01` on the check declaration): a
deterministic head decision at the call site — cheap, local, no
coordination. MVP ships this.
-2. **Per-service check budget**: a process-wide token bucket (checks/second,
+2. **Per-process check execution budget**: a process-wide fixed-window execution limit (checks/second,
configured via env/config per service). A check only runs if it passes its
sample rate *and* acquires budget. MVP ships a minimal fixed-rate version;
full token-bucket accounting is post-MVP.
@@ -35,12 +35,11 @@ suppression itself is observable.
## Consequences
-- Worst-case check cost per service is bounded and configurable — the
+- Check execution count per process is bounded and configurable — the
platform persona gets a single number to reason about, independent of how
many decorated functions ship in a release.
- The watcher's declaration-based rules keep working at any sampling level;
- what sampling changes is *detection latency* (fewer executed checks →
- longer time-to-first-violating-sample), which is a visible, tunable
+ sampling can miss a rare failure entirely; when failures recur it also changes detection latency, which is a visible, tunable
trade-off rather than a silent gap.
- Suppression markers make the dial auditable: "how often are checks actually
running in prod" is a standard attribute query, and a service quietly
diff --git a/docs/adr/0006-first-release-contract.md b/docs/adr/0006-first-release-contract.md
new file mode 100644
index 0000000..e210262
--- /dev/null
+++ b/docs/adr/0006-first-release-contract.md
@@ -0,0 +1,73 @@
+# ADR-0006: First release execution and evidence contract
+
+Status: Accepted for implementation — 2026-09-27
+
+The SDK/wire contract remains current. [ADR-0008](0008-local-agent-session-first.md)
+adds the primary local agent-session workflow and the optional `session` extra;
+its disposable runner owns tracer setup on behalf of local scenarios.
+
+## Decision
+
+The first release is **0.1.0 (alpha)**, distribution/import name `melampus`.
+Python 3.11+; core depends on the OTel API, never configures a provider or exporter.
+The application owns SDK configuration and flushing. `watch` and `demo` are extras.
+
+This ADR resolves ambiguities in ADRs 0001–0005 and the founding spec:
+
+- Freeze the wire contract and fixtures in a separate commit before implementing
+ either producer or consumer. For this bootstrap, implementation may follow in
+ the same review branch; the contract and its tests must land before any release.
+ Subsequent wire changes require a schema version change and compatibility review.
+- v0 uses fixed names, bounded parallel arrays (maximum 16 checks), with one
+ result per check. IDs identify rules; SHA-256 identifies their declarations.
+ These are private experimental conventions, not official OTel conventions.
+- Checks are synchronous predicates over the successful return value, including
+ awaited return values. Return exactly `bool`. Exceptions and non-bool results
+ mean `error`; they do not replace the application's return value. Checks must
+ be pure, fast, non-blocking, and must not mutate the result. Python cannot
+ sandbox or forcibly time-limit arbitrary user predicates.
+- Application exceptions/cancellation propagate unchanged. Checks then have
+ `not_executed` results. Exception messages, stack traces, arguments, returned
+ values and predicate errors are never captured by Melampus. The span has ERROR
+ status without a description. Other installed instrumentation is outside this guarantee.
+- Report `observed=false expected=true` for failed predicates, plus check ID,
+ contract hash, function, trace ID, and span ID. Raw application values and
+ human-readable contract prose are intentionally absent. Source code resolves hashes.
+- `capture_content=True` raises `NotImplementedError` at decoration time; it must
+ never silently enable an unimplemented privacy-sensitive capability.
+- SHA-256 uses exact UTF-8 bytes without normalization; assumptions use compact
+ UTF-8 JSON of the ordered list. Hashes are identifiers, not anonymization.
+ Symbol names and check IDs are visible metadata; never embed secrets in them.
+- Check sampling is deterministic from trace ID, span ID and check ID. Each check
+ consumes one execution permit after passing sampling. Budget is a thread-safe
+ **per-process fixed one-second window**, configured through a shared Policy.
+ It limits execution count, not CPU time or aggregate service cost. Operators
+ explicitly replace Policy configuration to disable paths without code changes.
+- A non-recording OTel span skips checks. Declarations are offered to every
+ recording span, subject to application sampling/export and attribute limits.
+ Suppressed or missing checks are never interpreted as passes.
+- The watcher accepts binary protobuf OTLP/HTTP POST `/v1/traces`, including gzip;
+ other encodings/transports are explicitly unsupported in v0. It defaults to
+ loopback and caps request size, socket wait and session deduplication memory.
+- Findings deduplicate on (trace ID, span ID, check ID) within one session.
+ This is bounded in-memory observation, not a durable exactly-once guarantee.
+- `watch --duration N` is finite; `/healthz` signals readiness. The producer must
+ flush and the collector must drain **before** the duration expires. SIGINT
+ closes a continuous session. Exit 0 means at least one evaluated check and no
+ findings/incompleteness; 1 means drift findings; 2 means invalid telemetry,
+ errors, unknown schemas, check errors, no evaluated checks or capacity exhaustion.
+ Exit 2 takes precedence over 1. Suppression counts always appear in the summary.
+
+## Evidence and consequences
+
+The separation between library API and application SDK follows
+[OTel Python instrumentation](https://opentelemetry.io/docs/languages/python/instrumentation/).
+Transport, success responses and retry expectations follow the
+[OTLP specification](https://opentelemetry.io/docs/specs/otlp/).
+The private namespace follows [OTel naming guidance](https://opentelemetry.io/docs/specs/semconv/general/naming/).
+Publishing follows [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/using-a-publisher/).
+
+The deterministic watcher reports the SDK's predicate evidence; it does not infer
+arbitrary intent or reevaluate source code. Sampling can miss rare failures entirely.
+The watcher is for local/CI use or a trusted network behind a secured collector;
+it is not an authenticated, durable production tracing backend.
diff --git a/docs/adr/0007-alpha-performance-baseline.md b/docs/adr/0007-alpha-performance-baseline.md
new file mode 100644
index 0000000..8fdbc22
--- /dev/null
+++ b/docs/adr/0007-alpha-performance-baseline.md
@@ -0,0 +1,48 @@
+# ADR-0007: Separate SDK overhead from declaration telemetry cost
+
+Status: Accepted for 0.1.0 alpha — 2026-09-28
+
+## Evidence
+
+The original spec asks for <3% extra latency versus a plain OTel span, without
+specifying whether the reference span carries the same declaration attributes.
+The first bare-span benchmark on macOS ARM64 / Python 3.11 measured ~4.74 μs
+versus ~8.02 μs (+69%). The Linux GitHub runner measured ~13.46 μs versus
+~25.19 μs (+87%). The original bare-span target is **not met**.
+
+An equivalent-work experiment uses identical span names, privacy settings and
+all nine declaration attributes, with no exporter on any timed path. Fifteen
+rotating rounds of 20,000 calls measured medians of 4.82 μs (bare), 8.09 μs
+(manual OTel with declarations), and 8.05 μs (Melampus). The difference between
+manual equivalent work and Melampus is within measurement noise, not evidence
+of a speedup. Most measured added time is the cost of carrying declarations. A subsequent
+run of the checked-in benchmark measured 4.80 / 7.98 / 8.06 μs respectively
+(~1.0% wrapper overhead, ~68% total overhead), consistent with this conclusion.
+
+## Decision
+
+For the experimental 0.1.0 release, distinguish two metrics:
+
+1. **SDK wrapper overhead:** target <3% against a manual OTel span carrying the
+ exact same declarations and privacy settings. This compares equivalent work.
+2. **Total adoption overhead:** always report absolute microseconds and relative
+ overhead against a bare span. Keep the original <3% ambition visible as unmet;
+ do not advertise the alpha as adding <3% total tracing latency.
+
+This explicitly revises the first-release performance criterion; it does not
+reclassify the original measurement as a pass. The alpha accepts the documented
+cost of carrying declarations. Production adopters must benchmark their actual
+workload, sampling policy, Python/OTel versions and exporter configuration.
+
+`make benchmark` emits platform/version, raw rounds, medians, both overheads and
+both target results. Shared-runner timing is reported, not used as a flaky CI gate.
+Negative deltas are noise, not guaranteed performance improvements. Functional
+checks, schema compatibility, privacy and package validity remain hard release gates.
+
+## Consequences
+
+The SDK does not bypass OTel attribute validation, drop declarations or install a
+custom tracer to force a favorable measurement. Future optimization work can target
+telemetry construction with the full adoption cost still visible. This decision
+supersedes the bare-span interpretation of SPEC's first-release overhead goal and
+the corresponding release blocker recorded during initial preparation.
diff --git a/docs/adr/0008-local-agent-session-first.md b/docs/adr/0008-local-agent-session-first.md
new file mode 100644
index 0000000..80c89a1
--- /dev/null
+++ b/docs/adr/0008-local-agent-session-first.md
@@ -0,0 +1,65 @@
+# ADR-0008: Make the generation-time repair loop the first-release product
+
+Status: Accepted for implementation — 2026-09-29
+
+## Problem
+
+The initial alpha implemented the telemetry foundation and positioned adoption
+around CI/canaries. The product's primary problem is earlier: an agent can keep
+generating behavior that diverges from intent faster than a human can review it.
+A watcher alone reports drift but does not feed it into the active coding loop.
+
+## Decision
+
+0.1.0 includes a dedicated local supervisor, SDK Contract objects, a scenario
+runner, an agent-neutral gate, and a Claude Code hook adapter. This supersedes
+the founding spec's decision to defer live generation hooks. Existing wire
+attributes and the optional OTLP watcher remain compatible foundations.
+
+- Reviewed intent/predicates live outside the implementation being generated.
+ `Contract.instrument()` uses the existing SDK. The disposable runner verifies
+ exact check object identity and declarations for every required function.
+- `melampus session` pins reviewed file hashes and observes scoped file contents.
+ Each changed revision runs the reviewed scenario in a new interpreter with
+ an always-on tracer. SDK evidence stays local; no collector/network export is
+ needed. The runner is an application and owns its tracer; the core library
+ remains OTel API-only as specified by ADR-0006.
+- Every required function/check must execute. No evidence, suppressed checks,
+ changed contracts, stale revisions, runner errors and timeouts are incomplete.
+ Maximum 256 required checks and 10,000 observed spans per run; at most 32 drift
+ examples are returned, with aggregate counts retained. Scenario timeout is
+ at most ten seconds; normal completion/timeout cleans up its process group.
+- Gates query a token-authenticated loopback supervisor. Saved state locates
+ the process; saved status is never authority. One owner holds the state lock.
+- Claude Code synchronous hooks check before/after tools and on Stop. Failed
+ state restricts progression to inspection and scoped repair edits. Hooks feed
+ evidence to the existing agent; Melampus neither launches nor pays for an LLM.
+- macOS/Linux are the initial session platforms. Other agents integrate through
+ the 0/1/2 gate contract. Native adapters beyond Claude Code are not claimed.
+
+## Consequences and limitations
+
+The operator still reviews executable claims and representative inputs. This is
+an execution feedback system, not general semantic inference or a security
+boundary. It does not interrupt unfinished model output, undo completed tools,
+cancel arbitrary parallel agent work, or detect undeclared/unexercised slop.
+Runtime/production monitoring is expansion, not the first-release adoption story.
+
+As with tests, weak or wrong predicates remain weak or wrong. Contracts avoid
+duplicating the same assertions across generated test files, but cannot eliminate
+the oracle problem. A green session certifies only its exercised claims.
+
+Hook behavior follows the [Claude Code reference](https://code.claude.com/docs/en/hooks).
+The included command hooks use their own timeout shorter than the host timeout;
+host-level hook cancellation can render no decision. Enabled hooks, a live
+supervisor, reviewed scope, and cooperative agents are operating prerequisites.
+
+## Required verification
+
+Real subprocess tests must demonstrate healthy → edited drift → deny progression
+and completion → allow repair → freshly healthy. They must also cover missing
+instrumentation, omitted targets, predicate substitution, skipped execution,
+same-size rapid edits, protected-file changes, stale runs, hangs, process death,
+and local session ownership. Existing SDK/wire tests and distribution checks
+continue to pass. Package artifacts must include the runner, supervisor, hooks,
+and executable onboarding example.
diff --git a/docs/demo-walkthrough.template.html b/docs/demo-walkthrough.template.html
new file mode 100644
index 0000000..d1b2a94
--- /dev/null
+++ b/docs/demo-walkthrough.template.html
@@ -0,0 +1,116 @@
+
+
+
+
+Melampus — a recorded Claude coding session
+
+
+
+
+
+melampus.
+
+
+
Claude stopped. The contract held.
+
A pricing refactor breaks two approved rules. Melampus blocks the next action, Claude repairs the code, and fresh evidence lets the session continue.
The owner reviews intent.py and the five scenario inputs. The agent edits pricing.py. A dedicated Melampus process watches that code and executes the scenario again when it changes.
+
IntegerOutput uses whole cents
≥ 0No negative price
≤ 10,000Approved ceiling, in cents
+
+
+Runs during generation, before unit tests or CI need to be invoked. No backend or telemetry collector is required for this local loop.
+
+
Input · cents
Original
Seeded defect
Claude’s repair
{{ROWS}}
+
Outputs come from a post-run replay of saved source snapshots on these public fixtures. The SDK evidence records check results, not raw argument or result values.
+
+
+
02 / RECORDING
Watch the next action change.
+
{{TIMELINE}}
+
THE FAILURE REACHED THE AGENT
“The hook blocked it as expected; not retrying.”
Claude’s recorded response after its harmless printf request was denied. The request was deliberately prompted to make the gate observable.
+
+
+
03 / REPAIR
One implementation edit. The same reviewed checks.
+
Actual pricing.py before and after Claude’s Edit. The instrumentation remains in place so the fresh implementation is checked again.
+
Loading source comparison. If offline, download drift.py and after.py from Evidence below.
+
Green means the checked claims passed.Claude also introduced int(cents). These five integer inputs do not establish whether truncating floats or rejecting other types is acceptable. A passing report still needs a good contract and a review of semantic choices.
+Inspect the approved contract · intent.py
Source available in Evidence below.
+Inspect the executed scenario · exercise.py
Source available in Evidence below.
+
+
+
04 / FAIL CLOSED
Missing evidence also stops progression.
+
After the live repair, the harness ran two additional controls. These were scripted checks, not actions taken by Claude.
+
INCOMPLETE · EXIT 2
Remove the decorator
The function can still return bounded prices, but its required checks no longer produce evidence. Melampus reports the missing checks.
INCOMPLETE · EXIT 2
Stop the supervisor
The gate reports that the local supervisor is unavailable. A previous healthy result does not authorize a new success claim.
+
+
+
05 / UNIT TESTS
The oracle is familiar. The control point is different.
+
The runnable example makes two temporary edits and executes real pytest and Melampus processes. It distinguishes a test-coverage gap from the session behavior Melampus adds.
+
Temporary edit
Smoke unit
Full boundary tests
Melampus
Next agent action
Return input unchanged
Pass
Fail
Drift
Blocked
Remove instrumentation
Pass
Pass
Incomplete
Blocked
+
SAME FOUNDATION
Good tests catch the same bad value
When the complete boundary suite runs, it catches the unclamped return. Melampus has no secret source of intent; both approaches depend on reviewed executable claims and representative inputs.
ADDED SESSION PROTOCOL
Evidence must stay attached and current
The supervisor reruns after watched edits, treats missing instrumentation as incomplete, and gives the synchronous agent hook a decision for the current revision.
+
Could hooks around pytest achieve similar control?Yes. A controller that runs the right tests after every relevant edit, detects missing or stale execution, preserves repair access, and blocks the agent on failure can provide similar protection. Melampus packages that loop around contracts attached to generated units; it complements the broader regression suite.
+
+
+
06 / TRY IT
Run the same example yourself.
+
Python 3.11+ and uv on macOS or Linux. The recorder creates a disposable copy; it does not change the repository’s example.
+
+
Get the demo implementation
This recording uses the first-release branch in PR #6. Publication on PyPI is not required.
Ask Claude to modify pricing:price while preserving PRICE.instrument and the reviewed intent. If intent needs to change, have the owner review it and restart the session. See the agent-session guide for configuration and adapters.
+
+
+
+
07 / VALUE
Keep human review focused on intent.
+
The loop handles repeated feedback
Re-executes the configured scenario when watched code changes.
Returns specific failed claims to the coding agent.
Blocks unrelated progression while allowing scoped repair.
Keeps reviewed assertions separate from implementation edits.
The team still owns the specification
Choose valuable predicates and representative scenarios.
Check coverage of the paths that matter.
Review meaningful behavior changes, including repair choices.
Keep unit tests, CI, security checks and code review.
+
Tests with the same inputs and assertions can catch this same bug. Melampus adds the continuously running session loop, evidence freshness and agent action gating. It does not infer all business intent from prose or guarantee that generated code is correct.
+
+
+
08 / EVIDENCE
Inspect the run. Reproduce the result.
+
These downloads are embedded in this HTML. Sharing this file shares the recording, not the author’s AI session. Readers run their own copy with their own Claude account.
+
{{DOWNLOADS}}
+
Recorded {{DATE}} with Melampus 0.1.0 and {{CLAUDE_VERSION}}. Temporary paths were replaced with <demo-project>. Published messages omit authentication metadata and hidden reasoning. Fonts and the syntax viewer use public CDNs; narrative, tables and evidence downloads remain available offline.
+
+
+
+
+
+
+
diff --git a/docs/demos/pricing-session/README.md b/docs/demos/pricing-session/README.md
new file mode 100644
index 0000000..7cb32c2
--- /dev/null
+++ b/docs/demos/pricing-session/README.md
@@ -0,0 +1,92 @@
+# Recorded local Claude repair
+
+[Download the visual walkthrough](walkthrough.html) and open it in a browser.
+The HTML contains its own evidence downloads; it does not connect to the author's AI session.
+[Preview the recorded timeline](recording.png).
+
+This run used Melampus 0.1.0, Claude Code 2.1.284, and the first-release implementation
+at commit `58abe4981196d91398f9ef2e8d6a1fc85a969e57`, on 2026-09-29.
+The recorder was added alongside this evidence.
+
+## What actually happened
+
+The harness copied `examples/agent-session` into a disposable project and deliberately
+replaced the price clamp with `return cents`. The supervisor detected the defect
+before the harness queried the gate. This is a seeded bug, not a claim that Claude
+independently introduced it.
+
+A real Claude Code model session then attempted a harmless shell command. Melampus's
+PreToolUse hook denied it and returned the two failed claims. Claude read the source
+and contract, performed one Edit, and completed after fresh evidence passed all
+15 evaluations (five inputs × three rules). Five reviewed files retained their hashes.
+
+The model added `int(cents)` when restoring the bounds. The integer scenarios do not
+prove that coercion is appropriate for other types. The agent itself noted this
+limitation. The report demonstrates the feedback loop, not universal correctness,
+typical latency, or measured human-review savings.
+
+After the live repair, scripted controls verified that removing instrumentation and
+stopping the supervisor both produce incomplete evidence (exit 2).
+
+## Compare with unit tests
+
+The repository now includes a controlled side-by-side comparison:
+
+```sh
+uv run --locked python examples/agent-session/compare_with_unit_tests.py
+```
+
+It shows that contract-equivalent boundary tests catch the same bad return value
+when invoked. It also shows the session-specific difference: after the correct
+function loses its instrumentation, all behavioral unit tests pass while Melampus
+reports incomplete evidence and denies the next agent action. The script restores
+the source after both edits. See the walkthrough for the full comparison and caveats.
+
+## Reproduce
+
+From the repository root, with Python 3.11+ and uv on macOS/Linux:
+
+```sh
+uv sync --locked --all-extras
+
+# No model request; scripted restoration exercises the actual protocol.
+uv run --locked python scripts/record_agent_demo.py --output demo-recordings/protocol
+
+# Real model request using your installed, signed-in Claude Code account.
+uv run --locked python scripts/record_agent_demo.py --live-claude --output demo-recordings/live
+
+# Build a report from a successful live recording.
+uv run --locked python scripts/build_demo_walkthrough.py demo-recordings/live --output demo-recordings/walkthrough.html
+```
+
+Use a new recording directory each time. Live runs require the CLI options supported
+by Claude Code 2.1.284 and can vary in model behavior. The recorder asserts the expected
+outcomes and fails rather than presenting an unsuccessful run as verified.
+The original live recording preceded the addition of the fixture replay helper;
+the helper was then run against these exact saved source files.
+
+For a normal two-terminal coding session, follow
+[the example setup](../../../examples/agent-session/README.md) and
+[agent integration guide](../../AGENT-SESSION.md).
+
+## Evidence
+
+- `run.json`: configuration provenance, phase reports, expected-outcome assertions,
+ agent conclusion, and hashes of reviewed files.
+- `hooks.jsonl`: actual hook event/tool names, timestamps and decisions.
+- `agent-transcript.jsonl`: visible messages and tool requests/results. Authentication,
+ session initialization, hidden reasoning and account/usage records are omitted.
+- `supervisor.log`: actual state transitions from the local supervisor.
+- `before.py`, `drift.py`, `after.py`: original, deliberately broken, and actual repaired source.
+- `intent.py`, `exercise.py`: the approved rules and public scenario.
+- `fixture-results.json`: post-run replay of the five public input values against the
+ saved source snapshots. Raw fixture values are printed by the demo harness, not
+ captured by SDK telemetry.
+- `recording.png`: screenshot of the walkthrough timeline, derived from these logs.
+
+Temporary project paths were replaced with ``.
+This fixture is intentionally public. Inspect recordings before sharing if you adapt
+the harness to private code or business inputs.
+
+The walkthrough narrative and downloads work offline. Fonts and the optional
+@pierre/diffs syntax viewer load from public CDNs.
diff --git a/docs/demos/pricing-session/after.py b/docs/demos/pricing-session/after.py
new file mode 100644
index 0000000..a85a31e
--- /dev/null
+++ b/docs/demos/pricing-session/after.py
@@ -0,0 +1,6 @@
+from intent import PRICE
+
+
+@PRICE.instrument(generator="example")
+def price(cents: int) -> int:
+ return max(0, min(int(cents), 10000))
diff --git a/docs/demos/pricing-session/agent-transcript.jsonl b/docs/demos/pricing-session/agent-transcript.jsonl
new file mode 100644
index 0000000..e4670df
--- /dev/null
+++ b/docs/demos/pricing-session/agent-transcript.jsonl
@@ -0,0 +1,13 @@
+{"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01JfydHwmxKyL8TRuFJfV3fh", "name": "Bash", "input": {"command": "printf 'starting review\\n'", "description": "Print starting review message"}, "caller": {"type": "direct"}}]}
+{"role": "user", "content": [{"type": "tool_result", "content": "PreToolUse:Bash hook error: Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner.", "is_error": true, "tool_use_id": "toolu_01JfydHwmxKyL8TRuFJfV3fh"}]}
+{"role": "assistant", "content": [{"type": "text", "text": "The hook blocked it as expected; not retrying."}]}
+{"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_011EGqQMG1bep4JzXJ6JD2hi", "name": "Read", "input": {"file_path": "/pricing.py"}, "caller": {"type": "direct"}}]}
+{"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01SRqHwgoerCs5KeQ2bg6Xdu", "name": "Read", "input": {"file_path": "/intent.py"}, "caller": {"type": "direct"}}]}
+{"role": "user", "content": [{"tool_use_id": "toolu_011EGqQMG1bep4JzXJ6JD2hi", "type": "tool_result", "content": "1\tfrom intent import PRICE\n2\t\n3\t\n4\t@PRICE.instrument(generator=\"example\")\n5\tdef price(cents: int) -> int:\n6\t return cents\n7\t"}]}
+{"role": "user", "content": [{"tool_use_id": "toolu_01SRqHwgoerCs5KeQ2bg6Xdu", "type": "tool_result", "content": "1\t\"\"\"Review these claims once before the agent starts implementing them.\"\"\"\n2\t\n3\tfrom melampus import Check, Contract\n4\t\n5\tPRICE = Contract(\n6\t intent=\"Return a nonnegative integer price in cents, capped at 10000 cents.\",\n7\t checks=(\n8\t Check(\"integer_cents\", lambda value: type(value) is int, \"Price uses integer cents.\"),\n9\t Check(\"nonnegative\", lambda value: value >= 0, \"Price is never negative.\"),\n10\t Check(\"capped\", lambda value: value <= 10000, \"Price never exceeds 10000 cents.\"),\n11\t ),\n12\t)\n13\t\n14\tCONTRACTS = {\"pricing:price\": PRICE}\n15\t"}]}
+{"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_014NKhRCh7quPg5xkGGrWxWb", "name": "Edit", "input": {"replace_all": false, "file_path": "/pricing.py", "old_string": " return cents", "new_string": " return max(0, min(int(cents), 10000))"}, "caller": {"type": "direct"}}]}
+{"role": "user", "content": [{"tool_use_id": "toolu_014NKhRCh7quPg5xkGGrWxWb", "type": "tool_result", "content": "The file /pricing.py has been updated successfully. (file state is current in your context \u2014 no need to Read it back)"}]}
+{"role": "assistant", "content": [{"type": "text", "text": "The warning shown before the edit was the old drift state. I'll read the file again to get a fresh hook report."}]}
+{"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01YGUsRmSGMayVoKxkvMJmhT", "name": "Read", "input": {"file_path": "/pricing.py"}, "caller": {"type": "direct"}}]}
+{"role": "user", "content": [{"tool_use_id": "toolu_01YGUsRmSGMayVoKxkvMJmhT", "type": "tool_result", "content": "1\tfrom intent import PRICE\n2\t\n3\t\n4\t@PRICE.instrument(generator=\"example\")\n5\tdef price(cents: int) -> int:\n6\t return max(0, min(int(cents), 10000))\n7\t"}]}
+{"role": "assistant", "content": [{"type": "text", "text": "I repaired `pricing.py`. After the edit, Melampus stopped reporting any failed checks.\n\n**Defect:** `price` returned its input unchanged. With the clamps removed, a negative input came back negative and a large input came back above the cap. That broke two checks in the reviewed contract, `nonnegative` and `capped`.\n\n**Fix:** I changed the function body to `return max(0, min(int(cents), 10000))`, so the result is always an integer between 0 and 10000 cents. The `@PRICE.instrument(generator=\"example\")` decorator is still there. I didn't touch any other file: not the contract, hooks, scenarios or supervisor.\n\n**Order of events:** Melampus blocked the opening `printf 'starting review\\n'` command because the code had drifted from the contract (2 of 15 checks failing). As instructed, I didn't retry it or work around it. Once I made the edit, the hooks gave no more blocking reports.\n\n**Limits of what was checked:**\n- The checks only confirm three things for the inputs the recorded scenarios actually ran: the result is an integer, it isn't negative, and it's at most 10000.\n- That doesn't prove the function is correct for every input. For example, `int(cents)` would silently cut off a float or raise an error on something that isn't a number, and the scenarios may not test that.\n- The contract doesn't say whether clamping is the right business behaviour for out-of-range prices, as opposed to rejecting them. That's a decision for whoever owns the contract."}]}
diff --git a/docs/demos/pricing-session/before.py b/docs/demos/pricing-session/before.py
new file mode 100644
index 0000000..ddd1812
--- /dev/null
+++ b/docs/demos/pricing-session/before.py
@@ -0,0 +1,6 @@
+from intent import PRICE
+
+
+@PRICE.instrument(generator="example")
+def price(cents: int) -> int:
+ return min(10000, max(0, cents))
diff --git a/docs/demos/pricing-session/drift.py b/docs/demos/pricing-session/drift.py
new file mode 100644
index 0000000..fb288b6
--- /dev/null
+++ b/docs/demos/pricing-session/drift.py
@@ -0,0 +1,6 @@
+from intent import PRICE
+
+
+@PRICE.instrument(generator="example")
+def price(cents: int) -> int:
+ return cents
diff --git a/docs/demos/pricing-session/exercise.py b/docs/demos/pricing-session/exercise.py
new file mode 100644
index 0000000..3fe94eb
--- /dev/null
+++ b/docs/demos/pricing-session/exercise.py
@@ -0,0 +1,6 @@
+"""Exercise the actual entry point; the SDK carries the assertions."""
+
+from pricing import price
+
+for cents in (-1, 0, 1200, 10000, 12000):
+ price(cents)
diff --git a/docs/demos/pricing-session/fixture-results.json b/docs/demos/pricing-session/fixture-results.json
new file mode 100644
index 0000000..b6d92a7
--- /dev/null
+++ b/docs/demos/pricing-session/fixture-results.json
@@ -0,0 +1,33 @@
+{
+ "source": "post-run replay of saved source snapshots on public fixture inputs",
+ "inputs_cents": [
+ -1,
+ 0,
+ 1200,
+ 10000,
+ 12000
+ ],
+ "outputs": {
+ "before.py": [
+ 0,
+ 0,
+ 1200,
+ 10000,
+ 10000
+ ],
+ "drift.py": [
+ -1,
+ 0,
+ 1200,
+ 10000,
+ 12000
+ ],
+ "after.py": [
+ 0,
+ 0,
+ 1200,
+ 10000,
+ 10000
+ ]
+ }
+}
diff --git a/docs/demos/pricing-session/hooks.jsonl b/docs/demos/pricing-session/hooks.jsonl
new file mode 100644
index 0000000..e4ebd9b
--- /dev/null
+++ b/docs/demos/pricing-session/hooks.jsonl
@@ -0,0 +1,10 @@
+{"time": 1790644926.043212, "event": "PreToolUse", "tool": "Bash", "exit_code": 0, "decision": {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner."}}, "stderr": ""}
+{"time": 1790644929.762377, "event": "PreToolUse", "tool": "Read", "exit_code": 0, "decision": {}, "stderr": ""}
+{"time": 1790644929.841214, "event": "PreToolUse", "tool": "Read", "exit_code": 0, "decision": {}, "stderr": ""}
+{"time": 1790644929.855362, "event": "PostToolUse", "tool": "Read", "exit_code": 0, "decision": {"decision": "block", "reason": "Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner."}, "stderr": ""}
+{"time": 1790644929.925497, "event": "PostToolUse", "tool": "Read", "exit_code": 0, "decision": {"decision": "block", "reason": "Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner."}, "stderr": ""}
+{"time": 1790644933.420563, "event": "PreToolUse", "tool": "Edit", "exit_code": 0, "decision": {"hookSpecificOutput": {"additionalContext": "Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner.", "hookEventName": "PreToolUse"}}, "stderr": ""}
+{"time": 1790644933.9085498, "event": "PostToolUse", "tool": "Edit", "exit_code": 0, "decision": {}, "stderr": ""}
+{"time": 1790644939.150099, "event": "PreToolUse", "tool": "Read", "exit_code": 0, "decision": {}, "stderr": ""}
+{"time": 1790644939.229707, "event": "PostToolUse", "tool": "Read", "exit_code": 0, "decision": {}, "stderr": ""}
+{"time": 1790644946.4418812, "event": "Stop", "tool": null, "exit_code": 0, "decision": {}, "stderr": ""}
diff --git a/docs/demos/pricing-session/intent.py b/docs/demos/pricing-session/intent.py
new file mode 100644
index 0000000..2c405a5
--- /dev/null
+++ b/docs/demos/pricing-session/intent.py
@@ -0,0 +1,14 @@
+"""Review these claims once before the agent starts implementing them."""
+
+from melampus import Check, Contract
+
+PRICE = Contract(
+ intent="Return a nonnegative integer price in cents, capped at 10000 cents.",
+ checks=(
+ Check("integer_cents", lambda value: type(value) is int, "Price uses integer cents."),
+ Check("nonnegative", lambda value: value >= 0, "Price is never negative."),
+ Check("capped", lambda value: value <= 10000, "Price never exceeds 10000 cents."),
+ ),
+)
+
+CONTRACTS = {"pricing:price": PRICE}
diff --git a/docs/demos/pricing-session/recording.png b/docs/demos/pricing-session/recording.png
new file mode 100644
index 0000000..758193d
Binary files /dev/null and b/docs/demos/pricing-session/recording.png differ
diff --git a/docs/demos/pricing-session/run.json b/docs/demos/pricing-session/run.json
new file mode 100644
index 0000000..a9139d8
--- /dev/null
+++ b/docs/demos/pricing-session/run.json
@@ -0,0 +1,157 @@
+{
+ "recorded_at": "2026-09-29T01:21:56.904240+00:00",
+ "melampus_version": "0.1.0",
+ "mode": "live-claude",
+ "defect_origin": "deliberately seeded by recording harness",
+ "repair_origin": "Claude Code model via Edit",
+ "inputs_cents": [
+ -1,
+ 0,
+ 1200,
+ 10000,
+ 12000
+ ],
+ "prompt": "This is a controlled Melampus product demonstration in a disposable project.\nThe harness deliberately removed the clamps in pricing.py. Do not edit intent.py,\nexercise.py, melampus.toml, settings, or the recording hook. First attempt the Bash\ncommand `printf 'starting review\\n'` so the demo records the real progression\ngate. If a Melampus hook blocks it, do not retry or bypass it. Read pricing.py and\nintent.py, then use Edit to repair pricing.py according to the existing reviewed\nSDK contract. Preserve the Contract.instrument decorator. Make no other changes.\nDo not add tests, run a shell workaround, use subagents, or restart the supervisor.\nOnce the hooks accept the repair, finish with a concise explanation of the defect,\nthe fix, and the limit of the checked claims. Do not claim universal correctness.\n",
+ "claude_version": "2.1.284 (Claude Code)",
+ "reviewed_hashes": {
+ "intent.py": "def8d4c257d504e95d066d73539cc725275cf7b45b658ce4a57bf909939a429e",
+ "exercise.py": "b194b8f086827efe23b3ff0db747bf36c7151866d0dda5e905d0756b56292248",
+ "melampus.toml": "476acae72ad63c200163fdc2b4778091169909e93b6443439fc0b0def2c601a2",
+ "CLAUDE.md": "18daa48c12aa42348065cd9088c28b7493751fe37a797770c2a73f5fb0f7dba0",
+ ".claude/settings.json": "18c6570cbd9f815b7fd185342baff745540404e3c052979b63ac2d59159cc035"
+ },
+ "claude_exit_code": 0,
+ "agent_result": {
+ "subtype": "success",
+ "is_error": false,
+ "result": "I repaired `pricing.py`. After the edit, Melampus stopped reporting any failed checks.\n\n**Defect:** `price` returned its input unchanged. With the clamps removed, a negative input came back negative and a large input came back above the cap. That broke two checks in the reviewed contract, `nonnegative` and `capped`.\n\n**Fix:** I changed the function body to `return max(0, min(int(cents), 10000))`, so the result is always an integer between 0 and 10000 cents. The `@PRICE.instrument(generator=\"example\")` decorator is still there. I didn't touch any other file: not the contract, hooks, scenarios or supervisor.\n\n**Order of events:** Melampus blocked the opening `printf 'starting review\\n'` command because the code had drifted from the contract (2 of 15 checks failing). As instructed, I didn't retry it or work around it. Once I made the edit, the hooks gave no more blocking reports.\n\n**Limits of what was checked:**\n- The checks only confirm three things for the inputs the recorded scenarios actually ran: the result is an integer, it isn't negative, and it's at most 10000.\n- That doesn't prove the function is correct for every input. For example, `int(cents)` would silently cut off a float or raise an error on something that isn't a number, and the scenarios may not test that.\n- The contract doesn't say whether clamping is the right business behaviour for out-of-range prices, as opposed to rejecting them. That's a decision for whoever owns the contract.",
+ "num_turns": 6
+ },
+ "live_hooks_verified": true,
+ "verified": true,
+ "events": [
+ {
+ "phase": "healthy_baseline",
+ "elapsed_seconds": 1.593,
+ "report": {
+ "exit_code": 0,
+ "findings": [],
+ "missing": [],
+ "undeclared": [],
+ "contract_mismatch": [],
+ "probe_error": false,
+ "checks": {
+ "passed": 15
+ },
+ "revision": "afb0de142a68beb4d33e61adba3060d60b34a536576bb0de0db4f90397ee3f03",
+ "generation": 1,
+ "state": "healthy"
+ }
+ },
+ {
+ "phase": "drift_detected",
+ "elapsed_seconds": 2.443,
+ "detection_seconds": 0.845,
+ "report": {
+ "exit_code": 1,
+ "findings": [
+ {
+ "function": "pricing:price",
+ "check_id": "nonnegative",
+ "contract_hash": "658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7",
+ "trace_id": "53c77b8ba3218de15348c226a4932d62",
+ "span_id": "f8055e5962a36413",
+ "observed": false,
+ "expected": true
+ },
+ {
+ "function": "pricing:price",
+ "check_id": "capped",
+ "contract_hash": "2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1",
+ "trace_id": "094e22912dc829285a34846b6466386b",
+ "span_id": "0cdd4dc29eb6d686",
+ "observed": false,
+ "expected": true
+ }
+ ],
+ "missing": [],
+ "undeclared": [],
+ "contract_mismatch": [],
+ "probe_error": false,
+ "checks": {
+ "passed": 13,
+ "failed": 2
+ },
+ "revision": "b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e",
+ "generation": 2,
+ "state": "drift"
+ },
+ "decision": {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Melampus: {\"checks\": {\"failed\": 2, \"passed\": 13}, \"contract_mismatch\": [], \"exit_code\": 1, \"findings\": [{\"check_id\": \"nonnegative\", \"contract_hash\": \"658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"f8055e5962a36413\", \"trace_id\": \"53c77b8ba3218de15348c226a4932d62\"}, {\"check_id\": \"capped\", \"contract_hash\": \"2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1\", \"expected\": true, \"function\": \"pricing:price\", \"observed\": false, \"span_id\": \"0cdd4dc29eb6d686\", \"trace_id\": \"094e22912dc829285a34846b6466386b\"}], \"generation\": 2, \"missing\": [], \"probe_error\": false, \"revision\": \"b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e\", \"state\": \"drift\", \"undeclared\": []}\nRepair the implementation using Edit/Write, then wait for fresh healthy evidence. Do not weaken contracts or continue unrelated work. If intent must change, ask the owner."
+ }
+ }
+ },
+ {
+ "phase": "live_agent_started",
+ "elapsed_seconds": 2.444
+ },
+ {
+ "phase": "repair_verified",
+ "elapsed_seconds": 30.431,
+ "reviewed_files_unchanged": true,
+ "report": {
+ "exit_code": 0,
+ "findings": [],
+ "missing": [],
+ "undeclared": [],
+ "contract_mismatch": [],
+ "probe_error": false,
+ "checks": {
+ "passed": 15
+ },
+ "revision": "42c170a3153ac9ada22c5aa6fcc130c3e384076b417d75c2a2a7f4b93fa29cf6",
+ "generation": 3,
+ "state": "healthy"
+ },
+ "decision": {}
+ },
+ {
+ "phase": "missing_instrumentation_blocked",
+ "elapsed_seconds": 30.793,
+ "report": {
+ "exit_code": 2,
+ "findings": [],
+ "missing": [
+ "pricing:price/capped",
+ "pricing:price/integer_cents",
+ "pricing:price/nonnegative"
+ ],
+ "undeclared": [
+ "pricing:price"
+ ],
+ "contract_mismatch": [],
+ "probe_error": false,
+ "checks": {},
+ "revision": "bd3892da73db34625113c25d07600b2d970af115e4164bb6e6e80e72a8f8987b",
+ "generation": 4,
+ "state": "incomplete"
+ }
+ },
+ {
+ "phase": "offline_blocks_success",
+ "elapsed_seconds": 31.126,
+ "report": {
+ "exit_code": 2,
+ "state": "incomplete",
+ "message": "Local supervisor unavailable. Start melampus session in its dedicated terminal; do not claim success."
+ }
+ },
+ {
+ "phase": "recording_complete",
+ "elapsed_seconds": 31.126
+ }
+ ]
+}
diff --git a/docs/demos/pricing-session/supervisor.log b/docs/demos/pricing-session/supervisor.log
new file mode 100644
index 0000000..1ff2744
--- /dev/null
+++ b/docs/demos/pricing-session/supervisor.log
@@ -0,0 +1,6 @@
+READY melampus session; state=/.melampus/session.json
+SESSION {"checks": {"passed": 15}, "contract_mismatch": [], "exit_code": 0, "findings": [], "generation": 1, "missing": [], "probe_error": false, "revision": "afb0de142a68beb4d33e61adba3060d60b34a536576bb0de0db4f90397ee3f03", "state": "healthy", "undeclared": []}
+SESSION {"checks": {"failed": 2, "passed": 13}, "contract_mismatch": [], "exit_code": 1, "findings": [{"check_id": "nonnegative", "contract_hash": "658a34fe4d16b32caca134be0e6bdbede4be833aacbc895dfc503172e45112a7", "expected": true, "function": "pricing:price", "observed": false, "span_id": "f8055e5962a36413", "trace_id": "53c77b8ba3218de15348c226a4932d62"}, {"check_id": "capped", "contract_hash": "2251215739c1b6484f2a05fe50cf70cac1391077f99d3f975a3a528e68116cf1", "expected": true, "function": "pricing:price", "observed": false, "span_id": "0cdd4dc29eb6d686", "trace_id": "094e22912dc829285a34846b6466386b"}], "generation": 2, "missing": [], "probe_error": false, "revision": "b6ea86669eff5d53d6c3d005c0bfb44005370ca0c9acc4e609e0e6ac3f7eb52e", "state": "drift", "undeclared": []}
+SESSION {"checks": {"passed": 15}, "contract_mismatch": [], "exit_code": 0, "findings": [], "generation": 3, "missing": [], "probe_error": false, "revision": "42c170a3153ac9ada22c5aa6fcc130c3e384076b417d75c2a2a7f4b93fa29cf6", "state": "healthy", "undeclared": []}
+SESSION {"checks": {}, "contract_mismatch": [], "exit_code": 2, "findings": [], "generation": 4, "missing": ["pricing:price/capped", "pricing:price/integer_cents", "pricing:price/nonnegative"], "probe_error": false, "revision": "bd3892da73db34625113c25d07600b2d970af115e4164bb6e6e80e72a8f8987b", "state": "incomplete", "undeclared": ["pricing:price"]}
+SESSION {"checks": {"passed": 15}, "contract_mismatch": [], "exit_code": 0, "findings": [], "generation": 5, "missing": [], "probe_error": false, "revision": "42c170a3153ac9ada22c5aa6fcc130c3e384076b417d75c2a2a7f4b93fa29cf6", "state": "healthy", "undeclared": []}
diff --git a/docs/demos/pricing-session/walkthrough.html b/docs/demos/pricing-session/walkthrough.html
new file mode 100644
index 0000000..ba56309
--- /dev/null
+++ b/docs/demos/pricing-session/walkthrough.html
@@ -0,0 +1,116 @@
+
+
+
+
+Melampus — a recorded Claude coding session
+
+
+
+
+
+melampus.
+
+
+
Claude stopped. The contract held.
+
A pricing refactor breaks two approved rules. Melampus blocks the next action, Claude repairs the code, and fresh evidence lets the session continue.
The owner reviews intent.py and the five scenario inputs. The agent edits pricing.py. A dedicated Melampus process watches that code and executes the scenario again when it changes.
+
IntegerOutput uses whole cents
≥ 0No negative price
≤ 10,000Approved ceiling, in cents
+
+
+Runs during generation, before unit tests or CI need to be invoked. No backend or telemetry collector is required for this local loop.
+
+
Input · cents
Original
Seeded defect
Claude’s repair
-1
0
-1 · fails
0
0
0
0
0
1,200
1,200
1,200
1,200
10,000
10,000
10,000
10,000
12,000
10,000
12,000 · fails
10,000
+
Outputs come from a post-run replay of saved source snapshots on these public fixtures. The SDK evidence records check results, not raw argument or result values.
+
+
+
02 / RECORDING
Watch the next action change.
+
T+1.6s
healthy
Baseline accepted
Five inputs exercise three approved rules: 15 evaluations pass.
T+2.4s
drift
The harness removes both clamps
The supervisor detects two failed evaluations before any gate query.
T+9.1s
blocked
Claude’s shell action is denied
The real hook sends nonnegative and capped failures back to Claude.
T+17.0s
healthy
Claude repairs pricing.py
One Edit restores the bounds. Fresh execution passes all 15 evaluations.
T+29.5s
healthy
Completion is accepted
The Stop hook accepts the result. Five reviewed files remain unchanged.
+
THE FAILURE REACHED THE AGENT
“The hook blocked it as expected; not retrying.”
Claude’s recorded response after its harmless printf request was denied. The request was deliberately prompted to make the gate observable.
+
+
+
03 / REPAIR
One implementation edit. The same reviewed checks.
+
Actual pricing.py before and after Claude’s Edit. The instrumentation remains in place so the fresh implementation is checked again.
+
Loading source comparison. If offline, download drift.py and after.py from Evidence below.
+
Green means the checked claims passed.Claude also introduced int(cents). These five integer inputs do not establish whether truncating floats or rejecting other types is acceptable. A passing report still needs a good contract and a review of semantic choices.
+Inspect the approved contract · intent.py
Source available in Evidence below.
+Inspect the executed scenario · exercise.py
Source available in Evidence below.
+
+
+
04 / FAIL CLOSED
Missing evidence also stops progression.
+
After the live repair, the harness ran two additional controls. These were scripted checks, not actions taken by Claude.
+
INCOMPLETE · EXIT 2
Remove the decorator
The function can still return bounded prices, but its required checks no longer produce evidence. Melampus reports the missing checks.
INCOMPLETE · EXIT 2
Stop the supervisor
The gate reports that the local supervisor is unavailable. A previous healthy result does not authorize a new success claim.
+
+
+
05 / UNIT TESTS
The oracle is familiar. The control point is different.
+
The runnable example makes two temporary edits and executes real pytest and Melampus processes. It distinguishes a test-coverage gap from the session behavior Melampus adds.
+
Temporary edit
Smoke unit
Full boundary tests
Melampus
Next agent action
Return input unchanged
Pass
Fail
Drift
Blocked
Remove instrumentation
Pass
Pass
Incomplete
Blocked
+
SAME FOUNDATION
Good tests catch the same bad value
When the complete boundary suite runs, it catches the unclamped return. Melampus has no secret source of intent; both approaches depend on reviewed executable claims and representative inputs.
ADDED SESSION PROTOCOL
Evidence must stay attached and current
The supervisor reruns after watched edits, treats missing instrumentation as incomplete, and gives the synchronous agent hook a decision for the current revision.
+
Could hooks around pytest achieve similar control?Yes. A controller that runs the right tests after every relevant edit, detects missing or stale execution, preserves repair access, and blocks the agent on failure can provide similar protection. Melampus packages that loop around contracts attached to generated units; it complements the broader regression suite.
+
+
+
06 / TRY IT
Run the same example yourself.
+
Python 3.11+ and uv on macOS or Linux. The recorder creates a disposable copy; it does not change the repository’s example.
+
+
Get the demo implementation
This recording uses the first-release branch in PR #6. Publication on PyPI is not required.
Ask Claude to modify pricing:price while preserving PRICE.instrument and the reviewed intent. If intent needs to change, have the owner review it and restart the session. See the agent-session guide for configuration and adapters.
+
+
+
+
07 / VALUE
Keep human review focused on intent.
+
The loop handles repeated feedback
Re-executes the configured scenario when watched code changes.
Returns specific failed claims to the coding agent.
Blocks unrelated progression while allowing scoped repair.
Keeps reviewed assertions separate from implementation edits.
The team still owns the specification
Choose valuable predicates and representative scenarios.
Check coverage of the paths that matter.
Review meaningful behavior changes, including repair choices.
Keep unit tests, CI, security checks and code review.
+
Tests with the same inputs and assertions can catch this same bug. Melampus adds the continuously running session loop, evidence freshness and agent action gating. It does not infer all business intent from prose or guarantee that generated code is correct.
+
+
+
08 / EVIDENCE
Inspect the run. Reproduce the result.
+
These downloads are embedded in this HTML. Sharing this file shares the recording, not the author’s AI session. Readers run their own copy with their own Claude account.
Recorded 2026-09-29 with Melampus 0.1.0 and 2.1.284 (Claude Code). Temporary paths were replaced with <demo-project>. Published messages omit authentication metadata and hidden reasoning. Fonts and the syntax viewer use public CDNs; narrative, tables and evidence downloads remain available offline.
+
+
+
+
+
+
+
diff --git a/examples/agent-session/.claude/settings.json b/examples/agent-session/.claude/settings.json
new file mode 100644
index 0000000..d086bd0
--- /dev/null
+++ b/examples/agent-session/.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/agent-session/CLAUDE.md b/examples/agent-session/CLAUDE.md
new file mode 100644
index 0000000..6cae010
--- /dev/null
+++ b/examples/agent-session/CLAUDE.md
@@ -0,0 +1,22 @@
+# Melampus coding session
+
+Implement the approved intent in `intent.py`. Use its Contract.instrument()
+decorator on every named function. Do not copy or weaken checks. Keep imports
+and inputs compatible with `exercise.py`.
+
+A separate `melampus session` process reexecutes the scenario after source edits.
+Hooks request fresh evidence before/after tools and before you finish. A drift
+or incomplete result means stop feature work and repair the implementation now.
+Read the function/check identifiers in the hook evidence. Use Read/Grep/Glob to
+inspect and Edit/Write on the watched implementation to repair it. Shell and
+other progression tools are blocked until the evidence is healthy again.
+
+Do not remove instrumentation, modify intent/scenarios/settings, restart the
+supervisor to accept changed contracts, or treat missing evidence as success.
+If the approved intent is wrong or a repair is impossible, ask the owner. After
+three unsuccessful repair attempts, explain the evidence and ask for help.
+
+Healthy only means the reviewed predicates passed for the exercised inputs.
+For example, a constant zero implementation satisfies this example's bounds;
+pricing accuracy would need a stronger approved contract. Never claim that a
+green session proves complete correctness or absence of all AI-generated slop.
diff --git a/examples/agent-session/README.md b/examples/agent-session/README.md
new file mode 100644
index 0000000..d3fcc0c
--- /dev/null
+++ b/examples/agent-session/README.md
@@ -0,0 +1,132 @@
+# Try the generation → drift → repair loop
+
+This is a local runnable project for Python 3.11+ on macOS/Linux. It uses SDK
+contracts and five inputs without a collector or cloud account. It also includes
+a pytest comparison that separates behavioral coverage from Melampus's local
+agent-session controls. Claude Code is optional for observing drift and required
+for the bundled agent hook integration.
+
+## 1. Install from the release candidate
+
+From the repository root:
+
+```sh
+uv sync --locked --all-extras
+source .venv/bin/activate
+```
+
+Or use `python -m pip install '.[session]' pytest` inside your own virtual environment.
+The alpha is not yet published to PyPI; don't assume an unrelated registry
+package is this release. After publication the install becomes
+`python -m pip install 'melampus[session]==0.1.0'`.
+
+Copy this example into an isolated working directory if you want to experiment
+without changing the release checkout. Keep the installed environment active.
+
+## 2. Review the four inputs
+
+- `intent.py`: approved intent and three predicates; `CONTRACTS` requires `pricing:price`.
+- `exercise.py`: negative, zero, normal, boundary, and excessive prices.
+- `melampus.toml`: source scope, protected settings/instructions, five-second deadline.
+- `CLAUDE.md` and `.claude/settings.json`: agent instructions and synchronous hooks.
+- `unit_tests/`: a typical smoke test plus contract-equivalent boundary tests.
+
+The predicates check integer/nonnegative/capped outputs. They do not prove a
+complete pricing algorithm. The contract belongs to the owner; the agent repairs
+`pricing.py` to satisfy it.
+
+## 3. Start the dedicated process
+
+```sh
+cd examples/agent-session # or your copied example directory
+melampus session
+```
+
+Wait for `READY` and a `healthy` report with 15 passed evaluations (five calls ×
+three checks). Leave this terminal running. In a second terminal, activate the
+same environment and enter the same directory:
+
+```sh
+melampus gate
+claude
+```
+
+Review/enable the supplied project hooks in Claude Code. `/hooks` lets you inspect
+them. If you already have settings, merge these four hook entries rather than
+overwriting your configuration. `melampus` must resolve in the hook's PATH; an
+absolute executable path is also supported. Don't turn on async execution.
+
+## 4. See drift before doing more work
+
+For a controlled demo, use your editor to change the implementation to:
+
+```python
+@PRICE.instrument(generator="example")
+def price(cents: int) -> int:
+ return cents
+```
+
+The dedicated terminal reports `drift`, identifying `nonnegative` and `capped`.
+No CI push is needed. Ask Claude:
+
+> Inspect the Melampus evidence and repair pricing.py using the existing SDK
+> contract. Keep intent.py and the scenario unchanged. Resume only after the
+> supervisor reports healthy.
+
+The hooks block shell/progression and completion, while allowing inspection and
+Edit/Write on `pricing.py`. Restoring `min(10000, max(0, cents))` produces fresh
+healthy evidence and reopens the gate. Removing the decorator produces incomplete
+evidence, even if the return value happens to be valid.
+
+To observe hook decisions without sending a model request:
+
+```sh
+printf '%s\n' '{"hook_event_name":"Stop"}' | melampus gate --claude
+```
+
+Healthy outputs `{}`; drift/incomplete outputs `decision: block` and repair
+evidence. `--claude` uses the hook's JSON protocol and normally exits 0; the
+agent-neutral `melampus gate` uses process exit codes 0/1/2.
+
+## 5. Compare it with unit tests
+
+Run the automated comparison from the example directory with no other supervisor
+running:
+
+```sh
+python compare_with_unit_tests.py
+```
+
+It makes two temporary edits, runs real pytest processes, queries a real Melampus
+session, prints this table, and restores `pricing.py` even if interrupted:
+
+| Temporary edit | Smoke unit test | Full boundary tests | Melampus | Next agent action |
+| --- | --- | --- | --- | --- |
+| `return cents` | Pass | Fail | Drift | Blocked |
+| Remove `@PRICE.instrument(...)` while keeping correct behavior | Pass | Pass | Incomplete | Blocked |
+
+The first row is a coverage lesson, not a Melampus advantage. A complete unit
+test suite catches the same behavioral defect when it runs. The narrow smoke test
+passes because `1200` does not exercise either boundary.
+
+The second row shows the added invariant: the reviewed contract must still be
+attached to and observed from the generated function. Ordinary behavioral tests
+do not care where their evidence came from. You could add a structural unit test
+for the decorator, but then you are rebuilding part of Melampus's required-
+evidence protocol.
+
+The remaining difference is timing and control. Pytest helps when a person, CI,
+or another hook invokes it and honors its exit status. The Melampus supervisor
+runs after watched changes, rejects stale or missing evidence, and its Claude Code
+hook blocks unrelated progression until the current source revision is healthy.
+Keep the unit tests: they remain the broader, mature regression suite.
+
+## 6. Generate a new implementation
+
+After the owner has reviewed the contract, ask the agent to rewrite `pricing.py`
+using `PRICE.instrument()` and preserve `pricing:price`. The supervisor accepts
+any implementation that satisfies the approved executable claims on the supplied
+inputs. Add new targets/contracts only through owner review and a session restart.
+
+Ctrl-C stops the supervisor. Subsequent gates report incomplete instead of using
+old evidence. See [the complete behavior and limits](../../docs/AGENT-SESSION.md).
diff --git a/examples/agent-session/compare_with_unit_tests.py b/examples/agent-session/compare_with_unit_tests.py
new file mode 100644
index 0000000..06b15d0
--- /dev/null
+++ b/examples/agent-session/compare_with_unit_tests.py
@@ -0,0 +1,141 @@
+"""Run an honest unit-test versus Melampus comparison against real edits."""
+
+from __future__ import annotations
+
+import signal
+import subprocess
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+from melampus.session import gate
+
+ROOT = Path(__file__).resolve().parent
+PRICING = ROOT / "pricing.py"
+STATE = ROOT / ".melampus" / "comparison.json"
+LOG = ROOT / ".melampus" / "comparison.log"
+
+
+def run_pytest(*paths: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, "-m", "pytest", "-q", *paths],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ timeout=20,
+ )
+
+
+def wait_for_state(expected: str, timeout: float = 8) -> dict[str, Any]:
+ deadline = time.monotonic() + timeout
+ last: dict[str, Any] = {}
+ while time.monotonic() < deadline:
+ report, _ = gate(STATE, {})
+ last = report
+ if report.get("state") == expected:
+ return report
+ time.sleep(0.05)
+ raise RuntimeError(f"expected Melampus state {expected!r}, last report was {last!r}")
+
+
+def hook_blocks() -> bool:
+ event = {
+ "hook_event_name": "PreToolUse",
+ "cwd": str(ROOT),
+ "tool_name": "Bash",
+ "tool_input": {"command": "continue with unrelated work"},
+ }
+ _, decision = gate(STATE, event)
+ return bool(decision.get("hookSpecificOutput", {}).get("permissionDecision") == "deny")
+
+
+def status(result: subprocess.CompletedProcess[str]) -> str:
+ return "PASS" if result.returncode == 0 else "FAIL"
+
+
+def main() -> int:
+ original = PRICING.read_text()
+ STATE.parent.mkdir(exist_ok=True)
+ with LOG.open("w") as log:
+ process = subprocess.Popen(
+ [
+ sys.executable,
+ "-m",
+ "melampus",
+ "session",
+ "--config",
+ str(ROOT / "melampus.toml"),
+ "--state",
+ str(STATE),
+ "--interval",
+ "0.05",
+ ],
+ cwd=ROOT,
+ stdout=log,
+ stderr=log,
+ text=True,
+ )
+ try:
+ wait_for_state("healthy")
+
+ PRICING.write_text(original.replace("return min(10000, max(0, cents))", "return cents"))
+ smoke_drift = run_pytest("unit_tests/test_pricing_smoke.py")
+ full_drift = run_pytest("unit_tests")
+ drift = wait_for_state("drift")
+ drift_blocked = hook_blocks()
+
+ PRICING.write_text(original)
+ wait_for_state("healthy")
+ PRICING.write_text(original.replace('@PRICE.instrument(generator="example")\n', ""))
+ smoke_unobserved = run_pytest("unit_tests/test_pricing_smoke.py")
+ full_unobserved = run_pytest("unit_tests")
+ incomplete = wait_for_state("incomplete")
+ incomplete_blocked = hook_blocks()
+
+ rows = [
+ (
+ "return cents",
+ status(smoke_drift),
+ status(full_drift),
+ drift["state"].upper(),
+ "BLOCKED" if drift_blocked else "ALLOWED",
+ ),
+ (
+ "remove decorator",
+ status(smoke_unobserved),
+ status(full_unobserved),
+ incomplete["state"].upper(),
+ "BLOCKED" if incomplete_blocked else "ALLOWED",
+ ),
+ ]
+ print("\nEDIT SMOKE UNIT FULL UNIT MELAMPUS NEXT AGENT ACTION")
+ print("------------------- ---------- --------- ---------- -----------------")
+ for row in rows:
+ print(f"{row[0]:19} {row[1]:10} {row[2]:9} {row[3]:10} {row[4]}")
+
+ expected = [
+ ("return cents", "PASS", "FAIL", "DRIFT", "BLOCKED"),
+ ("remove decorator", "PASS", "PASS", "INCOMPLETE", "BLOCKED"),
+ ]
+ if rows != expected:
+ print("\nUnexpected comparison result. See:", LOG, file=sys.stderr)
+ return 1
+ print(
+ "\nFull boundary tests catch the behavioral defect when they run. "
+ "Melampus adds change-triggered execution, required evidence, and an agent gate."
+ )
+ return 0
+ finally:
+ PRICING.write_text(original)
+ if process.poll() is None:
+ process.send_signal(signal.SIGINT)
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/agent-session/exercise.py b/examples/agent-session/exercise.py
new file mode 100644
index 0000000..3fe94eb
--- /dev/null
+++ b/examples/agent-session/exercise.py
@@ -0,0 +1,6 @@
+"""Exercise the actual entry point; the SDK carries the assertions."""
+
+from pricing import price
+
+for cents in (-1, 0, 1200, 10000, 12000):
+ price(cents)
diff --git a/examples/agent-session/intent.py b/examples/agent-session/intent.py
new file mode 100644
index 0000000..2c405a5
--- /dev/null
+++ b/examples/agent-session/intent.py
@@ -0,0 +1,14 @@
+"""Review these claims once before the agent starts implementing them."""
+
+from melampus import Check, Contract
+
+PRICE = Contract(
+ intent="Return a nonnegative integer price in cents, capped at 10000 cents.",
+ checks=(
+ Check("integer_cents", lambda value: type(value) is int, "Price uses integer cents."),
+ Check("nonnegative", lambda value: value >= 0, "Price is never negative."),
+ Check("capped", lambda value: value <= 10000, "Price never exceeds 10000 cents."),
+ ),
+)
+
+CONTRACTS = {"pricing:price": PRICE}
diff --git a/examples/agent-session/melampus.toml b/examples/agent-session/melampus.toml
new file mode 100644
index 0000000..26b9999
--- /dev/null
+++ b/examples/agent-session/melampus.toml
@@ -0,0 +1,5 @@
+contracts = "intent"
+probe = "exercise.py"
+watch = ["pricing.py"]
+protect = [".claude/settings.json", "CLAUDE.md"]
+timeout = 5
diff --git a/examples/agent-session/pricing.py b/examples/agent-session/pricing.py
new file mode 100644
index 0000000..ddd1812
--- /dev/null
+++ b/examples/agent-session/pricing.py
@@ -0,0 +1,6 @@
+from intent import PRICE
+
+
+@PRICE.instrument(generator="example")
+def price(cents: int) -> int:
+ return min(10000, max(0, cents))
diff --git a/examples/agent-session/unit_tests/test_pricing_boundaries.py b/examples/agent-session/unit_tests/test_pricing_boundaries.py
new file mode 100644
index 0000000..212de3c
--- /dev/null
+++ b/examples/agent-session/unit_tests/test_pricing_boundaries.py
@@ -0,0 +1,20 @@
+"""Behavioral tests equivalent to the reviewed Melampus pricing claims."""
+
+import pytest
+from pricing import price
+
+
+@pytest.mark.parametrize(
+ ("cents", "expected"),
+ [
+ (-1, 0),
+ (0, 0),
+ (1200, 1200),
+ (10000, 10000),
+ (12000, 10000),
+ ],
+)
+def test_price_is_bounded(cents: int, expected: int) -> None:
+ result = price(cents)
+ assert type(result) is int
+ assert result == expected
diff --git a/examples/agent-session/unit_tests/test_pricing_smoke.py b/examples/agent-session/unit_tests/test_pricing_smoke.py
new file mode 100644
index 0000000..689ff25
--- /dev/null
+++ b/examples/agent-session/unit_tests/test_pricing_smoke.py
@@ -0,0 +1,7 @@
+"""A common fast unit test: one representative input and expected output."""
+
+from pricing import price
+
+
+def test_typical_price() -> None:
+ assert price(1200) == 1200
diff --git a/examples/demo/README.md b/examples/demo/README.md
new file mode 100644
index 0000000..e9ce80d
--- /dev/null
+++ b/examples/demo/README.md
@@ -0,0 +1,35 @@
+# Stock collector demo
+
+The direct `make demo` route requires no Docker. This variant proves the same
+contract through an unmodified OpenTelemetry Collector Contrib 0.161.0, using
+stock `otlp`, `batch`, `otlp_http`, and `debug` components.
+
+```sh
+uv sync --locked --all-extras
+docker compose -f examples/demo/compose.yaml up -d
+uv run --locked python scripts/demo_session.py \
+ --collector http://127.0.0.1:4319/v1/traces \
+ --watch-host 0.0.0.0 --watch-port 4318
+docker compose -f examples/demo/compose.yaml down
+```
+
+The watcher binds to all interfaces for container-to-host access; run this on a
+trusted development machine. The collector's published receiver port is bound
+to host loopback. The debug exporter shows declaration attributes; the second
+exporter fans out to the watcher. Use your existing backend exporter in place
+of debug outside the demo.
+
+For a native collector (same config, loopback-only watcher):
+
+```sh
+MELAMPUS_WATCH_ENDPOINT=http://127.0.0.1:4318 \
+ otelcol-contrib --config=examples/demo/collector.yaml
+# In another terminal:
+uv run --locked python scripts/demo_session.py \
+ --collector http://127.0.0.1:4319/v1/traces --watch-port 4318
+```
+
+The healthy session must return 0; the seeded session must return 1 and report
+only the `nonnegative` check. Each runs for 8 seconds to allow the collector's
+200 ms batch to drain. A timeout or export loss produces an incomplete session,
+not a healthy result. The demo driver itself returns 0 only when both assertions pass.
diff --git a/examples/demo/collector.yaml b/examples/demo/collector.yaml
new file mode 100644
index 0000000..f8763e6
--- /dev/null
+++ b/examples/demo/collector.yaml
@@ -0,0 +1,26 @@
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4319
+processors:
+ batch:
+ timeout: 200ms
+exporters:
+ otlp_http/watcher:
+ endpoint: ${env:MELAMPUS_WATCH_ENDPOINT}
+ sending_queue:
+ enabled: false
+ retry_on_failure:
+ enabled: true
+ initial_interval: 100ms
+ max_interval: 500ms
+ max_elapsed_time: 3s
+ debug:
+ verbosity: detailed
+service:
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [batch]
+ exporters: [otlp_http/watcher, debug]
diff --git a/examples/demo/compose.yaml b/examples/demo/compose.yaml
new file mode 100644
index 0000000..29f26a6
--- /dev/null
+++ b/examples/demo/compose.yaml
@@ -0,0 +1,12 @@
+services:
+ collector:
+ image: otel/opentelemetry-collector-contrib:0.161.0
+ command: ["--config=/etc/otelcol-contrib/config.yaml"]
+ environment:
+ MELAMPUS_WATCH_ENDPOINT: http://host.docker.internal:4318
+ extra_hosts:
+ - "host.docker.internal:host-gateway"
+ volumes:
+ - ./collector.yaml:/etc/otelcol-contrib/config.yaml:ro
+ ports:
+ - "127.0.0.1:4319:4319"
diff --git a/examples/demo/service.py b/examples/demo/service.py
new file mode 100644
index 0000000..7f6c638
--- /dev/null
+++ b/examples/demo/service.py
@@ -0,0 +1,49 @@
+"""One healthy call or one seeded drift; flush before exiting."""
+
+import argparse
+import os
+
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.sdk.resources import Resource
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+
+from melampus import Check, instrumented
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--drift", action="store_true")
+ args = parser.parse_args()
+ provider = TracerProvider(resource=Resource.create({"service.name": "melampus-demo"}))
+ provider.add_span_processor(
+ SimpleSpanProcessor(
+ OTLPSpanExporter(
+ endpoint=os.environ.get(
+ "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "http://127.0.0.1:4318/v1/traces"
+ )
+ )
+ )
+ )
+
+ @instrumented(
+ intent="Return a nonnegative price in cents",
+ checks=[
+ Check("integer", lambda result: type(result) is int, "Result is an integer"),
+ Check("nonnegative", lambda result: result >= 0, "Result is nonnegative"),
+ ],
+ tracer=provider.get_tracer("melampus-demo"),
+ )
+ def price(drift=False):
+ return -1 if drift else 1200
+
+ try:
+ print(f"price={price(args.drift)}")
+ if not provider.force_flush(timeout_millis=5000):
+ raise SystemExit("telemetry flush timed out")
+ finally:
+ provider.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..7ab4c4a
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,75 @@
+[build-system]
+requires = ["hatchling>=1.27,<2"]
+build-backend = "hatchling.build"
+
+[project]
+name = "melampus"
+dynamic = ["version"]
+description = "Keep AI coding sessions aligned with reviewed intent and local execution evidence."
+readme = "README.md"
+requires-python = ">=3.11"
+license = "Apache-2.0"
+license-files = ["LICENSE"]
+authors = [{name = "Melampus contributors"}]
+classifiers = [
+ "Development Status :: 3 - Alpha",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+ "Typing :: Typed",
+]
+dependencies = ["opentelemetry-api>=1.25,<2"]
+
+[project.optional-dependencies]
+watch = ["opentelemetry-proto>=1.25,<2"]
+demo = ["opentelemetry-sdk>=1.25,<2", "opentelemetry-exporter-otlp-proto-http>=1.25,<2"]
+session = ["opentelemetry-sdk>=1.25,<2", "opentelemetry-exporter-otlp-proto-common>=1.25,<2", "opentelemetry-proto>=1.25,<2"]
+
+[project.scripts]
+melampus = "melampus.cli:main"
+
+[project.urls]
+Homepage = "https://github.com/melampus-org/melampus-python"
+Documentation = "https://github.com/melampus-org/melampus-python/tree/main/docs"
+Issues = "https://github.com/melampus-org/melampus-python/issues"
+
+[dependency-groups]
+dev = ["hatchling>=1.27,<2", "pytest>=8,<10", "pytest-cov>=7,<8", "coverage>=7.10.6,<8", "ruff>=0.12,<1", "mypy>=1.15,<2", "pyyaml>=6,<7", "types-PyYAML>=6", "twine>=6.1,<8", "build>=1.2,<2", "pre-commit>=4,<5", "jsonschema>=4,<5"]
+
+[tool.hatch.version]
+path = "VERSION"
+pattern = '^(?P\d+\.\d+\.\d+)$'
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/melampus"]
+
+[tool.hatch.build.targets.sdist]
+include = ["src", "tests", "semconv", "scripts", "docs", "examples", "benchmarks", "release", "Makefile", "pyproject.toml", "uv.lock", "VERSION", "README.md", "LICENSE", "CHANGELOG.md", "CONTRIBUTING.md", "SECURITY.md"]
+
+[tool.ruff]
+target-version = "py311"
+line-length = 100
+extend-exclude = ["release/_lib"]
+
+[tool.ruff.lint]
+select = ["E4", "E7", "E9", "F", "I", "UP", "B"]
+
+[tool.mypy]
+python_version = "3.11"
+strict = true
+
+[[tool.mypy.overrides]]
+module = ["opentelemetry.proto.*", "google.protobuf.*"]
+ignore_missing_imports = true
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = "-ra --strict-markers --strict-config --import-mode=importlib"
+
+[tool.uv]
+cache-keys = [{ file = "pyproject.toml" }, { file = "VERSION" }]
+
+[tool.coverage.run]
+patch = ["subprocess"]
diff --git a/scripts/build_demo_walkthrough.py b/scripts/build_demo_walkthrough.py
new file mode 100644
index 0000000..16810e0
--- /dev/null
+++ b/scripts/build_demo_walkthrough.py
@@ -0,0 +1,130 @@
+"""Build a portable visual walkthrough from a verified live Claude recording."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import html
+import json
+from datetime import datetime
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def build(recording: Path, output: Path) -> None:
+ run = json.loads((recording / "run.json").read_text())
+ if not run.get("verified") or not run.get("live_hooks_verified"):
+ raise ValueError("This walkthrough requires a verified live Claude recording.")
+ events = {event["phase"]: event for event in run["events"]}
+ hooks = [json.loads(line) for line in (recording / "hooks.jsonl").read_text().splitlines()]
+ messages = [
+ json.loads(line) for line in (recording / "agent-transcript.jsonl").read_text().splitlines()
+ ]
+ edit_count = sum(
+ block.get("type") == "tool_use" and block.get("name") == "Edit"
+ for message in messages
+ for block in message["content"]
+ )
+ epoch = datetime.fromisoformat(run["recorded_at"]).timestamp()
+
+ def hook_time(event: str, tool: str | None) -> float:
+ return next(h["time"] - epoch for h in hooks if h["event"] == event and h["tool"] == tool)
+
+ stages = [
+ (
+ events["healthy_baseline"]["elapsed_seconds"],
+ "healthy",
+ "Baseline accepted",
+ "Five inputs exercise three approved rules: 15 evaluations pass.",
+ ),
+ (
+ events["drift_detected"]["elapsed_seconds"],
+ "drift",
+ "The harness removes both clamps",
+ "The supervisor detects two failed evaluations before any gate query.",
+ ),
+ (
+ hook_time("PreToolUse", "Bash"),
+ "blocked",
+ "Claude’s shell action is denied",
+ "The real hook sends nonnegative and capped failures back to Claude.",
+ ),
+ (
+ hook_time("PostToolUse", "Edit"),
+ "healthy",
+ "Claude repairs pricing.py",
+ "One Edit restores the bounds. Fresh execution passes all 15 evaluations.",
+ ),
+ (
+ hook_time("Stop", None),
+ "healthy",
+ "Completion is accepted",
+ "The Stop hook accepts the result. Five reviewed files remain unchanged.",
+ ),
+ ]
+ timeline = "".join(
+ f'
T+{t:.1f}s'
+ f'
{state}
{html.escape(title)}
'
+ f"
{html.escape(description)}
"
+ for t, state, title, description in stages
+ )
+ fixtures = json.loads((recording / "fixture-results.json").read_text())
+ rows = ""
+ for index, value in enumerate(fixtures["inputs_cents"]):
+ before, drift, after = (
+ fixtures["outputs"][name][index] for name in ("before.py", "drift.py", "after.py")
+ )
+ marker = ' class="failed"' if drift != after else ""
+ rows += (
+ f"
{value:,}
{before:,}
{drift:,}"
+ f"{' · fails' if drift != after else ''}