# Agent Onboarding Guide

## What This API Can Do
The API supports authenticated user and admin workflows for key lifecycle management, completions, and major create flows across `play`, `watch`, `read`, `listen`, `explore`, `activities`, and `dream`.

## Current Load-Bearing Docs
Start with these before treating older docs as source of truth:

- `/docs/agent-onboarding.md` for API/agent access rules.
- `/docs/repo-conventions.md` for repo hygiene, generated artifacts, and archival rules.
- `/docs/api-impact-checklist.md` for Card completion evidence on API/data/admin changes.
- `/docs/bucket-list-api-surface.md` before touching bucket-list routes or template/list terminology.
- `/docs/explore-location-data-contract.md` before adding or editing Explore location records.

Other planning, audit, and sprint docs may describe historical decisions or superseded architecture. Prefer code headers, current tracker Cards and Work Orders, and the docs above when they disagree.

Machine-readable references:
- OpenAPI: `/openapi/openapi.v1.json`
- Capability manifest: `/.well-known/api-capabilities.json`
- Shared discovery aliases: `/api/v1/me`, `/api/v1/capabilities`, `/api/v1/usage`, `/api/v1/access-matrix`, `/api/v1/openapi`
- Skill pack: `/docs/agent-skill-pack.v1.json`
- Codex skill file: `/docs/skills/adventures-together-codex.SKILL.md`
- Claude Code skill file: `/docs/skills/adventures-together-claude.md`
- OpenCode skill file: `/docs/skills/adventures-together-opencode.md`
- Repo conventions: `/docs/repo-conventions.md` — read before creating files, archiving docs, moving Convex one-offs, or handling generated artifacts.
- Self-discovery endpoint: `/api/v1`
- Catalog research contract: `/docs/catalog-research-data-contract.md`
- Bucket list item audit playbook: `/docs/bucket-list-item-audit-playbook.md`
- API impact checklist for feature/change planning: `/docs/api-impact-checklist.md`
- Current work authority: repository `docs/tracker/GUIDE.md`; Cards and Work Orders travel with authorized clones. The tracker is internal documentation, not a public API.
- Agent issue handoff standard: `/docs/agent-issue-handoff-standard.md`
- **Bucket list vocabulary** (read before touching any bucket-list endpoint): `/docs/bucket-list-api-surface.md` — the table at the top distinguishes Ideas (proposed/staged future lists), Personal lists (user-private), Research templates (real templates with items), and Candidates. Names overlap; surfaces don't. Pick the one matching *intent*, not the closest-sounding word.

