# Agentry — install bootstrap

If the user pasted this URL and said "install this" or "set it up", do the
install. Do NOT summarize this file back to them. Do NOT claim success until
`POST /v1/projects/:project_id/install/verify` returns `ok: true`.

This file is intentionally lean. After reading it:

Set a custom `user-agent` header on every non-browser direct Agentry HTTP
request. Defaults such as `Python-urllib/3.x` can be blocked by Cloudflare
with CF error 1010. Browser fetch uses the browser's own User-Agent and cannot
set this header manually.

1. Fetch `/v1/setup/manifest`, then `/v1/install/contract`.
   That structured JSON contract is the authoritative machine-readable source
   for phases, ordered steps, approval gates, snippet references, and verify rules.
   Use `framework_env_matrix`, `host_env_matrix`, and
   `env_preflight_checks` from setup responses before choosing public env
   prefixes, host secrets, or deploy-hook placement.
2. Derive the plan with `POST /v1/install/plan`.
3. Before each mutating call you have not already loaded, fetch the narrow
   filtered operation schema for exact payload shape, required/optional fields,
   auth, and response properties:
   `/v1/openapi.json?flow=install`,
   `/v1/openapi.json?tag=Install&include_components=false`, or
   `/v1/openapi.json?path=%2Fv1%2Fprojects%2F%7Bproject_id%7D%2Finstall%2Fverify&method=post`.
   Do not guess payloads from prose.
4. Use `/agentry.md` later for day-to-day questions, reports/interfaces, and
   post-setup ops features.

Agentry has no SDK by design. The install generates a small runtime helper for
`POST /v1/logs/` and `POST /v1/analytics/`, then wires `POST /v1/deploys/`
only from CI/provider post-deploy automation. The durable install artifact is
the approved business question, funnel/business logic flow, required events and
properties, failure surfaces, and verify proof.

## Minimum verified install lane

The first beta success path is intentionally small:

1. Resolve auth/project and fetch `/v1/setup/manifest` +
   `/v1/install/contract`.
2. Inspect enough source to name the business question, value funnel, relevant
   events/properties, failure paths, deploy surface, and concrete wiring targets.
   Include exact file plus function/handler/route evidence for every route,
   server action, background job, webhook, lifecycle event, and failure surface
   you might ask Agentry to wire; prose inventories like "server actions:
   createProject, inviteMember" are not enough.
3. Call `POST /v1/install/plan` with those discovered facts; do not invent a
   hand-written plan.
4. Present `plan_review.message_markdown`, wait for approval, then save the
   signal map.
5. Wire the approved runtime writes: `/v1/logs/`, `/v1/analytics/`, and
   `/v1/deploys/` when those signal types are in scope.
6. Save the implementation report and run
   `POST /v1/projects/:project_id/install/verify`.

Minimum does **not** mean building dashboards, public-query publications,
feature flags, cohorts, surveys, A/B tests, session replay, alerts, webhooks,
suppressions, sourcemaps, invites, billing, usage, or every possible future
question before first success. Those are readiness follow-ups unless the user
explicitly asked for them. If verify returns `ok:true` with
`readiness_gaps`, report the install as working and name those gaps; do not
claim every product question is fully answerable yet.

## Credentials & project binding

Separate the agent/owner credentials from the app runtime credentials:

- **api_key (`agk_`, secret — never commit):** read it from the
  `AGENTRY_API_KEY` env var, else from `~/.agentry/credentials.json`
  (`{ "api_key": "agk_..." }`). If neither exists, run the device flow:
  `POST /v1/auth/device` → give the user the `verification_uri_complete`
  link → poll `POST /v1/auth/device/poll` every `interval` seconds until it
  returns an `api_key` → write it to `~/.agentry/credentials.json` (chmod 600).
  Send it as `Authorization: Bearer <api_key>` on authed calls; confirm with
  `GET /v1/me`.
- **project_id (not secret — safe to commit):** read `.agentry/config.json`
  (`{ "server_url", "project_id" }`), else `AGENTRY_PROJECT_ID` env
  at the repo root. If neither exists, `GET /v1/projects` (or `POST /v1/projects`
  to create one) and write `.agentry/config.json` so every teammate + CI run
  targets the same project. Ingest endpoints derive this from `AGENTRY_DSN`;
  do not add `AGENTRY_PROJECT_ID` or a project id URL segment just for app
  telemetry.
