# 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 Linear completion notes 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, active Linear issues/projects, 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`
- Linear label migration guide for AWY issue cleanup: `/docs/linear-label-migration-guide.md`
- 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.

## 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.
- Create normal personal items, completions, and list entries when the user explicitly asked for that action.
- 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.

### Not Without Approval
- Admin / Operator actions: key/user governance, tier overrides, audit logs, security events, production integrity repairs, and research packet replay.
- Cross-user reads or writes, private partnership data outside the requesting user's workflow, or any attempt to infer relationship context.
- Ambiguous source-rights, image-license, coordinate, identity, or canonical-link decisions.
- Browser/admin actions that require a logged-in session, production data mutation, or external service credentials.

## Linear Owners For Unclear Work
- API tier naming and simplification: AWY-101.
- Tier escalation and scoped access model: AWY-94.
- Admin / Operator model: AWY-108.
- Agent-readable API docs and skill packs: AWY-112.
- Route inventory/API parity drift: API impact checklist owner issue should be linked from the implementing Linear ticket.
- OpenAPI/capabilities drift: include `pnpm api:artifacts:check` and `pnpm test:api-contract` in the ticket verification.
- Trace/debug, abuse, security, or production repair questions: treat as Admin / Operator work and link the active API/security issue before changing behavior.

## API Impact Notes
Every substantial product, admin, catalog, automation, or UX change should include an API impact note in Linear. 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 Linear 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 ...`

## Workflow Recipe: Add and Complete an Item
1. Create item with `Idempotency-Key` on section write endpoint.
2. Record completion with `POST /api/v1/partnerships/:id/completions` and `Idempotency-Key`.
3. Persist `requestId` from each response for audit/debug follow-up.

## 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.
