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

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.
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 querying, recipes, dashboards, and
   post-setup ops features.

Agentry has no SDK by design. The install generates a small helper and wires
errors + analytics + deploy tagging in one continuous pass.

## 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", "public_key" }`), 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. Runtime ingest helpers can derive this from
  `AGENTRY_DSN`; do not add `AGENTRY_PROJECT_ID` just for app telemetry.
- **project DSN (`agnt_`, runtime 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.

The app's ingest DSN (`agnt_`) is separate — it's the runtime secret your app
code uses to POST events, kept in the app's own env (e.g. `AGENTRY_DSN`).

## Agent rules

1. Treat "install Agentry" as ALL THREE signal types: errors, analytics, deploys.
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; print the approval message and stop the turn instead.
4. Let `POST /v1/install/plan` decide WHAT to instrument; 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. Present `plan_review.message_markdown` directly when it exists; do not rewrite the approval step from scratch unless you must. Do not compress away the "Questions Agentry will answer" section or collapse `questions_for_user` into one generic approval ask.
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 returns `recipes_pending_real_data`, do not call it installed. Tell the user to exercise real flows and re-run verify later.
10. After verify passes, run the go-live host env checkpoint before the final response:
    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); if your CLI/session can set host env vars or CI secrets, do it for production
    and staging. If you cannot write them, ask the user to paste the variables into that host's env UI.
    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
    so production/staging data reaches the project.
11. Before your final response, run the Agentry product-defect feedback checkpoint.
    If Agentry's API, docs, OpenAPI schema, recipes, 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. When building post-setup dashboards or internal admin routes that call
    `POST /v1/projects/:project_id/analytics/query`, use a server-side request
    timeout of at least 45 seconds. Agentry's PostHog/HogQL upstream budget is
    45 seconds; 1-15 second client aborts and quick database fallbacks around raw
    analytics tabs will kill valid slow queries and create false partial-data
    states. Do not fire a large Promise.all burst of raw analytics/query calls;
    run at most 1-2 concurrently. For an internal funnel dashboard page, keep
    AGENTRY_API_KEY server-only, use
    `GET /v1/projects/:project_id/recipes/required-events` as canonical project
    coverage after a signal map exists, and remember that
    `GET /v1/recipes/required-events` is raw catalog planning coverage that can
    be larger than the approved saved state. For property checks, call
    `GET /v1/projects/:project_id/event-property-keys?events=a,b,c`; the
    no-events form intentionally returns empty guidance. Load the primary
    funnel/summary first, then optional filters/attribution. Prefer
    `POST /v1/projects/:project_id/public-queries`, return/embed the resulting
    public-query URL, or use caching/smaller HogQL for browser-facing dashboards.

## 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:
   - map the happy-path funnel to the ideal user outcome
   - capture repo-specific `product_summary`, `metric_lens`, and `primary_outcome`
   - capture already-live analytics or business event names in `existing_live_events`
   - capture key entities and the important journey stages in `key_user_journeys`
   - inventory `ui_surfaces`, `api_surfaces`, `async_surfaces`, and `admin_surfaces` so shared request/page telemetry covers the whole product, not just the signup funnel
   - 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:
   - `required_events`, `required_event_properties`, `missing_events`
   - `event_buckets`, `happy_path_funnel`, `failure_surface_map`
   - `coverage_checklist`, `plan_review`
   - `post_setup_blueprint` for the branded `/agentry` view, query/publication plan, deployment env handoff, and automations
   - `suggested_questions_to_answer`, `future_question_prompt`, `questions_for_user`
   Recipe capability packages are starting points, not scripts to paste verbatim:
   adapt each starter prompt and event/property requirement to the saved signal map. Do not copy examples as-is.

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 Agentry will answer" / questions this install is designed to answer
   - the `/agentry` post-setup blueprint and its expected panels
   - the 3–6 month future-question prompt
   - each approval question from `questions_for_user`
   Do not compress those question sections into a single sentence; this is where the user widens or corrects the signal map before code is written.
   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, do not rebuild the plan by hand before saving it.

5. `PUT /v1/projects/:project_id/signal-map`
   After approval, persist the approved discovery map, funnel, event buckets,
   failure surface map, event-property commitments, recipe decisions, and
   `post_setup_blueprint` so future sessions and verify runs resume from the same contract.

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

8. `POST /v1/projects/:project_id/install/verify`
   Run the hard gate with the same shapes/flags used in planning, plus a fresh
   `repo_audit` built from the current approved signal map (the server cannot
   read your checkout, so the audit is your coverage proof).

Success requires:
- synthetic errors + analytics + deploys all pass
- the approved signal map exists and its required events / properties are emitting
- the implementation report exists and matches the approved plan hash
- at least one real non-synthetic event exists
- shapes are present
- applicable recipes exist
- applicable recipes are runnable, or explicitly waiting on real data

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

If verify returns `ok: true`, setup still has a required post-setup phase:
use the saved `post_setup_blueprint` to build or offer the protected
`/agentry` view, apply or hand off deployment env vars, and propose the
first app-specific automations. Do not turn recipe 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.

   Wire:
   - `AGENTRY_DSN` (`agnt_...`) in the app runtime for errors, analytics, and deploy ingest.
   - `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, upload sourcemaps, manage alerts, or run automation. Never expose it through
     `NEXT_PUBLIC_`, `VITE_`, `REACT_APP_`, or any browser bundle.
   - `AGENTRY_DEPLOY_SHA` or the provider-native commit SHA env (`VERCEL_GIT_COMMIT_SHA`,
     `RENDER_GIT_COMMIT`, `RAILWAY_GIT_COMMIT_SHA`, etc.) for deploy attribution.

   After saving env vars, redeploy, trigger one real product flow and one deploy
   event, then re-run verify or check `GET /v1/projects/:project_id/event-names`
   and `GET /v1/projects/:project_id/deploys`.

10. Feedback checkpoint
   Before the final response, scan the run for Agentry product defects:
   - API/schema/docs mismatch
   - endpoint returned a misleading shape
   - recipe catalog or recipe requirements 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`, `recipe`, `install_contract`, or
     `verify`), `expected`, `actual`, `workaround_used`, `blocked_user`,
     and any endpoint/path/recipe 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.

## 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 part of the install. Fetch `/adapters`, detect ALL
available agent harnesses, and write every applicable thin pointer 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.

Always write `AGENTS.md` by default as the repo-local cross-tool pointer. Then
install every detected client-specific adapter:

- 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 the adapters you installed.
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. Build or offer the
  protected `/agentry` folder/view with overview, primary funnel, cases, deploy
  health, and instrumentation health panels customized to this app.
- `suggested_next_steps` from the successful verify response as supporting
  options, not a generic menu to copy. Always include the go-live deployment
  checklist first: copy live Agentry values from local `.env` / `.env.local`
  into the actual host's environment variables yourself if you can; otherwise
  ask the user to paste them into that host's env UI; then redeploy and trigger
  real data. 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/recipes/catalog` for workflow + executable recipe discovery
- `/v1/recipes` for executable analytics/cases recipes
- `/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.