## Tier Model
- `trial`: low-volume discovery and starter automation.
- `personal` / **Standard**: default self-serve tier for normal write workflows.
- `contributor` / **Trusted**: trusted higher-throughput tier with public/shared item creation and updates across all 8 Together domains (never other users' personal records).
- `admin` / **Admin / Operator**: governance and security operations across all keys/users.

AWY-local boundaries:
- Partnership records, votes, completions, notes, and personal bucket lists are private user/partnership data. Agents may only read or write them with the requesting user's key and explicit workflow intent.
- Public bucket-list templates, catalog records, research packet replay, media credits, source reviews, image quality, and list audits are shared production surfaces. Treat them as public content operations, not personal automation.
- Explore coordinates, source evidence, identity resolution, and image metadata are high-trust content fields. Stage uncertain identity/source/image-rights calls for PM/admin review instead of patching by guess.
- Admin research packet replay, API key governance, audit logs, security events, tier overrides, and production integrity repairs require Admin / Operator authorization.

## Authentication Quickstart
1. Create key: `POST /api/v1/auth/register` (requires active Clerk session).
2. Send all API requests with:

```http
Authorization: Bearer <api_key>
```

3. Optional correlation ID:

```http
x-request-id: <your-correlation-id>
```

4. Verify first success:

```bash
export AT_BASE_URL="https://adventureswithyou.com"
export ADVENTURES_API_KEY="at_..."

curl -i -H "Authorization: Bearer $ADVENTURES_API_KEY" -H "x-request-id: first-success-me" "$AT_BASE_URL/api/v1/me"
curl -s "$AT_BASE_URL/api/v1/capabilities"
curl -i -H "Authorization: Bearer $ADVENTURES_API_KEY" "$AT_BASE_URL/api/v1/usage"
curl -i -H "Authorization: Bearer $ADVENTURES_API_KEY" "$AT_BASE_URL/api/v1/access-matrix"
curl -i -H "Authorization: Bearer $ADVENTURES_API_KEY" "$AT_BASE_URL/api/v1/bucket-lists?section=dream"
```

Use `/api/v1/access-matrix` or the CLI `doctor` command before a larger agent task. It tells the agent which preset workflows are ready, which endpoints are blocked by tier/session/admin requirements, remaining quota, and which request IDs/key prefix to include in support handoff notes.

If the doctor says a workflow is blocked by tier, submit an elevated-access request from `/settings/api-keys`. Include the intended workflows, data/content scope, expected volume, whether public catalog or bucket-list writes are needed, and whether Admin / Operator actions are needed. Admin approval applies a user-level effective tier override, so existing keys can inherit the approved access without rotating the key.

## User authority and current support

User-directed personal actions are permitted where supported. The September 5 owner decision supersedes earlier person-only bans: help with hearts, double hearts, Passes, completions, ratings, memories, notes, images, partnerships and private items within the user's access and instructions. Current MCP tools are narrower than REST/browser workflows; a missing tool is not a policy prohibition. Preserve attribution and privacy, and check the actual endpoint contract.

The website supports signed-in partnership creation and image-upload flows. REST supports private question creation; do not assume every catalog type supports private creation. Memory REST edits still use legacy fields, so do not claim full per-person editing parity. Partnership notes may be shared with the other member; they are not automatically person-private. Adventures does not set rules for how a user employs their AI outside this website.

## What Agents Can Do

### Now, With Standard Access
- Discover the API, inspect capabilities, usage, and access matrix.
- Manage the agent's own API keys.
- Read allowed user/partnership data for the user's active workflow.
- Help with authorized planning and personal-data workflows, including hearts, completions and memory create/edit/delete where the endpoint supports them.
- Preserve `requestId` and `x-request-id` values in handoff notes.

### Later, With Trusted Access
- Add or update public/shared catalog and bucket-list content across the Together domains.
- Run higher-volume content production workflows after checking source-rights, image quality, and list scope.
- Attach reusable catalog research and rich content when the canonical item identity is clear.

### Access and unresolved intent
- Admin / Operator actions: key/user governance, tier overrides, audit logs, security events, production integrity repairs, and research packet replay.
- Do not access private data outside the requesting user's permissions or invent another person's views.
- Ambiguous source-rights, image-license, coordinate, identity, or canonical-link decisions.
- Use the access required by the chosen interface. A logged-in browser or an existing user authorization is not a reason to ask again for routine actions in that workflow; unavailable access and unclear intent still need resolution.

## Where Unclear Work Belongs

Read the repository tracker Guide and the relevant Card. Record API parity,
tier/scope, operator-access or escalation decisions on that Card; create a
bounded decision Card if none covers the question. Do not resolve old three-digit
issue identifiers or manufacture a current owner from them. Verify inventory
and discovery changes with `pnpm api:artifacts:check` and
`pnpm test:api-contract`.

## API Impact Notes
Every substantial product, admin, catalog, automation, or UX change should include an API impact note in the repository tracker. Use `/docs/api-impact-checklist.md` for the pasteable issue section and completion-comment template. Agents may write `API impact: none` for isolated UI/internal changes, but should create or link a decision issue when API parity, tier/scope, Admin / Operator access, or access escalation is unclear.

## Agent Trace Mode
For debugging handoffs, agents can opt in to sanitized trace metadata on supported endpoints:

```http
x-agent-debug: true
```

Trace metadata is safe to paste into Card evidence or support notes. It can include request ID, operation ID, method/path, tier, key/user IDs, duration, action/entity summary, and redaction markers. It must not include bearer tokens, raw API keys, key hashes, full request bodies, prompt bodies, source documents, or private partnership records. CLI calls can use `--trace` with `call`.

## Error Contract
All errors use:

```json
{
  "ok": false,
  "error": {
    "code": "RATE_LIMITED",
    "message": "Rate limit exceeded",
    "details": { "limit": 300, "remaining": 0, "resetAt": 1771860300000 },
    "requestId": "..."
  }
}
```

## Safe Defaults

### Retries + Idempotency
For non-idempotent writes, send `Idempotency-Key`.

```http
Idempotency-Key: 9f8c9d0e-3f3b-48ab-9ae2-bf43a8e5bf22
```

Server behavior:
- same key + same payload => replayed success response
- same key + different payload => `409 IDEMPOTENCY_KEY_REUSED`
- duplicate request currently processing => `409 IDEMPOTENCY_IN_PROGRESS`

### 429 Backoff
On `429`, use headers:
- `x-ratelimit-window`
- `x-ratelimit-limit`
- `x-ratelimit-remaining`
- `x-ratelimit-reset`
- `retry-after`

Backoff rule:
- Prefer `retry-after` seconds.
- If absent, wait until `x-ratelimit-reset`.
- Add jitter to avoid burst retries.

### Permission/Tier Denied
- `401 UNAUTHORIZED`: key missing/invalid/expired.
- `403 FORBIDDEN`: key tier too low for endpoint.
- Do not retry permission failures without changing key or endpoint.

## CLI Onboarding
The project ships a CLI at `tools/at-api-cli/at-api-cli.mjs`.

High-value commands:
- `discover`
- `capabilities`
- `doctor`
- `play-search --q "..."`
- `dream-lists --partnership-id ...`
- `dream-create-list --partnership-id ... --name "..."`
- `dream-add-item --partnership-id ... --title "..."`
- `security-events --admin-key ...`
- `audit-logs --admin-key ...`
- `npm run integrity:bucket-audit -- --admin-key ... --base-url ...`

## Recording a user's completion through REST

The REST API exposes `POST /api/v1/partnerships/:id/completions`, with
`Idempotency-Key` and returned `requestId` values. An assistant may use it
on the user's instructions and within the key's access. Confirm the intended
item and whether the user is recording an individual or together experience;
do not infer a completion from a heart or invent either person's experience.
Reuse an idempotency key only for the same intended write. The current MCP
connection does not yet expose this workflow; that limitation does not prohibit
using a supported REST route.

## Workflow Recipe: Research a Catalog Item
1. Create or update the canonical catalog item with concise fields such as title/name, taxonomy, short description, website, tags, and primary image when available.
2. Store reusable research through:
   - `PUT /api/v1/catalog/:section/:catalogTable/:catalogItemId/research`
   - `PUT /api/v1/catalog/:section/:catalogTable/:catalogItemId/rich-content`
3. Include aliases/search names, structured source evidence, media assets, and `learn_more` rich content when the item has enough substance.
4. Keep bucket-list membership fields separate. Bucket-list rows should only store list-specific rank/order, `whyIncluded`, notes, and citations.
5. Do not write Learn More as a checklist. Write like a strong educational guide or thoughtful recommender, with length matched to the item’s substance.

## Workflow Recipe: Audit a Bucket List
1. Load `/docs/bucket-list-item-audit-playbook.md` before changing bucket-list items, images, tags, sources, or Learn More guides.
2. Verify the bucket-list scope and current canonical links first. Do not create duplicate catalog records for alternate names.
3. Audit images as first-class evidence: the primary image must show the exact item or a clearly representative example, with a source page, alt text, credit, and license when known.
4. Audit tags as search facets, not filler keywords. Remove generic tags and list-wide theme tags repeated on every item.
5. Apply only high-confidence patches. Stage ambiguous identity, source, image-rights, or list-scope decisions for admin review.

## Operational Debugging
- Use `requestId` from errors when reporting issues.
- Admin users can query `GET /api/v1/admin/audit-logs` and filter by `requestId`, `keyId`, or time range.
- Use `GET /api/v1/admin/security-events` for focused security investigations; the response includes a risk-ranked security summary for top keys.
- Use `docs/api-incident-response-playbook.md` when deciding whether to suspend API access, rotate/revoke keys, lower tier, or treat a signal as normal heavy usage.
- Use `GET /api/v1/admin/stats` for key lifecycle, trend, and security summary analytics.
- Use `GET /api/v1/admin/access-requests` and `PATCH /api/v1/admin/access-requests/:id` to review API Center escalation requests.
- Use `GET /api/v1/admin/operations/overview` and `GET /api/v1/admin/operations/partnerships` for partnership health diagnostics.
- Use `GET /api/v1/admin/integrity/bucket-list` and `POST /api/v1/admin/integrity/bucket-list` for bucket-list reconciliation reporting and repair runs.