- **project DSN (`agnt_`, publishable ingest token):** read it from the app's local
  or host env as `AGENTRY_DSN`. Do not rotate just to inspect it. Owners can call
  `GET /v1/projects/:id/dsn` to recover the current DSN when Agentry has an
  encrypted copy, or `POST /v1/projects/:id/dsn/verify` with a candidate DSN to
  check it without changing anything. Only call
  `POST /v1/projects/:id/dsn/rotate` when the DSN is lost, stale, or leaked, and
  then update every local, CI, staging, and production `AGENTRY_DSN`.
- **teammates:** invite them with `POST /v1/projects/:id/invites` and
  `role: "member"` or `role: "owner"`. An invited owner has full project-owner
  access with their own `agk_` key. Invites never rotate or change the
  project's `AGENTRY_DSN`.

The canonical handoff state lives on the server: `/v1/projects/:id/signal-map`
and `/v1/projects/:id/implementation-report`. Repo-local `.agentry/*.json`
artifacts such as planner output, verify requests, or debug captures are optional
debug/handoff files only. Do not create root-level `.agentry-*` scratch files,
and do not commit generated local state.

Do not copy raw `agk_`, `agnt_`, bearer tokens, or full credential/session JSON
into debug, resolved-state, repo-audit, implementation-report, or handoff files.
If a local state artifact is useful, store only `project_id`,
`server_url`, presence booleans such as `has_api_key`/`has_dsn`, and redacted
prefixes or suffixes. Raw `AGENTRY_DSN` belongs only in app/runtime env or
host/CI env or secrets storage where ingest actually uses it. For install verify,
put the raw DSN only in the in-memory POST body and save any
`.agentry/verify-request.json` snapshot with `dsn` set to
`<redacted:AGENTRY_DSN>`.

The app's ingest DSN (`agnt_`) is separate — it's the publishable ingest token your
app code uses to POST events, kept in the app's intended env (e.g. `AGENTRY_DSN`
or a framework-public DSN env for browser telemetry). It is not an owner/API key.

## Agent rules

1. By default, treat "install Agentry" as all three signal types: errors, analytics, and deploys. If the user explicitly scopes the install or `signal_types` narrows the request, wire only the requested surface and preserve the omitted signals as follow-up context instead of silently widening scope.
2. Resolve auth/project state BEFORE discovery (see Credentials & project binding).
   If you already have an api_key, skip the device flow. Re-use the existing project
   for this repo when `.agentry/config.json` is present; otherwise create/select it
   before discovery.
3. After auth/project creation, enter planning mode before touching code.
   If your runtime exposes a planning-mode tool (for example `EnterPlanMode` / `ExitPlanMode`),
   call it immediately after auth/project creation and stay in planning mode through discovery,
   planner output, and user approval. In non-interactive harnesses, do not call
   `ExitPlanMode` just to present the plan; send `[AWAITING_USER]` and the
   approval message as the assistant response, then stop the turn instead.
4. Let `POST /v1/install/plan` decide WHAT to instrument from the repo's
   business question, funnel/business logic flow, and answer contracts; use the
   structured contract only for HOW to wire the chosen surface/runtime. When the
   planner is reachable, do not substitute a hand-written plan.
5. If your runtime supports forced tool choice, force the planning call for the planning turn and the verify call for the final gate.
6. Save the full planner JSON silently, then present `plan_review.message_markdown` directly in the assistant response when it exists; do not rewrite the approval step from scratch unless you must. Tool output, shell stdout, `cat`, `sed`, `node`, or a saved file is not user approval. The planner message is intentionally concise; use structured fields for extra detail instead of expanding the approval step.
   The planner request body is non-secret: do not include `dsn`, `api_key`,
   bearer tokens, copied session JSON, or raw `AGENTRY_DSN` in
   `POST /v1/install/plan` or `.agentry/plan-request.json`. Runtime DSNs
   belong only in app env, host/CI secrets, direct ingest auth, and the final
   verify request.
