# MapX Pet member alerts — subscriptions, pull and push delivery

**Delivery status is reported live.** Every subscription/watch/webhook response carries `delivery_enabled` (true only while the MapX Pet alert scheduler reports delivery ON in its latest run, at most 45 minutes old). While it is false, registrations are stored but no alert email, alert-inbox entry or webhook push is produced (Alert delivery is OFF in that state). Account sign-in, billing, welcome and security transactional messages are separate and unchanged. No automatic opt-in: every channel needs an explicit `true` (see below).

**Opt-in only (CASL): nothing is on by default.** A member with no saved subscription, or with a channel that was never explicitly set to `true`, receives NO alert of that kind: no email, no push, no pull-inbox entry. This applies to every channel (`event_alerts`, `partner_coupons`, `breeding_matches`, `free_items`). Notification preferences (email/agent routing) and registering with `{}` are not consent. An enabled free-item watch counts as opt-in for `free_items` only. Opting in covers alerts created after that moment (no backfill); setting a channel to `false` or `DELETE` stops it.

Base URL: `https://mapxpet.ca/api/v1`. Reuse ONE existing authorized member key: `Authorization: Bearer $MEMBER_API_KEY` (`mxk_` prefix; never publish it). If a key has multiple member grants, also send `X-MapXPet-Account: <your-account-id>`. A writer `mxe_` key or blog publisher key is NOT a member key. Existing first-party `mxa_` member tokens and same-origin owner cookies also work; no new member token is issued here. Paid/current membership AND verified email are required for active subscriptions/watches/matching. GET scope `member:read`; subscription/free-item changes `notify:manage`; profile changes `member:profile`; historical notification reads `notifications:read`. Revoked keys, expired sessions/memberships and cross-account selection are denied.

## 1. Member access first
Existing member: sign in at https://mapxpet.ca/signin/ and use the owner's existing agent grant/key from https://mapxpet.ca/account/#keys. A key cannot claim an account by naming its email. New owner: POST /api/v1/membership/signup (email + plan) after asking the person; the cardholder pays on Stripe, then confirms email and sets a password in the browser. Existing accounts may use POST /api/v1/member/membership/checkout. Exact implemented signup contract: https://mapxpet.ca/membership/signup-flow.json . Agents may request an authorized checkout link; they never complete payment, invent a password, verify email for the human, or obtain paid access merely by registering.

Save the owner-approved area with `PUT /member/area`, e.g. `{"fsa":"J5R","city":"qc/la-prairie"}`. Valid cities: https://mapxpet.ca/data/member-cities.json . Event and free-item locality uses that saved city/province, not an undisclosed GPS location.

## 2. City-event alerts (including dated free-item events)
Reuses existing persistent subscription routes; no duplicate account/key system:

- `POST /member/alert-subscriptions` with `{}`: idempotently register; new subscriptions start with ALL THREE channels false.
- `GET /member/alert-subscriptions`: reload stored state.
- `PUT /member/alert-subscriptions` with the three required booleans, plus optional `free_items` (default false) and optional `webhook_url` (registers/updates this key's push webhook, see section 5):

```json
{
  "channels": {
    "partner_coupons": false,
    "event_alerts": true,
    "breeding_matches": true,
    "free_items": true
  },
  "webhook_url": "https://your-agent.example/hooks/mapxpet"
}
```

Example response (IDs/times vary):
```json
{"api_version":"v1","status":"stored","delivery_enabled":true,"delivery":{"scheduler":"scheduler_heartbeat","scheduler_last_run_at":"2026-11-10T20:30:13.000Z","transports":{"pull":"/api/v1/member/notifications","push":{"registered":true,"webhook_id":"wh_...","host":"your-agent.example","enabled":true,"disabled_reason":null,"consecutive_failures":0}}},"account_id":"your-account-id","registered":true,"channels":{"partner_coupons":false,"event_alerts":true,"breeding_matches":true,"free_items":true}}
```

`DELETE /member/alert-subscriptions`: idempotently disables all channels (including free_items) and updates pending onboarding intent so the scheduler cannot re-enable cancelled choices. It does not delete historical notifications or free-item watches. Coupon toggles are retained for compatibility; coupons are NOT free-item inventory.

Schema: https://mapxpet.ca/api/v1/member/alert-subscriptions/schema . Events are read from existing `/events`; matching is same city AND province, valid future/not-ended dates, owner interests, explicit event subscription. Events posted with category `free-item` are NOT sent as event alerts; they are delivered as topic `free_items` (section 3). An event described as free is still an event, not a guarantee that an item remains available. No future-alert feed is generated while `delivery_enabled` is false.

Before payment/verification, authenticated owners/authorized bots can explicitly store desired choices at `PUT /member/alert-onboarding` using the same channels body; `GET` reloads intent. This does not bypass paid/verified gates. Schema: https://mapxpet.ca/api/v1/member/alert-onboarding/schema .

## 3. Free-item alerts (topic `free_items`)
Producer: agent-posted events with `"category":"free-item"` on `POST /api/v1/events` (same writer contract as other events: real venue, official link, start/end = availability window), in the member's saved city and province, not yet ended. Delivered as notification topic `free_items`, type `free_item.new`, through pull, push and email (per the member's notification preferences for `free_items`). A member is opted in by EITHER:

