Metadata-Version: 2.4
Name: modelpin-relay
Version: 0.1.1
Summary: Sends Modelpin check and watch results from CI to Jira and Bitbucket
License-Expression: Apache-2.0
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: modelpin==0.5.3; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: jsonschema; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: types-PyYAML; extra == "dev"
Dynamic: license-file

# modelpin-relay

Sends the results of [Modelpin](https://pypi.org/project/modelpin/) checks from CI to Jira and Bitbucket. It reads
the files Modelpin writes (run records, reports, the committed baseline, `modelpin watch --json` output) and the
repository's git history, builds one signed JSON event, and:

- in Bitbucket Pipelines, posts a `modelpin-check` Code Insights report on the commit (through the Pipelines
  proxy, so no credentials are needed);
- sends the event to Modelpin for Jira's web trigger, if `MODELPIN_WEBHOOK_URL` and `MODELPIN_WEBHOOK_SECRET` are
  set.

It never imports or changes Modelpin, never calls a model, and never sends prompts, message histories or tool
arguments. Apache-2.0.

## Commands

```text
modelpin-relay pending        Post the PENDING Code Insights report (Bitbucket only)
modelpin-relay skip           --reason TEXT [--config modelpin.yaml]
modelpin-relay publish        --exit-code CODE --since EPOCH --to MODEL [--from MODEL] [--provider NAME]
                              [--config modelpin.yaml] [--store-dir .modelpin] [--scenarios-dir DIR]
                              [--no-insights] [--no-event] [--dry-run] [--out DIR] [--sample]
                              [--outcome-file PATH]
modelpin-relay publish-watch  --input PATH [--no-event] [--dry-run] [--out DIR] [--sample]
modelpin-relay version
common: [--ci auto|bitbucket|github|local] [--url-env NAME] [--secret-env NAME]
```

Pass `--exit-code` the exit code of `modelpin check` in the same step, and `--since` the step's start time
(`date +%s`). The relay uses a run record only if Modelpin wrote it during this step for this candidate with this
exit code; otherwise the outcome is `error`, never `clean`. Only `clean` passes.

Exit codes: 0 done (or nothing to send), 2 usage error, 5 a send failed. The relay never changes the check's own
exit code: end the CI step with that.

## Bitbucket Pipelines

```yaml
image: python:3.12

clone:
  depth: full # history_keys need commit history

pipelines:
  pull-requests:
    "**":
      - step:
          name: Modelpin model check
          caches: [pip]
          script:
            - export MODELPIN_MODEL_FILE="app/model.txt" # the file in your repository that holds the model id
            - pip install "modelpin[providers]==0.5.3" "modelpin-relay==0.1.*"
            - git fetch origin "$BITBUCKET_PR_DESTINATION_BRANCH"
            - if git diff --quiet FETCH_HEAD -- "$MODELPIN_MODEL_FILE" modelpin.yaml scenarios/ .modelpin/; then modelpin-relay skip --reason "No model or scenario change in this pull request"; exit 0; fi
            - export MODELPIN_CANDIDATE="$(tr -d '[:space:]' < "$MODELPIN_MODEL_FILE")"
            - start=$(date +%s); modelpin-relay pending || echo "Modelpin pending report failed"; code=0; modelpin check --to "$MODELPIN_CANDIDATE" || code=$?; modelpin-relay publish --exit-code "$code" --since "$start" --to "$MODELPIN_CANDIDATE" || echo "Modelpin publish failed"; exit $code
```

Store `MODELPIN_WEBHOOK_URL`, `MODELPIN_WEBHOOK_SECRET` and your provider key as secured repository variables.

## The event

The event is versioned (`"schema": "modelpin.atlassian/v1"`), and a field with no value is sent as `null`,
never left out. The body stays under 180,000 bytes: the relay shortens the migration report, then example outputs, then drops unchanged results,
and lists what it cut in `truncated`. Model ids, outputs and file paths come only from files the pull request and
Modelpin wrote; the relay reads only regular files inside the checkout and never follows a link.

## Verifying the signature

Each POST carries `X-Modelpin-Signature: t=<unix seconds>,v1=<hex>`, where `v1` is the hex HMAC-SHA256 of
`<t>.<raw body>`, keyed with the UTF-8 bytes of the secret exactly as shown in Modelpin for Jira's Setup tab.
A receiver checks the header is exactly `t=` ten digits, `,v1=` and 64 lowercase hex characters, rejects a `t`
more than 300 seconds from now, compares the HMAC in constant time, and rejects an `event_id` it has seen in the
last 15 minutes. Retries reuse the `event_id` with a fresh timestamp and signature.

```python
import hashlib, hmac
expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
ok = hmac.compare_digest(expected, v1)
```

## Development

```bash
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/python -m pytest && .venv/bin/ruff check . && .venv/bin/mypy --strict src
.venv/bin/python tests/golden.py      # regenerate tests/fixtures/events after a change to the event
```

`scripts/capture_fixtures.sh` regenerates the Modelpin 0.5.3 fixtures offline with Modelpin's `fake` provider.