7. Save the approved signal map after confirmation, save the implementation report after code edits, then verify.
8. Do not report "installed" unless `POST /v1/projects/:project_id/install/verify` returns `ok: true`.
9. If verify reports pending real data but `ok: true`, treat setup as verified and surface the missing flows as question/readiness gaps. Dashboards may show those gaps later, but dashboard construction is not the setup contract; the durable contract is the approved business question, funnel, events/properties, failure surfaces, and verify/read proof.
10. After verify passes, include the go-live host env checkpoint in the final handoff:
    read the live Agentry values from local `.env`, `.env.local`, `.env.production`, `.dev.vars`,
    `.agentry/config.json`, and `~/.agentry/credentials.json` when needed; detect the host
    actually used by the repo (Vercel, Netlify, Render, Railway, Fly, Docker/Kubernetes, GitHub Actions,
    or another provider); state which vars are required there and whether you set them or need user action.
    If your CLI/session can set host env vars or CI secrets immediately, do it for production and staging;
    otherwise ask the user to paste the variables into that host's env UI as follow-up.
    At minimum wire `AGENTRY_DSN`. `AGENTRY_URL` is optional and defaults to
    `https://api.agentry.sh`; `AGENTRY_PROJECT_ID` is only for owner/API tooling
    that cannot derive it from the DSN. Add `AGENTRY_API_KEY` only in
    server-side/admin/CI environments that call owner-side Agentry APIs.
    Never expose `AGENTRY_API_KEY` through client-public env prefixes. Redeploy and trigger a real flow
    only when go-live proof is explicitly requested or immediately available; it is not an install blocker after
    verify returns `ok:true`.
11. Before your final response, run the Agentry product-defect feedback checkpoint.
    If Agentry's API, docs, OpenAPI schema, install contract, or verify
    gate was wrong or misleading, fire-and-forget `POST /v1/feedback` with
    `kind: "agent_discovered_bug"` and a stable `fingerprint`. Do this even
    if you worked around the defect and the user is no longer blocked; do not wait
    for repeated failures.
12. Reports, dashboards, protected `/agentry` routes, public-query URLs, and
    automations are optional post-setup output. Build them only after
    `install/verify` returns `ok:true` and only when the user asks for that
    follow-up. First report the minimum install result, readiness gaps, and
    go-live env handoff. Then use `/agentry.md`, `/v1/docs/query`,
    `/v1/query-blueprints`, answer contracts, event/property metadata, cases,
    deploys, and filtered OpenAPI docs to design the optional surface.

## Install flow

1. Resolve auth/project state — see Credentials & project binding above.
   - If you have no api_key, run the device flow; otherwise reuse it.
   - If `.agentry/config.json` binds a project, reuse it.
   - Otherwise `GET /v1/projects` (or `POST /v1/projects`) and write `.agentry/config.json`.

2. Discovery
   Read the FULL PRODUCT REPO, not just the main route:
   - identify the primary business question this install should answer
   - map the happy-path funnel / business logic flow to the ideal user outcome
   - work backward from that question to the events, properties, failure paths, and deploy context needed for an honest answer
   - capture repo-specific `product_summary`, `product_category`, `metric_lens`, and `primary_outcome`
   - capture already-live analytics or business event names in `existing_live_events`
   - capture already-live event properties in `existing_event_properties` when code proves them, for example from `capture("event", { property })` or `track("event", { property })` calls
   - capture key entities and the important journey stages in `key_user_journeys`
   - inventory `ui_surfaces`, `api_surfaces`, `async_surfaces`, `admin_surfaces`, and `deploy_surfaces` so shared request/page telemetry and deploy attribution cover the whole product, not just the signup funnel
   - put cron jobs and app/API routes in `async_surfaces` or `api_surfaces`, not `deploy_surfaces`; deploy surfaces are CI workflows, provider deploy hooks/config, release scripts, or an explicit "none found" note
   - preserve literal UI copy and commented/TODO event names in `notes` or `planned_wiring_candidates`; only put an event in `existing_live_events` when code actually emits it
   - infer shapes and revenue/B2B/two-sided flags
   - identify domain entities and state transitions
   - inventory public/auth/admin/internal routes
   - note risky failure paths, swallowed failures, jobs, webhooks, integrations, `monetization_surfaces`, `external_dependencies`, and existing telemetry
   - include source, config, migrations, tests, templates, and ops scripts
   - skip vendor/build noise like `node_modules`, `.next`, `dist`, `build`, coverage output, and generated assets unless the app's own source truly lives there