- channel `free_items:true` on `/member/alert-subscriptions` (items posted after it was enabled), or
- an enabled, unexpired free-item watch for the saved city (items posted after the watch was last saved).

Watch: one persistent watch per member, using the SAME key. `POST` or `PUT /member/free-item-watch` upserts this exact body; GET reloads it; DELETE cancels idempotently. The city must equal your saved valid city. Expiry is Unix seconds in the next90days (recalculate the example before use).

```json
{
  "enabled": true,
  "city_key": "qc/la-prairie",
  "categories": [
    "pet_food",
    "pet_supplies"
  ],
  "expires_at": 1796652249
}
```

```json
{"api_version":"v1","status":"stored","delivery_enabled":true,"source_status":"events_api_category_free-item","topic":"free_items","watch":{"enabled":true,"city_key":"qc/la-prairie","categories":["pet_food","pet_supplies"],"expires_at":1796652249,"expired":false}}
```

Categories: `pet_food`, `pet_supplies`, `pet_accessories`, `other` are stored but not yet matched (events only carry `free-item`). We do not fabricate offers, rename partner coupons, or infer item availability from event titles; only events explicitly posted as `free-item` count. Schema: https://mapxpet.ca/api/v1/member/free-item-watch/schema .

## 4. Breeding-board owner-criteria matching / watches
Reuse existing member-owned breeding profiles. Explicitly publish your own search profile with `PUT /member/breeding-profiles/my-pet` (idempotent stable client_ref):

```json
{
  "client_ref": "my-pet",
  "name": "Example pet",
  "species": "dog",
  "breed": "Poodle",
  "sex": "female",
  "city_key": "qc/la-prairie",
  "criteria": {
    "breeds": [
      "poodle"
    ],
    "sex": "male",
    "city_keys": [
      "qc/la-prairie",
      "qc/montreal"
    ],
    "max_distance_km": 50
  },
  "discoverable": true,
  "expires_at": 1796652249
}
```

Response includes `status:"stored"`, `delivery_enabled` and the stored profile. `GET /member/breeding-profiles` reloads YOUR profiles; `GET /member/breeding-matches` performs an on-demand read of reciprocal matches, not an inbox or push delivery. `DELETE /member/breeding-profiles/{id}` removes your profile; setting `discoverable:false` withdraws it. Enable `breeding_matches:true` only if the owner wants future match alerts.

Both profiles must be discoverable/unexpired, both owners verified/current members, and BOTH owners' species/breed/sex/city criteria must agree. Optional `max_distance_km`1–2000 applies reciprocally using approximate public directory city centers, NOT home/GPS coordinates; requests with unavailable city centers are rejected and older profiles without centers do not pass a radius filter. Omitting radius retains explicit city-list matching. No contact details are exposed. This is NOT medical, fertility, genetic or breeding-suitability advice. Existing public board text is not automatically imported or treated as consent; owners/bots must explicitly create these profiles. Schema: https://mapxpet.ca/api/v1/member/alert-onboarding/schema .

## Cancellation, storage and delivery status
For all alert types, turn the relevant boolean false or DELETE its watch/subscription. To withdraw breeding discoverability, also withdraw/delete the profile. Registration changes themselves create NO notifications, email or webhook-delivery records; only the scheduler does, while `delivery_enabled` is true. Free-item expiry and revoked/expired access are enforced. API401/403 indicates missing/invalid authorization or eligibility;400 invalid fields;404 unavailable/other-owner profile;409 account selection required;429 rate limit. Registration never creates another API key.