3. `POST /v1/install/plan`
   Turn the detected surface/runtime + shapes + current inventory + discovery_map into:
   - the business question this install is designed around
   - `required_events`, `required_event_properties`, `provider_satisfied_events`, `missing_events`
   - `event_buckets`, `happy_path_funnel`, `failure_surface_map`
   - `coverage_checklist`, `plan_review`
   - `signal_map_template`, the canonical body to save after user approval
   - `post_setup_blueprint` for the written question/readiness handoff, optional UI hints, deployment env handoff, and automations
   - `suggested_questions_to_answer`, `future_question_prompt`, `questions_for_user`
   Answer contracts are the telemetry coverage commitments for this install:
   adapt each question and event/property requirement to the saved signal map. Do not copy examples as-is.
   If existing analytics wrappers already emit properties, include `existing_event_properties`
   or exact captured-property evidence in the planner request; otherwise the planner must treat
   those properties as unproven and report them as gaps.
   Do not include `dsn`, `api_key`, bearer tokens, copied session JSON, or
   raw `AGENTRY_DSN` in the planner body or `.agentry/plan-request.json`;
   this endpoint accepts non-secret planning context only.

4. Approval checkpoint
   Present `plan_review.message_markdown` if present, with the future-question prompt intact.
   Wait for approval or corrections before any major code edits.
   The approval step must surface:
   - the happy-path funnel
   - the coverage checklist
   - events already live
   - events/properties still to add
   - "Questions this install is designed to answer"
   - the post-setup question/readiness handoff, with `/agentry` and panel ideas only as optional downstream UI guidance
   - the 3–6 month future-question prompt
   - the most important approval questions from `questions_for_user`
   Keep this checkpoint concise enough that the agent can complete implementation and verify in the next turn; full detail belongs in the structured plan JSON.
   If the planner reports assumption warnings about empty journeys, primary outcome, key entities, surface inventories, dependencies, or risky failure paths, resolve those gaps before code edits.
   If the user approves the planner output as-is, PUT `signal_map_template` as the request body; do not rebuild the plan by hand before saving it.

5. `PUT /v1/projects/:project_id/signal-map`
   After approval, PUT the planner's `signal_map_template` to persist the approved discovery map, funnel, event buckets,
   failure surface map, event-property commitments, answer contracts, and
   `planned_wiring_map` / `post_setup_blueprint` so future sessions and verify
   runs resume from the same contract without reopening the bulky planner output.

6. Implementation
   Wire:
   - comprehensive error capture, including handled/swallowed failures
   - comprehensive analytics, including shared request/page telemetry for meaningful routes, endpoints, and internal workflows
   - revenue events when billing exists
   - deploy capture with the real git SHA from CI or the deployment provider after deploy success
   - privacy disclosure from `/v1/privacy/disclosure`

7. `PUT /v1/projects/:project_id/implementation-report`
   Persist the execution handoff: files touched, coverage added, unresolved gaps, and follow-up checks.
   Do not include raw API keys, DSNs, bearer tokens, or full credential/session JSON in this report
   or in `.agentry` helper files such as `resolved-state.json`; use redacted summaries and
   presence booleans only.

8. `POST /v1/projects/:project_id/install/verify`
   Run the hard gate with owner auth `Authorization: Bearer $AGENTRY_API_KEY`.
   Use the project `AGENTRY_DSN` only as `body.dsn`, along with the
   shapes/flags used in planning and a fresh `repo_audit` built from the
   current approved signal map (the server cannot read your checkout, so the
   audit is your coverage proof).

Verify success requires:
- synthetic errors + analytics + deploys all pass
- the approved signal map exists
- the implementation report exists and matches the approved plan hash
- the current repo audit is structured proof, not prose
- no hard `gate_failures` remain

Missing planned events/properties, weak state-transition proof, missing real
traffic, blocked answer contracts, missing shapes, and missing error-surface
coverage are returned as `readiness_gaps`. They are still important product
work, but they do not make a working beta install look broken. Report setup as
verified when `ok: true`, then use the gaps to decide which flow to trigger,
which server outcome event to move, or which question/report empty state to show.
The final user handoff must explicitly repeat non-empty `readiness_gaps`,
zero real traffic, pending/blocked answer contracts, and missing real events or
properties. Do not collapse this state to only "Verification returned ok:true";
say "install verified, but these product questions still need real traffic or
instrumentation" and name the gap messages/counts.

If verify returns `ok: false`, the install is NOT done.

If verify returns `ok: true`, the minimum install is complete after the final
handoff. That handoff should document the approved business question,
funnel/business logic flow, events, properties, and readiness gaps so a future
agent can answer day-to-day questions without reopening the whole install. Use
the saved `post_setup_blueprint` to build a small protected Agentry question
surface only when the user asks for it or it clearly fits the app; `/agentry`
is the suggested default protected route, not a required implementation pattern.
Apply or hand off deployment env vars when possible, and propose automations as
optional follow-up. Do not turn generic examples into UI literally; use the app's saved funnel, entities, live events,
and failure surfaces.

9. Go-live host env checkpoint
   A local install is not live until the deployment host has the same Agentry
   env vars. Read live values from local `.env`, `.env.local`, `.env.production`,
   `.dev.vars`, `.agentry/config.json`, and `~/.agentry/credentials.json` when owner auth is needed.
   Detect the host this repo actually uses: Vercel, Netlify, Render, Railway, Fly,
   Docker/Kubernetes, GitHub Actions, or another provider.

   If your current auth/session can set host env vars or CI secrets, set them
   yourself for production and staging. If not, ask the user to paste them into
   that host's env/secrets UI. Do not print full secret values in chat.
   Do not copy raw credentials into debug, resolved-state, repo-audit, or handoff files
   while doing this; only the actual app/host/CI env store should receive
   a raw `AGENTRY_DSN`.

   Wire:
   - `AGENTRY_DSN` (`agnt_...`) in the app runtime for errors and analytics, plus in the CI/provider deploy hook for deploy ingest, not in runtime startup code.
   - `AGENTRY_URL` only when self-hosting; helpers default to `https://api.agentry.sh`.
   - `AGENTRY_PROJECT_ID` only for owner/API tooling that cannot derive it from `AGENTRY_DSN`.

   If the app's `AGENTRY_DSN` looks wrong, first call
   `POST /v1/projects/:id/dsn/verify` with the candidate value. If an owner needs
   the current value, call `GET /v1/projects/:id/dsn`. Do not call
   `POST /v1/projects/:id/dsn/rotate` unless you intend to invalidate the old
   value and update every host environment immediately.
   - `AGENTRY_API_KEY` (`agk_...`) only in server-side/admin/CI environments that call owner-side
     Agentry APIs, manage sourcemap list/blob/delete operations, manage alerts, or run automation. Sourcemap upload itself uses
     `AGENTRY_DSN` from CI/build. Never expose it through
     `NEXT_PUBLIC_`, `APP_PUBLIC_`, `VITE_`, `REACT_APP_`, or any browser bundle.
   - `AGENTRY_DEPLOY_SHA` or the provider-native commit SHA env (`GITHUB_SHA`,
     `COMMIT_REF`, `VERCEL_GIT_COMMIT_SHA`, `RENDER_GIT_COMMIT`,
     `RAILWAY_GIT_COMMIT_SHA`, etc.) for deploy attribution.

   If you save env vars in this session, redeploy, trigger one real product flow
   and one deploy event from the real deploy completion path, then re-run verify
   or check `GET /v1/projects/:project_id/event-names` and
   `GET /v1/projects/:project_id/deploys`. If you cannot write the host env
   from this session, include the exact variable names and host UI handoff; the
   minimum install is already complete when verify returned `ok:true`.

10. Feedback checkpoint
   Before the final response, scan the run for Agentry product defects:
   - API/schema/docs mismatch
   - endpoint returned a misleading shape
   - answer contracts or required telemetry guidance were wrong
   - verify false-positive or false-negative
   - install contract omitted a necessary step
   - the agent had to infer a payload, inspect source, or use a workaround because
     the canonical Agentry contract failed

   For each distinct issue, POST `/v1/feedback` with:
   - `kind: "agent_discovered_bug"`
   - `fingerprint: "agent_discovered_bug:<flow>:<surface>:<short_slug>"`
   - `message`: one concise sentence describing the product defect
   - `project_id`: current project id when available
   - `tool_name: "install_feedback_checkpoint"`
   - `agent_note`: JSON with `source: "agent_discovered_product_defect"`,
     `flow` (`install`, `verify`, `query`, or `deploy`), `surface`
     (`api`, `openapi_schema`, `docs`, `answer_contract`, `install_contract`, or
     `verify`), `expected`, `actual`, `workaround_used`, `blocked_user`,
     and any endpoint/path/contract ids

   Feedback is deduped by unresolved fingerprint, so file it aggressively. Use
   `agent_discovered_bug` for these reports; normal customer installs are
   reporting product defects, not repairing Agentry.