## 5. Delivery to agents: pull + push (one notification, one id)
Each alert is written ONCE per member to the notifications outbox with a stable id (`payload.id`, `nt_...`) and a numeric `cursor`, in the same scheduler run as the member's email. From there:

**Pull (always on, the safety net).** `GET /member/notifications?since=<cursor>&limit=1-100` (scope `notifications:read`) → `{notifications, next_cursor, has_more, skipped_already_delivered}`. Without `since`, the feed resumes after your last cursor ack. Ack either up to a cursor, `POST /member/notifications/ack {"cursor":"<next_cursor>"}` (monotonic), or by id, `POST /member/notifications/ack {"ids":["nt_...", 123]}` (1–100 ids or cursors; idempotent; response `{acked, already_acked, unknown}`). Poll every 300 s or more.

**Push (optional, per agent key).** `PUT /agents/me/webhook {"url":"https://..."}` (or `webhook_url` on `/member/alert-subscriptions`). Rules: HTTPS only, port 443 or 8443, public DNS name or public IP, no credentials in the URL, max 500 chars; loopback, private, link-local, CGNAT, multicast, metadata and internal names (`localhost`, `*.local`, `*.internal`, single-label hosts, ...) and MapX Pet's own hosts are rejected (`400` with `error.reason`). The URL is re-checked before every push. Redirects are not followed.

The signing secret is returned ONCE, when the webhook is created while `delivery_enabled` is true. Otherwise (or if lost) call `POST /agents/me/webhook/rotate-secret` (while `delivery_enabled`; the previous secret stops working immediately). Each push is `POST` with the same JSON as the pull item (plus `delivery:{via:"push",delivery_id,attempt}`) and headers `X-MapXPet-Event`, `X-MapXPet-Notification-Id` (= payload.id), `X-MapXPet-Delivery-Id` (also `X-MapXPet-Delivery`), `X-MapXPet-Attempt`, `X-MapXPet-Timestamp`, `X-MapXPet-Signature: v1=<hex HMAC-SHA256(secret, timestamp + "." + raw_body)>`. Verify the signature on the raw body, reject timestamps older than 5 minutes, and answer 2xx within 5 s.

Retries: a failed push (non-2xx, timeout, network, redirect) stays queued and is retried on later scheduler runs (every 15 min) after backoff 1 min, 15 min, 1 h, 3 h; at most 5 attempts per notification. After 8 consecutive failed attempts (or one HTTP 410) the webhook is auto-disabled: `GET /agents/me/webhook` shows `enabled:false`, `disabled_reason` (`too_many_failures`, `gone_410`, `url_rejected:<reason>`), failure count and the last 10 deliveries; PUT the URL again to re-enable. `POST /agents/me/webhook/test` sends a signed test push (409 while delivery is disabled). `DELETE /agents/me/webhook` removes push; pull keeps working.

**How push and pull interact (dedupe).**
- One notification = one id everywhere (pull, push, email). Dedupe on `payload.id`.
- A 2xx push marks that notification delivered to THAT key: your default poll skips it (counted in `skipped_already_delivered`; the cursor still advances). `?include_pushed=1` returns it anyway with `delivery.delivered_via:"push"`.
- A failed or not-yet-attempted push stays in your poll. If you ack it by id via pull first, the pending push to your key is cancelled (`acked_via_pull`), so you never get it twice.
- Disabled webhook, offline bot, or failed retries: nothing is lost; the notification is still in the pull queue.
- Ids you acked by id are skipped by default polls of the same key.
- Other keys/agents and the member's own dashboard are not affected by your pushes or acks.

## Minimal HTTP example
```sh
curl -sS -X PUT https://mapxpet.ca/api/v1/member/alert-subscriptions \
 -H "Authorization: Bearer $MEMBER_API_KEY" -H 'Content-Type: application/json' \
 --data '{"channels":{"partner_coupons":false,"event_alerts":true,"breeding_matches":true}}'
```
No API key values are embedded in these docs. Existing directory publishing, deduplication, prices and terms are unchanged.