After the go-live checkpoint and feedback checkpoint, end the completed install
with this user-facing handoff: Basic events are set up. Ask me questions about your product, growth, revenue, reliability, or usage and I will verify whether the needed events exist, answer with evidence when they do, or wire missing telemetry when they do not.

## Endpoints used by this flow

- `GET /install.md`
- `GET /v1/openapi.json?flow=install`, `?tag=Install&include_components=false`, or `?path=...&method=...` for filtered schema lookups
- `POST /v1/auth/device`
- `POST /v1/auth/device/poll`
- `GET /v1/projects`
- `POST /v1/projects`
- `GET /v1/install/contract`
- `POST /v1/install/plan`
- `PUT /v1/projects/:project_id/signal-map`
- `PUT /v1/projects/:project_id/implementation-report`
- `POST /v1/projects/:project_id/install/verify`
- `GET /v1/projects/:project_id/verify-report`
- host/CI env settings for `AGENTRY_DSN`, `AGENTRY_URL`, optional `AGENTRY_PROJECT_ID`, optional server-only `AGENTRY_API_KEY`
- `POST /v1/feedback`

## Make future sessions recognise Agentry

Future-session adapters are optional pointers after the verified install. Fetch `/adapters`, detect ALL
available agent harnesses, and write helpful thin pointers when they fit instead of
stopping at the first client you find. Power users commonly switch between
Codex, Claude Code, Cursor, Windsurf, ChatGPT/custom GPTs, and AGENTS.md-aware
tools in the same repo.

Prefer writing `AGENTS.md` as the repo-local cross-tool pointer when this repo uses AGENTS.md or the user wants future-session hints. Then optionally install detected client-specific adapters:

- Codex: user-level skill at `${CODEX_HOME:-$HOME/.codex}/skills/agentry/SKILL.md`
  when `$CODEX_HOME` is set, `~/.codex/` exists, or the current harness is Codex.
- Claude Code: project-local skill at `.claude/skills/agentry/SKILL.md` when
  `.claude/` exists or the current harness is Claude; optionally also install
  user-global `~/.claude/skills/agentry/SKILL.md` when the user wants every
  future Claude Code session to recognise Agentry.
- Cursor: `.cursor/rules/agentry.mdc` when `.cursor/` exists.
- Windsurf: append/update `.windsurfrules` when that file exists or Windsurf
  project config is present.
- ChatGPT/custom GPTs: tell the user to import the OpenAPI Action schema at
  `https://api.agentry.sh/v1/openapi.json`; there is no repo file to write.

Before finalizing, report the harnesses you found and any adapter paths you installed or skipped.
If you find multiple user-global destinations, ask once whether to install all of
them; default to all detected harnesses unless the user narrows the scope.
Each adapter just points back at `/` + `/v1/openapi.json`, so none of them drift.

## Post-setup

Once telemetry is verified, use:

- the saved `post_setup_blueprint` as the primary handoff. Document the
  business question, primary funnel, required events/properties, cases/deploy
  context, and readiness gaps first. If a protected Agentry surface is useful,
  build the smallest app-fitting view from that same contract; `/agentry` is
  the suggested default path only when it fits the existing app.
- `suggested_next_steps` from the successful verify response as supporting
  options, not a generic menu to copy. Offer the go-live deployment checklist as
  supporting follow-up: name the detected host, required env vars, and whether
  you can set them or need user action. Copy/redeploy/trigger real data only
  when explicitly requested or immediately available. Include the open-ended
  custom interface / custom question options, and ask what to build first.
- `/agentry.md` for the lean day-to-day reference
- `/v1/docs/query` for HogQL patterns
- `/v1/query-blueprints` for deterministic analytics/cases/deploy query templates
- `/v1/docs/automation` for webhook + automation templates

Keep this bootstrap small in agent context. Pull the structured contract and
planner output when you need details.
