From 315ee44dfc1bdcba88fc5fd2cd465f6d9debf48a Mon Sep 17 00:00:00 2001 From: HaniMoudarres Date: Mon, 30 Nov 2026 00:26:27 -0500 Subject: [PATCH] Add the Render MCP and Render skills for all tools sync-mcp.py gains oauth_client_ids so remote servers that need a pre-registered public OAuth client per tool (Render) work in Claude Code, Cursor and Codex. Docs note that vercel and render show our project only to Hani until those plans are upgraded. Co-authored-by: Cursor --- .agents/skills/add-shared-tool/SKILL.md | 5 +- .agents/skills/render-blueprints/SKILL.md | 282 ++++++ .../references/blueprints.md | 102 +++ .../references/common-mistakes.md | 107 +++ .../references/compute-plans.md | 23 + .../references/environment-variables.md | 38 + .../references/field-reference.md | 226 +++++ .../references/persistent-disks.md | 29 + .../references/preview-environments.md | 119 +++ .../references/private-networking.md | 25 + .../references/service-types.md | 37 + .../references/wiring-patterns.md | 172 ++++ .agents/skills/render-debug/SKILL.md | 249 +++++ .../render-debug/references/compute-plans.md | 23 + .../references/database-debugging.md | 299 ++++++ .../render-debug/references/deployments.md | 50 + .../references/environment-variables.md | 38 + .../render-debug/references/error-patterns.md | 859 ++++++++++++++++++ .../render-debug/references/log-analysis.md | 479 ++++++++++ .../references/metrics-debugging.md | 297 ++++++ .../references/quick-workflows.md | 297 ++++++ .../render-debug/references/render-access.md | 52 ++ .../references/troubleshooting.md | 619 +++++++++++++ .agents/skills/render-env-vars/SKILL.md | 77 ++ .../references/environment-variables.md | 38 + .../references/platform-variables.md | 17 + .../references/wiring-reference.md | 174 ++++ .agents/skills/render-monitor/SKILL.md | 314 +++++++ .../references/compute-plans.md | 23 + .../render-monitor/references/deployments.md | 50 + .../references/metrics-guide.md | 297 ++++++ .../references/render-access.md | 52 ++ .agents/skills/render-web-services/SKILL.md | 117 +++ .../references/custom-domains.md | 58 ++ .../references/deployments.md | 58 ++ .../references/health-check-patterns.md | 72 ++ .../references/persistent-disks.md | 29 + .../references/private-networking.md | 25 + .ai/mcp.servers.json | 5 + .codex/config.toml | 5 + .cursor/mcp.json | 6 + .mcp.json | 7 + AGENTS.md | 2 + README.md | 5 +- docs/ai/README.md | 51 +- docs/architecture.md | 12 +- scripts/sync-mcp.py | 26 +- skills-lock.json | 35 + 48 files changed, 5954 insertions(+), 28 deletions(-) create mode 100644 .agents/skills/render-blueprints/SKILL.md create mode 100644 .agents/skills/render-blueprints/references/blueprints.md create mode 100644 .agents/skills/render-blueprints/references/common-mistakes.md create mode 100644 .agents/skills/render-blueprints/references/compute-plans.md create mode 100644 .agents/skills/render-blueprints/references/environment-variables.md create mode 100644 .agents/skills/render-blueprints/references/field-reference.md create mode 100644 .agents/skills/render-blueprints/references/persistent-disks.md create mode 100644 .agents/skills/render-blueprints/references/preview-environments.md create mode 100644 .agents/skills/render-blueprints/references/private-networking.md create mode 100644 .agents/skills/render-blueprints/references/service-types.md create mode 100644 .agents/skills/render-blueprints/references/wiring-patterns.md create mode 100644 .agents/skills/render-debug/SKILL.md create mode 100644 .agents/skills/render-debug/references/compute-plans.md create mode 100644 .agents/skills/render-debug/references/database-debugging.md create mode 100644 .agents/skills/render-debug/references/deployments.md create mode 100644 .agents/skills/render-debug/references/environment-variables.md create mode 100644 .agents/skills/render-debug/references/error-patterns.md create mode 100644 .agents/skills/render-debug/references/log-analysis.md create mode 100644 .agents/skills/render-debug/references/metrics-debugging.md create mode 100644 .agents/skills/render-debug/references/quick-workflows.md create mode 100644 .agents/skills/render-debug/references/render-access.md create mode 100644 .agents/skills/render-debug/references/troubleshooting.md create mode 100644 .agents/skills/render-env-vars/SKILL.md create mode 100644 .agents/skills/render-env-vars/references/environment-variables.md create mode 100644 .agents/skills/render-env-vars/references/platform-variables.md create mode 100644 .agents/skills/render-env-vars/references/wiring-reference.md create mode 100644 .agents/skills/render-monitor/SKILL.md create mode 100644 .agents/skills/render-monitor/references/compute-plans.md create mode 100644 .agents/skills/render-monitor/references/deployments.md create mode 100644 .agents/skills/render-monitor/references/metrics-guide.md create mode 100644 .agents/skills/render-monitor/references/render-access.md create mode 100644 .agents/skills/render-web-services/SKILL.md create mode 100644 .agents/skills/render-web-services/references/custom-domains.md create mode 100644 .agents/skills/render-web-services/references/deployments.md create mode 100644 .agents/skills/render-web-services/references/health-check-patterns.md create mode 100644 .agents/skills/render-web-services/references/persistent-disks.md create mode 100644 .agents/skills/render-web-services/references/private-networking.md diff --git a/.agents/skills/add-shared-tool/SKILL.md b/.agents/skills/add-shared-tool/SKILL.md index 01f5c47..c6cc3b5 100644 --- a/.agents/skills/add-shared-tool/SKILL.md +++ b/.agents/skills/add-shared-tool/SKILL.md @@ -16,7 +16,10 @@ generated files by hand (`.mcp.json`, `.cursor/mcp.json`, the generated block in arguments the vendor documents (e.g. `npx -y ` becomes `"command": "npx", "args": ["-y", ""]`). Add `"wrap": true` when the command is `npx` or another shim so it also works on native Windows. - - `"type": "http"` (remote server) needs `url`. + - `"type": "http"` (remote server) needs `url`. If its OAuth has no dynamic client + registration and the vendor documents a public client ID per tool, add + `"oauth_client_ids": {"claude": "...", "cursor": "...", "codex": "..."}` (see the + `render` entry). Never add a client secret. - Never write secrets. List variable NAMES in `env_vars`; each person sets them in their own environment, and tell the user which variables to set. - To skip a tool, set `"targets"`, e.g. `["claude", "cursor"]`. diff --git a/.agents/skills/render-blueprints/SKILL.md b/.agents/skills/render-blueprints/SKILL.md new file mode 100644 index 0000000..2d7f6c6 --- /dev/null +++ b/.agents/skills/render-blueprints/SKILL.md @@ -0,0 +1,282 @@ +--- +name: render-blueprints +description: >- + Authors and validates render.yaml Blueprints for Render infrastructure. Use + when the user needs to write or edit a render.yaml, wire services together + with fromDatabase/fromService/fromGroup, set up projects and environments + for multi-service apps, configure preview environments, validate against + the schema, or fix immutable field errors. Trigger terms: render.yaml, + Blueprint, IaC, fromDatabase, fromService, envVarGroups, previews, projects, + environments. +license: MIT +compatibility: >- + Git repository on GitHub, GitLab, or Bitbucket for Blueprint sync. Render CLI + v2.7.0+ recommended for `render blueprints validate`. IDEs can validate + against the public JSON Schema URL below. +metadata: + author: Render + version: "1.0.0" + category: configuration +--- + +# Render Blueprints (render.yaml) + +Blueprints define Render infrastructure as YAML (commonly `render.yaml` at the repo root). This skill focuses on **authoring**, **wiring**, **projects/environments**, **previews**, **validation**, and **immutable fields**. Heavy detail lives under `references/`. + +Before creating or modifying a Blueprint, read `references/blueprints.md` for the current specification-fetch, validation, repository-sync, and safety workflow. + +For current compute-plan terminology, Plan IDs, and availability, use `references/compute-plans.md` instead of relying on plan catalogs embedded in examples. + +Before adding or changing a service-attached disk, read `references/persistent-disks.md` for current architectural constraints and configuration workflow. + +Before wiring private-network addresses, ports, or discovery hostnames, read `references/private-networking.md`. + +Before choosing a service type or translating its Dashboard name to Blueprint structure, read `references/service-types.md`. + +## When to Use + +Apply this skill when the user: + +- Creates or edits a `render.yaml` / Blueprint +- Wires databases, private services, or Key Value into app env vars +- Groups services with **projects** and **environments** +- Configures **preview environments** for pull requests +- Validates YAML against Render’s schema or CLI +- Asks what can or cannot change after a resource is created + +For end-to-end deploy flows and MCP/CLI operations, see **render-deploy**. For env var strategy outside Blueprint syntax, see **render-env-vars**. For Docker-specific Blueprint fields, see **render-docker**. + +## Blueprint Structure + +### Top-level keys + +| Key | Purpose | +|-----|---------| +| `services` | Web, worker, cron, private service, Key Value, static (via `web` + `runtime: static`) | +| `databases` | Managed PostgreSQL instances | +| `envVarGroups` | Reusable env var sets attached to services | +| `projects` | Optional grouping; contains `environments` and service lists | +| `previews` | Defaults for PR preview environments | + +A Blueprint may also use patterns like **ungrouped** resources vs **environment-scoped** lists, depending on whether you adopt the projects model. See `references/common-mistakes.md` for duplication and naming pitfalls. + +### Minimal example: web + PostgreSQL + +```yaml +databases: + - name: mydb + plan: basic-256mb + region: oregon + +services: + - type: web + name: api + runtime: node + region: oregon + plan: starter + buildCommand: npm ci && npm run build + startCommand: npm start + envVars: + - key: DATABASE_URL + fromDatabase: + name: mydb + property: connectionString +``` + +## Service Types + +| `type` | Role | +|--------|------| +| `web` | Public HTTP service (use `runtime: static` for static sites) | +| `pserv` | Private service (internal HTTP/TCP; not public) | +| `worker` | Long-running background process | +| `cron` | Scheduled job (`schedule` required) | +| `keyvalue` | Managed Key Value (Redis-compatible); alias **`redis`** accepted in Blueprints | + +## Runtimes + +Common `runtime` values: **`node`**, **`python`**, **`go`**, **`ruby`**, **`rust`**, **`elixir`**, **`docker`**, **`image`**, **`static`**. + +- **`docker`**: Build from `Dockerfile` (see `dockerfilePath`, `dockerContext`, `dockerCommand`). +- **`image`**: Run a prebuilt container image with `image.url` and optional `image.creds.fromRegistryCreds`. +- **`static`**: Static site; requires `staticPublishPath` and build output paths (see references). + +## Cross-Service Wiring + +Before configuring variables, secrets, secret files, or environment groups, read `references/environment-variables.md`. + +Service env vars under `envVars` can pull values from other resources instead of hardcoding secrets. Environment-group variables cannot reference services, databases, or other environment groups. + +### `fromDatabase` + +Reference a database in `databases:` by `name`. Properties include: + +- `connectionString`, `connectionPoolString`, `host`, `port`, `user`, `password`, `database` + +### `fromService` + +Reference a service by `name`. Typical properties: + +- `host`, `port`, `hostport`, `connectionString`, `envVarKey` + +Which properties are valid depends on target service type (e.g. Key Value vs `pserv`). See `references/wiring-patterns.md`. + +### `fromGroup` + +Attach shared vars from `envVarGroups` (by group `name`). + +Full patterns and combinations: `references/wiring-patterns.md`. + +## Projects and Environments + +For multi-service apps, use the **`projects`/`environments`** pattern instead of flat top-level `services`/`databases`. This groups all related resources into a single Render project, supports multiple environments (production, staging), and enables environment-scoped configuration. + +```yaml +projects: + - name: my-app + environments: + - name: production + services: + - type: web + name: api + runtime: node + plan: standard + buildCommand: npm ci && npm run build + startCommand: npm start + envVars: + - key: DATABASE_URL + fromDatabase: + name: db + property: connectionString + - key: REDIS_URL + fromService: + type: keyvalue + name: cache + property: connectionString + - key: API_SECRET + sync: false + + - type: worker + name: jobs + runtime: node + plan: starter + buildCommand: npm ci + startCommand: node worker.js + envVars: + - key: DATABASE_URL + fromDatabase: + name: db + property: connectionString + - key: REDIS_URL + fromService: + type: keyvalue + name: cache + property: connectionString + + - type: keyvalue + name: cache + plan: starter + maxmemoryPolicy: noeviction + ipAllowList: [] # Internal access only + + databases: + - name: db + plan: basic-256mb +``` + +Key rules: + +- Each environment owns its `services` and `databases` lists. +- Do not define the same resource at both the root level and inside an environment. +- `envVarGroups` can be scoped to a project environment or shared across the workspace. +- With a Pro workspace or higher, environment isolation can block cross-environment private network traffic. + +For single-service apps, flat top-level `services`/`databases` is fine. Reach for the projects pattern when you have multiple services, need staging/production separation, or want environment-scoped env groups. + +## Preview Environments + +When a preview request is underspecified, first establish the desired generation mode, retention period, preview compute plans, and whether the user expects to exclude any resources. + +Top-level `previews` controls Blueprint preview environments: + +- **`previews.generation`**: `off` (default), `manual`, or `automatic` +- **`previews.expireAfterDays`**: Auto-delete preview stacks after N days + +Do not confuse preview environments with service previews: + +- A top-level `previews.generation: automatic` creates the Blueprint's preview environment, including the resources declared by that Blueprint. +- A service-level `previews.generation` controls that service's independent service previews. It does **not** override the Blueprint preview environment or exclude that service from it. It accepts only `manual` or `automatic`; omit it to disable independent service previews. +- Use `previews.plan` and `previews.numInstances` on compute services to size their preview-environment instances. Key Value and Postgres use `previewPlan` instead. + +If a user needs a worker or another resource omitted entirely from Blueprint preview environments, explain that service-level preview generation is not an exclusion mechanism; the Blueprint or application architecture must account for that requirement. Other limitations include autoscaling behavior, `sync: false` variables, and database plan compatibility—see `references/preview-environments.md`. + +## Immutable Fields + +**CRITICAL:** Some fields cannot change after the resource is created. Edits may be rejected or require replacement resources. + +### Services + +- **`type`**: Cannot change (e.g. web → worker). +- **`runtime`**: Cannot change (e.g. node → docker). + +### Databases + +Cannot change after creation: + +- `name` (logical Blueprint/database identifier in this context) +- `databaseName` +- `user` +- `region` +- `postgresMajorVersion` + +Plan other fields (disk, HA, replicas) carefully up front; consult Render docs for fields that can scale vs require recreation. + +## Key Fields (Quick Map) + +| Area | Fields | +|------|--------| +| Plans | `plan`; compute-service `previews.plan`; Key Value/Postgres `previewPlan` | +| Build/run | `buildCommand`, `startCommand`, `preDeployCommand`, `rootDir` | +| Deploy | `autoDeployTrigger`: `commit`, `checksPass`, or `off` | +| Lifecycle | `maxShutdownDelaySeconds`: 1–300, default **30** | +| HTTP | `healthCheckPath`, `domains` | +| Storage | `disk` (`name`, `mountPath`, `sizeGB`) | +| Scale | `scaling` / `numInstances` (see references) | +| Monorepo | `buildFilter` (`paths`, `ignoredPaths`) | +| Docker | `dockerfilePath`, `dockerContext`, `dockerCommand`, `registryCredential`; prebuilt `image.url` / `image.creds` | + +Deprecated names to avoid: `env` (use `runtime`), `redis` (use `keyvalue`), `autoDeploy` (use `autoDeployTrigger`), `previewsEnabled`, and `pullRequestPreviewsEnabled`. Use the appropriate top-level or service-level `previews.generation` replacement described in `references/common-mistakes.md`. + +## References + +| Document | Contents | +|----------|----------| +| `references/blueprints.md` | Current Blueprint specification, schema, validation, repository-sync, and safety workflow | +| `references/compute-plans.md` | Current compute-plan terminology, Plan ID discovery, availability, and change behavior | +| `references/environment-variables.md` | Current environment-variable documentation, secrets, groups, platform variables, and mutation safety | +| `references/persistent-disks.md` | Service-attached disk constraints, current documentation, sizing, snapshots, and Blueprint workflow | +| `references/private-networking.md` | Private-network scope, addresses, Blueprint references, discovery, ports, and isolation | +| `references/service-types.md` | Service-type selection, execution models, and Blueprint naming | +| `references/field-reference.md` | YAML fields by service type, database, groups, projects, previews, scaling, disk, static, Key Value | +| `references/wiring-patterns.md` | `fromDatabase` / `fromService` / `fromGroup` examples and combined wiring patterns | +| `references/common-mistakes.md` | Branch + previews, `buildFilter`, replicas, duplicates, preview plans, wiring mistakes | +| `references/preview-environments.md` | `previews.generation`, expiry, `previews.plan`, `previewPlan`, disks, PR workflow | + +## Related Skills + +- **render-deploy** — Deploy flows, Blueprint planning and approval, MCP/CLI operations +- **render-env-vars** — Env var strategy, secrets, Dashboard vs Blueprint +- **render-docker** — Dockerfile-backed services and image runtime nuances + + +## Current documentation retrieval + +Whenever this skill directs you to consult current Render documentation: + +1. Retrieve the linked Markdown document directly with an available URL-fetching tool or HTTP client, such as `curl`. Do not substitute web-search summaries for the document. +2. Confirm that retrieval succeeded and returned the expected document, then read its contents. Saving a file or printing its path is not sufficient. +3. If the request fails or your tool cannot read the Markdown response, open and read the linked HTML version instead. +4. If neither version can be retrieved, disclose that the current reference is unavailable and follow any topic-specific fallback in the skill. Use bundled guidance only for stable constraints, and do not guess at changeable platform details. + +When a task requires multiple references, apply this workflow to each one and distinguish the documents you verified from those that remain unavailable. + diff --git a/.agents/skills/render-blueprints/references/blueprints.md b/.agents/skills/render-blueprints/references/blueprints.md new file mode 100644 index 0000000..032ab63 --- /dev/null +++ b/.agents/skills/render-blueprints/references/blueprints.md @@ -0,0 +1,102 @@ + +## Render Blueprints + +A Render Blueprint is a declarative YAML definition of interconnected Render services, databases, and environment groups. The file is usually named `render.yaml` and stored at the root of a Git repository, although its path can be customized when the Blueprint is created. + +Blueprint creation and sync read the file from the linked remote Git repository. Local edits are not available to Render until they are committed and pushed to that repository. + +### Author and validate + +Do not rely on remembered Blueprint fields, allowed values, defaults, or update behavior. Before creating or modifying a Blueprint, use the documentation-retrieval workflow in the root `SKILL.md` to retrieve and read the [Markdown reference](https://render.com/docs/blueprint-spec.md) or its [HTML version](https://render.com/docs/blueprint-spec). + +If neither version can be retrieved, use the current JSON Schema and Render validation where possible. Use the bundled guidance only for stable workflow and safety constraints, and do not guess at unfamiliar or potentially changed syntax. + +Read the sections relevant to every resource and field being changed. In particular, confirm required fields, service-type support, immutable fields, defaults for new resources, behavior for existing resources, and whether omitting or emptying a field preserves or removes existing configuration. Do not treat an example Blueprint as a complete specification. + +Use the public JSON Schema for editor or programmatic validation: + +```text +https://render.com/schema/render.yaml.json +``` + +When Render CLI v2.7.0 or later is available, validate the finished file: + +```bash +render blueprints validate render.yaml +``` + +Fix validation errors before presenting the Blueprint as ready to deploy. Validation does not apply, sync, or deploy the Blueprint. Schema validation checks structure; Render CLI or API validation can also catch platform-aware errors. If copied examples, the schema, and Render validation disagree, prefer the configuration accepted by current Render validation and call out the discrepancy. + +Blueprint resource names are used to associate definitions with existing resources. Before reusing or changing a name, verify that the Blueprint will manage the intended resource. Do not define the same resource in more than one location, such as both a root-level list and a project environment or `ungrouped`. + +Treat edits to an existing Blueprint as infrastructure changes, not ordinary text edits. Review the proposed diff for replacements, removals, immutable-field changes, and destructive declarative behavior before applying or recommending a sync. Never hardcode secret values in a Blueprint; consult the current environment-variable sections of the specification for supported secret mechanisms and their limitations. + +### Discover deployment capabilities + +Blueprint operations are in public alpha. Inspect the active MCP tool schemas or installed CLI help before using them; do not assume every client exposes them. The CLI introduced create, plan, approve, and update in v2.35.0 under `render ea blueprints`. Local validation remains `render blueprints validate`. + +| Operation | MCP | CLI | +|-----------|-----|-----| +| Create and plan the first sync | `create_blueprint` | `render ea blueprints create` | +| Plan an existing Blueprint | `plan_blueprint` | `render ea blueprints plan ` | +| Apply its newest planned sync | `approve_blueprint` | `render ea blueprints approve ` | +| Update settings | `update_blueprint` | `render ea blueprints update ` | +| Read settings, status, and managed resource IDs | `get_blueprint` | Inspect the current command surface; do not invent a Blueprint get command | + +Prefer available MCP tools, then a capable CLI. If neither exposes the required operation, use the Dashboard or current REST API. For exact contracts, inspect the current [MCP tool definitions](https://github.com/render-oss/render-mcp-server/blob/main/pkg/blueprint/tools.go) and [CLI reference](https://render.com/docs/cli-reference). Separate local schema/CLI/API validation from remote planning; MCP has no dedicated Blueprint validation tool. + +### Prepare the remote source and resource scope + +Confirm the workspace and reuse its `workspaceId` on MCP calls that support it. Reuse the existing Blueprint ID (`exs-...`) when updating its infrastructure. A sync ID is not a Blueprint ID. + +Before creating or planning, verify that the intended YAML revision is pushed to the configured branch and repository-relative path. Merging into the default branch is not required. Preserve unrelated checkout changes and publish only within the user's authorization. Before pushing to an existing Blueprint's branch, check whether auto-sync will apply that push immediately. + +For MCP creation, supply `repoUrl`, the intended `branch`, and `path` if different from `render.yaml`. Normalize an SCP-style remote such as `git@github.com:org/repo.git` to `https://github.com/org/repo`; the tool accepts HTTPS or `ssh://` URLs, not SCP syntax. Pass the branch separately from the URL. + +CLI creation without `--repo` uses local `origin` and the current branch. With `--repo`, it defaults to the remote's default branch; pass `--branch` to use another branch. `--path` is relative to the repository root, not the current directory. After verifying the intended workspace and push, an example is: + +```bash +render ea blueprints create --repo https://github.com/acme/app --branch release --path infra/render.yaml --auto-sync=false --output json +``` + +Choose existing-resource and auto-sync behavior deliberately: + +- `existingResources: create_new` / `--existing-resources create_new` is the default. It creates separate resources with a Blueprint-specific suffix, leaving existing resources unchanged. Repeated creation can produce unwanted duplicate infrastructure; keep the returned Blueprint ID. +- `adopt` brings matching existing resources under management and updates their configuration. Use it only when the user intends to manage those resources, after checking resource identity and ownership. Review any ownership-conflict notices before approval. +- `autoSync` / `--auto-sync` defaults to true. After first approval, later Git pushes automatically apply changes. Explain this before approval; use false when the user wants manual review of future changes. Manually requested plans always need approval, even with auto-sync enabled. + +### Interpret the plan before approving + +Creation saves the Blueprint and plans its first sync; it does not apply resource changes. Do not immediately request another plan after successful creation. Planning an existing Blueprint reads its configured remote branch/path. Wait for a pending or running sync to finish before requesting another plan. + +Read `planningOutcome`, `sync`, and `notices`. CLI JSON wraps these in `data` and includes guidance in `meta`; MCP returns the result fields directly. + +| Outcome | Next action | +|---------|-------------| +| `planned` | Review the returned proposed changes, notices, and `sync.requiredManualEnvVars`; share `sync.dashboardUrl` when present. Apply only after the user authorizes the reviewed plan. | +| `no_changes` | Report that this attempt found no infrastructure changes. Do not approve. | +| `failed` | Inspect notices/errors, fix the cause, push corrected YAML if needed, then re-plan the same Blueprint. Do not approve, even if a sync object exists. | +| Missing or unknown | Inspect the current contract and returned error/state. Do not infer success or approve. | + +Approval targets the Blueprint's newest saved sync, not a caller-specified sync ID. A failed attempt or a no-change result can leave an older plan awaiting approval. Never run approval as an unconditional next command. If another actor has planned changes since review, or the plan expired, obtain and review a fresh plan before applying. Unapproved plans expire after 24 hours under the current contract. + +If a create/update request fails after potentially saving state, inspect the Blueprint before retrying. Do not recreate it merely because planning failed. Report saved settings and planning success separately. + +### Supply manual values and apply + +Use the entries in `sync.requiredManualEnvVars` as the checklist. For MCP, supply `manualEnvVars` entries with the exact `serviceType`, `serviceName`, `key`, and user-provided `value`. Reuse values already supplied; ask only for missing ones and never invent credentials. Do not print secrets or put them in the Blueprint or repository. Values sent through MCP appear in the agent context. + +CLI create/plan writes a JSON array of those entries with empty value placeholders to the returned manual-env-vars file. Fill required values before approval: an empty placeholder is submitted as an empty string, not treated as missing. A newly planned sync replaces the generated file, or removes it if no manual values are required, so check it again after re-planning. + +Use `render ea blueprints approve --output json` for inspectable approval output, substituting the actual Blueprint ID. It reads the generated file by default and deletes it after approval. `--manual-env-vars-file ` reads a custom JSON file (not `.env`) and leaves it on disk; `--manual-env-vars-file -` reads stdin. Keep any such file outside the repository with restricted permissions and remove it when no longer needed. + +If the user wants values kept outside agent context, have them supply values directly through CLI or the approval API. Alternatively, they can approve at the returned Dashboard URL and then set values on each service's Environment page; explain that initial deployments may fail until those values are set. + +Call approve only after the user authorizes applying the reviewed plan. Reuse authorization that already covers that plan; providing values, allowing secret generation, or accepting costs alone does not authorize deployment. The call returns before the sync and service deployments finish. + +### Update settings and verify the result + +Update accepts name, branch, path, and auto-sync settings; it does not change the repository. Omitted settings are retained. Branch/path changes also request planning; name/auto-sync-only changes do not. MCP skips the update and planning if all supplied values already match. Settings take effect immediately and can remain changed even when planning fails. An MCP response with a planning-stage `error` means the settings were updated but no planning result is available. Inspect state before retrying an uncertain update. + +Use `get_blueprint` when available to read settings and managed resource IDs. Do not equate Blueprint status with workload health: `created` persists until first approval; after approval, `paused` describes disabled auto-sync even while manual syncs are possible; `in_sync` can also mean a plan awaits approval. Follow the resulting resource deployments to terminal states, inspect failures, and verify application behavior before reporting success. Share the returned Dashboard URL and distinguish planning, approval, sync completion, and workload readiness. + diff --git a/.agents/skills/render-blueprints/references/common-mistakes.md b/.agents/skills/render-blueprints/references/common-mistakes.md new file mode 100644 index 0000000..fa4d398 --- /dev/null +++ b/.agents/skills/render-blueprints/references/common-mistakes.md @@ -0,0 +1,107 @@ +# Common Blueprint Mistakes + +Symptoms, causes, and fixes for frequent `render.yaml` errors. + +## 1. Setting `branch` while using preview environments + +**Mistake:** A global or service-level `branch` is set (e.g. `main`) while PR previews are enabled. + +**Effect:** Previews are meant to build **pull request** refs. Forcing a single branch can make preview builds ignore the PR commit you intend to test, undermining PR workflows. + +**Fix:** Use default branch settings appropriate for production services; let previews use PR head refs. Avoid hardcoding production `branch` on services that must track arbitrary PRs. Validate preview behavior in the Dashboard after changes. + +--- + +## 2. `buildFilter` sync — omitting `paths` clears filters + +**Mistake:** Syncing a Blueprint that includes `buildFilter` but **omits** `paths` or `ignoredPaths` keys. + +**Effect:** Missing keys can be interpreted as “set to empty,” **replacing** existing path filters with empty lists—triggering builds on every unrelated commit or breaking intended ignore rules. + +**Fix:** Always specify the **full** desired `paths` and `ignoredPaths` arrays when using `buildFilter`. Treat filters as replace, not patch. + +--- + +## 3. `readReplicas` — empty list or name drift + +**Mistake A:** Setting `readReplicas: []` to “leave unchanged.” + +**Effect:** An **empty list destroys all read replicas**. + +**Mistake B:** Renaming replica identifiers in YAML without understanding reconcile behavior. + +**Effect:** Unmatched replicas may be **removed** and new ones **created**, causing churn or brief disconnects. + +**Fix:** Treat `readReplicas` as authoritative. Only include entries you want to exist. Prefer additive changes with care and validate in a non-production environment first. + +--- + +## 4. Deprecated fields + +| Deprecated | Use instead | +|------------|-------------| +| `env` | `runtime` | +| `redis` (service type) | `keyvalue` (alias `redis` if still accepted—prefer `keyvalue` in new files) | +| `autoDeploy` | `autoDeployTrigger` | +| Top-level `previewsEnabled: true` | Top-level `previews.generation: automatic` | +| Service-level `pullRequestPreviewsEnabled: true` | Service-level `previews.generation: automatic`; omit `generation` to disable service previews | + +**Fix:** Migrate to current keys; run schema validation against `https://render.com/schema/render.yaml.json`. + +--- + +## 5. Same resource defined in multiple places + +**Mistake:** Defining a service or database at the **root** and again under a **project environment**, or listing duplicates across environments. + +**Effect:** Confusing reconcile behavior, name collisions, or unintended duplicate infrastructure. + +**Fix:** Each logical resource should live in **exactly one** scope: root `services` / `databases` **or** a single `projects[].environments[]` block—not both. + +--- + +## 6. Using the wrong preview-plan field + +**Mistake:** Setting `previewPlan` on a compute service, setting `previews.plan` on Key Value or Postgres, or mixing flexible and legacy Postgres compute plans between `plan` and `previewPlan`. + +**Effect:** Preview deploy failures or plan validation errors. + +**Fix:** Use `previews.plan` for web, private, worker, and cron services. Use `previewPlan` for Key Value and Postgres, and keep Postgres plans in compatible instance families. + +--- + +## 7. `fromService` / `fromDatabase` to non-existent names + +**Mistake:** Typo in `name` under `fromService` / `fromDatabase`, or reference before resource is defined in scope. + +**Effect:** Validation failures or broken deploys with missing env vars. + +**Fix:** Keep a single naming table; grep for `name:` and cross-check references. Run `render blueprints validate`. + +--- + +## 8. Forgetting `ipAllowList` on Key Value + +**Mistake:** Provisioning `keyvalue` without proper network restrictions. + +**Effect:** Security exposure or service creation errors (depending on account defaults and product requirements). + +**Fix:** Always set **`ipAllowList`** to explicit CIDRs appropriate for your private services and regions. + +--- + +## 9. Hardcoding connection strings + +**Mistake:** Pasting `postgres://...` or `redis://...` into `value:`. + +**Effect:** Secrets in Git, drift across environments, rotation pain, preview breakage. + +**Fix:** Use **`fromDatabase`** and **`fromService`** with `connectionString` or discrete fields; use **`generateValue`** for app secrets. + +--- + +## Quick prevention + +1. `render blueprints validate` (CLI v2.7.0+). +2. JSON Schema in the IDE: `https://render.com/schema/render.yaml.json`. +3. Diff previews against production wiring before merging. diff --git a/.agents/skills/render-blueprints/references/compute-plans.md b/.agents/skills/render-blueprints/references/compute-plans.md new file mode 100644 index 0000000..5d0ccc1 --- /dev/null +++ b/.agents/skills/render-blueprints/references/compute-plans.md @@ -0,0 +1,23 @@ + +## Compute plans + +A compute plan determines the CPU and RAM available to each instance of a Render service. Use **compute plan**, not the former term **instance type**. Do not confuse a service's compute plan with its workspace plan, which controls account-level features and limits. + +Compute plans differ by service type: + +- Web services, private services, background workers, and cron jobs use CPU-and-memory plan IDs such as `0.5c-512mb` and `1c-2g`. +- Render Postgres has its own plan catalog and connection limits. +- Render Key Value uses memory-based plan IDs such as `256mb` and `1g`. +- Workflow tasks select a compute plan in application code; a Workflow service does not set a Blueprint `plan`. +- Static sites do not have compute plans. + +Legacy plan names such as `starter`, `standard`, and `pro` remain valid in Render tooling, including Blueprints and API requests. For new configuration, prefer the current plan ID when the selected configuration surface accepts it. Before passing a plan to an API, MCP tool, or CLI command, inspect that operation's current schema or help and use one of its accepted values; the compute-plan reference describes the product catalog, not every tool version's input contract. Do not rename an existing legacy plan merely for consistency unless the user asks for that change. + +Do not rely on a memorized plan catalog. When a task depends on current plan IDs, specifications, defaults, availability, or pricing, fetch the canonical compute-plan reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/compute-plans.md) or its [HTML version](https://render.com/docs/compute-plans). + +Read the section for the relevant service type. If the document cannot be fetched, do not guess at current plan details. Preserve an existing valid plan where possible, or explain that the plan must be confirmed in the Render Dashboard or current documentation. + +When estimating capacity or cost, remember that every instance of a scaled service uses the selected compute plan and is billed accordingly. Changing the compute plan for Render Postgres, Render Key Value, or a service with an attached persistent disk requires brief downtime; other services normally apply the change with a zero-downtime deploy. + diff --git a/.agents/skills/render-blueprints/references/environment-variables.md b/.agents/skills/render-blueprints/references/environment-variables.md new file mode 100644 index 0000000..e9de03c --- /dev/null +++ b/.agents/skills/render-blueprints/references/environment-variables.md @@ -0,0 +1,38 @@ + +## Environment variables and secrets + +Render environment-variable values are strings. Applications must explicitly parse values that represent booleans, numbers, lists, or structured data; for example, the string `"false"` is truthy in many languages. + +Environment variables can be managed through the Render Dashboard, Blueprints, environment groups, and supported API, MCP, or CLI operations. Before changing a service, determine which mechanism is intended to be the source of truth. Do not make parallel Dashboard and infrastructure-as-code edits without explaining how future syncs or deploys will reconcile them. + +Never commit secret values to application source, `render.yaml`, checked-in `.env` files, fixtures, examples, or logs. Keep local secret-bearing `.env` files out of version control. Do not print or repeat secret values returned by the user, Render, or another provider. Use Render's supported secret mechanisms or an external secret manager appropriate to the user's workflow. + +Before configuring environment variables, secret files, or environment groups, fetch the current Render configuration reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/configure-environment-variables.md) or its [HTML version](https://render.com/docs/configure-environment-variables). + +Read the sections relevant to the configuration surface being used. Dashboard save options can rebuild and deploy, deploy the existing build, or save without deploying; do not assume a changed value is active until the applicable deploy occurs. + +For Blueprint-managed variables, also consult the current Blueprint YAML reference before writing syntax or predicting update behavior. In particular: + +- Use literal `value` entries only for non-sensitive configuration. +- `generateValue: true` creates a platform-generated secret when the variable does not already exist. +- `sync: false` prompts for a value only during initial Blueprint creation. It is ignored for existing services during later Blueprint updates, is not included in preview environments, and is not valid in environment groups. +- Use current `fromDatabase`, `fromService`, and `fromGroup` syntax instead of hardcoding connection strings or copying shared values. + +Blueprint syncs preserve existing service environment variables that are omitted from the Blueprint; omission does not delete them. Values defined with `fromDatabase` or `fromService` refresh on each Blueprint sync, not immediately when the referenced property or variable changes. + +Environment groups provide shared variables and secret files to linked services. A variable defined directly on a service takes precedence over the same key from a linked group. Precedence between multiple linked groups with the same key is not guaranteed; avoid collisions instead of depending on group creation order. Respect project-environment scoping when linking groups to services. + +Use secret files for credentials or configuration that must be read from the filesystem rather than an environment variable. Confirm current size and runtime-path rules in the fetched reference. Treat secret-file contents with the same precautions as other credentials. + +Render also injects documented default environment variables. Do not maintain a memorized catalog. Fetch the current default-variable reference when a task depends on a variable's name, availability, build/runtime scope, or semantics: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/environment-variables.md) or its [HTML version](https://render.com/docs/environment-variables). + +Depend only on documented platform variables. Other `RENDER_*` variables are internal and can change without notice. + +Treat environment-variable changes as service configuration mutations. Confirm the target workspace and service, inspect the existing keys without exposing their values, and preserve variables outside the user's requested scope. Before using an API, MCP, or CLI operation, check whether it patches individual keys or replaces the complete collection. After the applicable deploy, verify that required keys are present and that the service starts successfully without logging secret values. + +If the current references or live configuration cannot be inspected, do not guess at secret behavior, precedence, or replacement semantics. Preserve existing configuration where possible and explain what must be confirmed before making the change. + diff --git a/.agents/skills/render-blueprints/references/field-reference.md b/.agents/skills/render-blueprints/references/field-reference.md new file mode 100644 index 0000000..f40eb99 --- /dev/null +++ b/.agents/skills/render-blueprints/references/field-reference.md @@ -0,0 +1,226 @@ +# Render Blueprint YAML Field Reference + +Authoritative detail for `render.yaml` fields. Pair with `wiring-patterns.md`, `common-mistakes.md`, and `preview-environments.md`. + +## Conventions + +- **`name`**: Stable identifier for the resource within the Blueprint; used by `fromService`, `fromDatabase`, and the Dashboard. +- **Required vs optional** vary by `type` and `runtime`; validate with the JSON Schema (`https://render.com/schema/render.yaml.json`) and `render blueprints validate`. + +--- + +## Common service fields (most types) + +Applies broadly to `web`, `pserv`, `worker`, `cron`, and often `keyvalue` where relevant. + +| Field | Notes | +|-------|--------| +| `name` | Unique among services in scope. | +| `type` | `web`, `pserv`, `worker`, `cron`, `keyvalue` (alias `redis`). **Immutable after create.** | +| `runtime` | `node`, `python`, `go`, `ruby`, `rust`, `elixir`, `docker`, `image`, `static`. **Immutable after create.** | +| `region` | Deploy region. | +| `plan` | Instance/plan slug. | +| `branch` | Git branch to deploy. | +| `rootDir` | Subdirectory for repo context. | +| `buildCommand` | Build step(s). | +| `startCommand` | Process to run (not used the same way for `cron`—see below). | +| `preDeployCommand` | Command before deploy rollout. | +| `autoDeployTrigger` | `commit`, `checksPass`, or `off`. | +| `maxShutdownDelaySeconds` | 1–300; default **30**. | +| `healthCheckPath` | HTTP path for health checks (web services only). | +| `domains` | Custom domains list. | +| `envVars` | List of env var objects (see [Env vars patterns](#env-vars-patterns)). | +| `buildFilter` | Limit builds to path changes (see [buildFilter](#buildfilter)). | +| `disk` | Persistent disk attachment (see [disk](#disk)). | +| `scaling` | Autoscaling settings (see [scaling](#scaling)). | +| `numInstances` | Manual instance count; interacts with `scaling`. | +| `registryCredential` | For private base images in a `runtime: docker` build. | +| `image` | For `runtime: image`: `url` plus optional `creds.fromRegistryCreds`. | +| `dockerfilePath` | Path to Dockerfile (`docker` runtime). | +| `dockerContext` | Docker build context path. | +| `dockerCommand` | Override container command. | +| `previews` | Mixed preview settings: `generation` configures independent service previews; `plan` and `numInstances` configure the service in preview environments. | + +**Cron-specific** + +| Field | Notes | +|-------|--------| +| `schedule` | Cron expression. | +| `buildCommand` / `startCommand` | Build + command invoked on schedule. | + +**Key Value (`keyvalue` / `redis`)** + +| Field | Notes | +|-------|--------| +| `maxmemoryPolicy` | Eviction policy for Key Value. | +| `ipAllowList` | **Typically required** for access control; mistakes around this are common. | + +**Private service (`pserv`)** + +| Field | Notes | +|-------|--------| +| (common fields) | Internal hostname/port wiring via `fromService` for consumers. | + +**Web + `runtime: static` (static sites)** + +| Field | Notes | +|-------|--------| +| `staticPublishPath` | Directory of built assets to publish. | +| `headers` | Custom response headers (rules/objects per schema). | +| `routes` | SPA / routing rules (e.g. fallback to `index.html`). | + +--- + +## Database fields (`databases`) + +| Field | Notes | +|-------|--------| +| `name` | Blueprint identifier; **immutable** after creation. | +| `plan` | Database plan. | +| `previewPlan` | Plan for preview DB instances. | +| `previewDiskSizeGB` | Disk sizing for preview databases. | +| `postgresMajorVersion` | Major version; **immutable**. | +| `databaseName` | **Immutable.** | +| `user` | **Immutable.** | +| `region` | **Immutable.** | +| `diskSizeGB` | Storage size. | +| `storageAutoscalingEnabled` | Autoscale storage when supported. | +| `readReplicas` | Replica list; **empty list removes all replicas** (destructive). | +| `highAvailability` | HA enabled/disabled per plan support. | +| `ipAllowList` | CIDR restrictions where applicable. | + +--- + +## envVarGroups + +| Field | Notes | +|-------|--------| +| `name` | Group identifier for `fromGroup`. | +| `envVars` | Variables may use `value` or `generateValue`; they cannot reference services, databases, or other groups. | + +**Constraints:** `sync: false`, `fromDatabase`, `fromService`, and `fromGroup` are **not valid** in env var groups. + +--- + +## projects / environments + +Projects group one or more **environments** (e.g. production, staging) under a single Render project. Use this pattern for multi-service apps. + +### Project fields + +| Field | Notes | +|-------|--------| +| `name` | Project name (appears in Dashboard). | +| `environments` | List of environment blocks. | + +### Environment fields + +Each environment is a self-contained set of resources: + +| Field | Notes | +|-------|--------| +| `name` | Environment key (e.g. `production`, `staging`). | +| `services` | Services belonging to this environment (same schema as top-level `services`). | +| `databases` | Databases belonging to this environment (same schema as top-level `databases`). | +| `envVarGroups` | Env var groups scoped to this environment. | + +### Structural rules + +- **No duplication:** Define each resource in **one** place: either at the root level **or** inside a single environment. Never both. +- **Cross-environment wiring:** `fromDatabase` and `fromService` resolve within the same environment. Referencing resources across environments is not supported in Blueprint YAML. +- **Environment isolation:** With a Pro workspace or higher, environments can be isolated so services in different environments cannot reach each other over the private network. +- **When to use projects:** Multiple services that belong together, staging/production parity, environment-scoped env groups. Single-service apps can use flat top-level lists instead. + +--- + +## previews (top-level) + +| Field | Notes | +|-------|--------| +| `generation` | `off` (default), `manual`, or `automatic`. | +| `expireAfterDays` | Delete preview environments after N days. | + +Top-level `previews.generation` controls preview environments. Service-level `previews.generation` instead controls independent service previews, accepts only `manual` or `automatic`, and does not override the top-level setting. Omit it to disable service previews. + +--- + +## Env vars patterns + +Each entry is typically keyed by `key` plus **one** of: + +| Pattern | Purpose | +|---------|---------| +| `value` | Inline literal. | +| `generateValue` | Render generates a random secret. | +| `sync` | `false` = do not sync from Blueprint after initial setup (secrets); see limitations in preview/group docs. | +| `fromDatabase` | Pull DB host, port, user, password, database, `connectionString`, or `connectionPoolString`. | +| `fromService` | Pull host/port/connection info from another service. | +| `fromGroup` | Import vars from an `envVarGroup` by name. | + +--- + +## scaling + +| Field | Notes | +|-------|--------| +| `numInstances` | Fixed instance count when not using autoscaling (or as baseline depending on config). | +| `scaling.minInstances` | Floor for autoscaled services. | +| `scaling.maxInstances` | Ceiling for autoscaled services. | +| `scaling.targetCPUPercent` | CPU target for autoscaling. | +| `scaling.targetMemoryPercent` | Memory target for autoscaling. | + +**Previews:** Autoscaling is disabled; previews use **minInstances** behavior (see `preview-environments.md`). + +--- + +## disk + +Before configuring an attached service disk, read [persistent-disks.md](persistent-disks.md) for its architectural constraints and confirm the current schema in the Blueprint specification. + +| Field | Notes | +|-------|-------| +| `name` | Disk identifier. | +| `mountPath` | Absolute mount path in the instance filesystem. | +| `sizeGB` | Provisioned disk capacity in GB. | + +--- + +## buildFilter + +Limit which Git changes trigger builds: + +| Field | Notes | +|-------|--------| +| `paths` | Include paths (glob / path rules per schema). | +| `ignoredPaths` | Excluded paths. | + +**Sync behavior:** Omitting `paths` or `ignoredPaths` when syncing can **replace** existing filters with empty lists—always send the full desired filter set. + +--- + +## static site fields (`type: web`, `runtime: static`) + +| Field | Notes | +|-------|--------| +| `buildCommand` | Build static assets. | +| `staticPublishPath` | Output directory for publishing. | +| `headers` | Header rules for responses. | +| `routes` | URL routing / SPA fallback configuration. | +| `buildFilter` | Path-based build triggers. | + +--- + +## Key Value fields (`type: keyvalue`) + +| Field | Notes | +|-------|--------| +| `name`, `region`, `plan` | Standard resource fields. | +| `previewPlan` | Plan for preview Key Value instances. | +| `maxmemoryPolicy` | Eviction policy string. | +| `ipAllowList` | **Required** for proper network restriction in typical setups—do not omit unless you explicitly accept open access per product rules. | + +--- + +## Schema + +Use `https://render.com/schema/render.yaml.json` as the source of truth for required fields and enum values; Render may add fields over time. diff --git a/.agents/skills/render-blueprints/references/persistent-disks.md b/.agents/skills/render-blueprints/references/persistent-disks.md new file mode 100644 index 0000000..3ba9242 --- /dev/null +++ b/.agents/skills/render-blueprints/references/persistent-disks.md @@ -0,0 +1,29 @@ + +## Persistent disks + +Use this guidance only for service-attached persistent disks and for architecture or configuration decisions directly affected by them. Do not apply it to Render Postgres or Key Value storage, object storage, build caches, or ordinary ephemeral filesystem tasks. + +By default, a Render service's filesystem is ephemeral. Files created or changed at runtime are lost when the service is redeployed or restarted. Use a persistent disk only when a supported service must retain local filesystem data across those events. + +Before designing, configuring, or troubleshooting a persistent disk, fetch the current documentation: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/disks.md) or its [HTML version](https://render.com/docs/disks). + +Read the relevant sections before relying on details that can change, including supported service types, size limits and pricing, mount-path restrictions, snapshot cadence and retention, transfer methods, and current scaling or deployment limitations. If the document cannot be fetched, do not guess those details from memory. + +A persistent disk belongs to one service and is mounted at one absolute path. Only files written under that mount path persist; the rest of the service filesystem remains ephemeral. Make sure the application writes every intended durable file beneath the configured mount path. A disk is not shared storage, and another service cannot access it. + +Under the documented generally available behavior, a disk-backed service runs as a single instance and cannot use autoscaling or zero-downtime deploys. During a deploy, Render stops the existing instance before starting its replacement, so expect a short interruption. If the workload needs horizontal scaling, shared state, or stronger availability, use an external or managed datastore instead of a service-attached disk. + +The disk is available only to the running service. Builds, pre-deploy commands, and one-off jobs run on separate compute and cannot access it. Do not design a build step, pre-deploy command, or one-off job that depends on files stored on the mounted disk. + +The documented supported service types are paid web services, private services, and background workers. For other workload types, use an appropriate external datastore or reconsider the service architecture rather than assuming a disk can be attached. + +Disk capacity can be increased but not decreased. Confirm current limits and pricing in the fetched documentation, and choose capacity using observed usage plus reasonable headroom. + +Treat attaching, resizing, or restoring a disk as a stateful mutation. After attaching, verify that the service deploys successfully and that reads and writes use the mounted path. + +Snapshots are a disaster-recovery mechanism, not a substitute for application-consistent database backups. A snapshot restore replaces the entire disk; it cannot restore individual files, and it discards changes made after that snapshot. Do not use a disk snapshot to recover a custom database, because a filesystem-level snapshot can restore the database into an inconsistent or corrupted state. Use the database engine's native backup and restore tools instead. Check the current documentation before promising a particular snapshot schedule, retention period, or restore procedure. + +Mount paths must be absolute and must satisfy Render's current restrictions. Fetch the documentation instead of reproducing its forbidden-path list or runtime-specific path suggestions from memory. When declaring a disk in a Blueprint, also fetch the current Blueprint specification and follow its disk schema rather than relying on remembered syntax. + diff --git a/.agents/skills/render-blueprints/references/preview-environments.md b/.agents/skills/render-blueprints/references/preview-environments.md new file mode 100644 index 0000000..6b11d0c --- /dev/null +++ b/.agents/skills/render-blueprints/references/preview-environments.md @@ -0,0 +1,119 @@ +# Preview Environments + +Pull request (PR) previews spin up temporary stacks from your Blueprint so each PR can be tested in isolation. This document summarizes Blueprint knobs and behavioral constraints. + +## Top-level `previews` + +```yaml +previews: + generation: off # default + expireAfterDays: 3 +``` + +### `previews.generation` + +| Value | Behavior | +|-------|----------| +| `off` | No automatic preview creation from PRs (default). | +| `manual` | Previews are created on demand (Dashboard/workflow action—exact UX may vary by integration). | +| `automatic` | Previews are created for eligible PRs per Render’s Git integration rules. | + +### `previews.expireAfterDays` + +- Positive integer: automatically **delete** preview environments after **N** days to control cost and clutter. +- Omit or set per product/docs for “no expiry” behavior. + +--- + +## Service previews vs. preview environments + +Service-level `previews.generation` configures a service's independent pull request previews. It does **not** override the Blueprint's top-level preview-environment generation mode. + +```yaml +services: + - type: web + name: api + runtime: node + # ... + previews: + generation: manual +``` + +The only supported service-level generation values are `manual` and `automatic`. Omit `previews.generation` to disable service previews. Do not set it to `off`, and do not use it to try to exclude a resource from preview environments. + +--- + +## Preview compute plans + +- For web services, private services, background workers, and cron jobs, set **`previews.plan`**. Despite sharing an object with the service-preview generation field, this field controls the compute plan used in preview environments. +- Set **`previews.numInstances`** to control the service's instance count in preview environments. +- For Key Value and Postgres instances, set **`previewPlan`**. +- For Postgres, `plan` and `previewPlan` must both use flexible compute plans or both use legacy compute plans. +- If no preview compute plan is specified, Render uses the base resource's compute plan. + +Use `compute-plans.md` for current Plan IDs and availability rather than copying plan catalogs into this preview-specific reference. + +```yaml +services: + - type: web + name: api + plan: standard + previews: + plan: starter + - type: keyvalue + name: cache + plan: standard + previewPlan: starter + ipAllowList: [] +databases: + - name: db + plan: pro-4gb + previewPlan: basic-1gb +``` + +--- + +## Database previews: `previewDiskSizeGB` + +- Databases created for previews may use **`previewDiskSizeGB`** (and related preview fields per schema) so preview DB storage is smaller/cheaper than production. +- Keep disk large enough for migrations and seed data used in CI. + +--- + +## `sync: false` env vars in previews + +- Environment variables with **`sync: false`** are **excluded** from automatic preview configuration. +- **Users must set these manually** on preview services (Dashboard or automation) or the app may fail at runtime (missing secrets). + +**Mitigation:** For previews, prefer secrets that can be generated per-preview, or use non-secret placeholders, or inject via your CI pipeline into preview env as allowed by your security model. + +--- + +## Autoscaling in previews + +- **Autoscaling is disabled** in preview environments. +- Instance counts follow **minimum instance** behavior (effectively pinned to the floor—commonly `scaling.minInstances` when autoscaling exists, or a single instance). +- Do not rely on preview traffic to test autoscale rules; test scaling in staging/production-like environments. + +--- + +## PR workflow — how previews map to Git + +1. A **pull request** is opened against the tracked branch (e.g. `main`). +2. Render uses the **PR head commit** (and Blueprint at that revision) to propose or create a preview environment according to the top-level `previews.generation` setting. +3. **Build filters** and **branch** settings on services still matter: misconfigured `branch` can break the expectation that previews track the PR (see `common-mistakes.md`). +4. When the PR closes or merges, previews are typically torn down per product rules; **`expireAfterDays`** enforces a maximum lifetime regardless. + +--- + +## Checklist + +- [ ] `previews.generation` matches team workflow (`off` / `manual` / `automatic`). +- [ ] `expireAfterDays` set if org needs automatic cleanup. +- [ ] Compute services use `previews.plan`; Key Value and Postgres use `previewPlan`. +- [ ] Postgres `previewPlan` is compatible with the primary `plan` family. +- [ ] `previewDiskSizeGB` (if used) sufficient for migrations. +- [ ] No reliance on `sync: false` secrets without a preview secret strategy. +- [ ] Any service-level `previews.generation` setting is intentional and treated separately from preview-environment generation. + +Validate with `render blueprints validate` and `https://render.com/schema/render.yaml.json`. diff --git a/.agents/skills/render-blueprints/references/private-networking.md b/.agents/skills/render-blueprints/references/private-networking.md new file mode 100644 index 0000000..d68d6be --- /dev/null +++ b/.agents/skills/render-blueprints/references/private-networking.md @@ -0,0 +1,25 @@ + +## Private networking + +Render services can communicate over a private network without traversing the public internet. Private-network peers must belong to the same workspace and run in the same region. An isolated project environment can additionally block traffic both to and from resources outside that environment, so workspace and region matching alone do not guarantee connectivity. + +Before designing, configuring, or troubleshooting private-network communication, fetch the current Render private-network reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/private-network.md) or its [HTML version](https://render.com/docs/private-network). + +Read the relevant sections. Confirm current service-type capabilities, port restrictions, environment-isolation behavior, discovery-hostname guidance, and plan requirements instead of relying on a memorized catalog. + +Web services and private services have internal hostnames and can receive private-network traffic. A private service must bind at least one port; use a background worker instead when a workload does not need to accept inbound connections. Render Postgres and Key Value instances provide internal connection URLs. Workflows, background workers, and cron jobs can initiate private-network connections but do not have an internal address for receiving them. Static sites are not on the private network. Free web services can initiate private-network connections but cannot receive them. + +Prefer the internal address or URL shown under **Connect > Internal** in the Render Dashboard. Include the protocol when the client or server requires one; an address such as `service:10000` does not by itself establish whether to use HTTP, HTTPS, or another protocol. A process that receives traffic must listen on the intended port and on an interface reachable outside its own container, such as `0.0.0.0`, rather than only on loopback. + +For Blueprint-managed connections, fetch the current Blueprint specification and use supported service or database references instead of copying a generated hostname, port, credential, or connection string. Web and private services currently expose `host`, `port`, and `hostport` properties. A Blueprint can obtain another service's discovery hostname by referencing that service's `RENDER_DISCOVERY_SERVICE` environment variable with `fromService.envVarKey`; the discovery hostname is not a service property. The fetched specification is authoritative for the syntax and supported references. + +A service can expose at most 75 ports on the private network. Ports `18012`, `18013`, and `19099` are unavailable for private-network communication. Port `10000` is not generally blocked: for a web service, private traffic to port `10000` routes to its primary HTTP server even when that server binds to another port. In that case, both port `10000` and the actual primary HTTP port route to the same server. + +Use a service's normal internal hostname for ordinary service-to-service traffic. For advanced per-instance communication, each web or private service has a discovery hostname, conventionally formed by appending `-discovery` to its internal hostname, that resolves to all active instance IP addresses. A service receives its own discovery hostname in `RENDER_DISCOVERY_SERVICE`. Use DNS APIs that honor the system resolver configuration, and do not persist resolved instance IPs because they can change between deploys. Prefer hostname-based communication unless per-instance addressing or custom load balancing is specifically required. + +When a private-network connection fails, verify the workspace, region, project-environment isolation settings, whether the destination service type accepts inbound traffic, the internal hostname or URL, protocol, port, listening interface, current deploy health, and DNS resolution. Do not substitute a public URL or expose a private service merely to bypass a private-network configuration problem. + +AWS PrivateLink is a separate Pro-or-higher feature for connecting a Render private network to compatible AWS-hosted systems. Fetch its current documentation before proposing or configuring it; do not treat ordinary Render service-to-service networking and PrivateLink as interchangeable. + diff --git a/.agents/skills/render-blueprints/references/service-types.md b/.agents/skills/render-blueprints/references/service-types.md new file mode 100644 index 0000000..a0a3786 --- /dev/null +++ b/.agents/skills/render-blueprints/references/service-types.md @@ -0,0 +1,37 @@ + +## Render service types + +Use this guidance when selecting or comparing Render service types, or when a task's architecture depends on the distinction between them. A task that is already unambiguously scoped to one service type does not need this entire overview. + +On Render, a service represents code deployed for a particular execution model. Render runs that service on one or more instances, and the service's compute plan determines the CPU and memory available to each instance. + +Before choosing a service type, fetch the current service-types reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/service-types.md) or its [HTML version](https://render.com/docs/service-types). + +If neither version can be retrieved, use the bundled overview below only for basic service-type selection. State that current platform details could not be verified, and do not guess about changeable capabilities such as supported runtimes, plans, scaling, networking, disks, health checks, deployment behavior, availability, or limits. + +Render provides six public service types for running code: + +- **Web service:** A continuously running server that receives public HTTP traffic and also has an internal hostname for private-network traffic. Use it for dynamic websites, APIs, and other internet-facing server applications. +- **Static site:** Built HTML, CSS, JavaScript, and other static assets served publicly from Render's global CDN. Use it only when the deployed application does not require server-side runtime logic. +- **Private service:** A continuously running server that receives traffic only over Render's private network. Use it for internal HTTP, TCP, gRPC, or other server processes that need an internal hostname but no public URL. +- **Background worker:** A continuously running process that does not receive incoming traffic or expose a public or internal hostname. Use it for queue consumers and other processes that pull or poll for work. +- **Cron job:** A command or process that starts on a schedule, performs a bounded unit of work, and exits. Use it for straightforward recurring tasks rather than an always-running process. +- **Workflow:** A collection of on-demand tasks executed across distributed compute, with Render handling task queuing, orchestration, and provisioning. Use it when the workload benefits from independently invoked tasks, retries, composition, or parallel execution instead of a continuously running worker process. + +Choose based on how the code executes and receives work: + +- Public incoming traffic that requires server-side logic belongs on a web service. Public static assets with no runtime server belong on a static site. +- An application that needs both public and private ingress remains a web service; use its internal hostname for traffic from other Render services. +- A process that receives private-network requests belongs on a private service. A process that only initiates connections and pulls work belongs on a background worker. +- A simple scheduled command that exits belongs on a cron job. An always-running queue consumer belongs on a background worker. On-demand or distributed tasks for which Render should manage queuing and per-run compute belong in a workflow. + +Cron jobs and Workflows use invocation-based execution models. The ordinary instance-count and autoscaling model used by continuously running services does not apply to them. + +Render Postgres and Render Key Value are fully managed datastores, not general-purpose compute service types for running application code. Use Render Postgres for relational data and Render Key Value for use cases such as shared caching and job queues. An attached persistent disk is a storage feature of certain compute services, not a service type of its own. + +After selecting a type, fetch the product article linked from the service-types reference before relying on details such as supported runtimes and sources, plans, scaling, networking, disks, health checks, deployment behavior, scheduling semantics, availability, or limits. These capabilities are not uniform across service types and can change independently. + +Human-facing service names do not always map directly to configuration identifiers or structure. When creating or editing a Blueprint, fetch the current Blueprint specification and use its service-type schema instead of inferring fields or values from this overview. In particular, do not assume that every Dashboard service type has a same-named Blueprint `type` or that managed datastores are declared like compute services. + diff --git a/.agents/skills/render-blueprints/references/wiring-patterns.md b/.agents/skills/render-blueprints/references/wiring-patterns.md new file mode 100644 index 0000000..92ba56b --- /dev/null +++ b/.agents/skills/render-blueprints/references/wiring-patterns.md @@ -0,0 +1,172 @@ +# Cross-Service Wiring Patterns + +Read [environment-variables.md](environment-variables.md) first for current syntax discovery, secret handling, precedence, and mutation safety. When wiring an internal service address or discovery hostname, also read [private-networking.md](private-networking.md). This reference retains cross-resource wiring examples for `render.yaml`. + +--- + +## fromDatabase + +Reference a Managed Postgres database property: + +```yaml +envVars: + - key: DATABASE_URL + fromDatabase: + name: my-postgres + property: connectionString +``` + +Available properties: + +| Property | Value | +|----------|-------| +| `connectionString` | Full `postgres://` URL (most common) | +| `connectionPoolString` | Managed PgBouncer URL when connection pooling is enabled | +| `host` | Database hostname | +| `port` | Database port | +| `user` | Database user | +| `password` | Database password | +| `database` | Database name | + +The `name` must match a database defined in the `databases` section of the same Blueprint, or an existing database in the workspace. + +--- + +## fromService (Key Value) + +Reference a Key Value (Redis-compatible) instance: + +```yaml +envVars: + - key: REDIS_URL + fromService: + name: my-redis + type: keyvalue + property: connectionString +``` + +Available properties: + +| Property | Value | +|----------|-------| +| `connectionString` | Full `redis://` URL | +| `host` | Internal hostname | +| `port` | Port number | + +--- + +## fromService (Private Service or Web Service) + +Reference another service's internal address or environment variable: + +```yaml +envVars: + # Get internal hostname + - key: AUTH_SERVICE_HOST + fromService: + name: auth-service + type: pserv + property: host + + # Get host:port + - key: AUTH_SERVICE_URL + fromService: + name: auth-service + type: pserv + property: hostport + + # Copy an env var from another service + - key: SHARED_SECRET + fromService: + name: auth-service + type: pserv + envVarKey: API_SECRET +``` + +Available properties for `pserv` and `web`: + +| Property | Value | +|----------|-------| +| `host` | Internal hostname | +| `port` | Listening port | +| `hostport` | `host:port` combined | + +Use `envVarKey` to copy a specific environment variable value from the other service. + +--- + +## fromGroup + +Link an entire environment group: + +```yaml +envVars: + - fromGroup: shared-secrets +``` + +This adds all variables from the named group to the service. The group must exist in the workspace or be defined in `envVarGroups`. + +--- + +## Combined Example + +A web service wired to Postgres, Key Value, and a private service: + +```yaml +services: + - type: web + name: api + runtime: node + plan: starter + buildCommand: npm ci + startCommand: npm start + envVars: + - key: DATABASE_URL + fromDatabase: + name: db + property: connectionString + - key: REDIS_URL + fromService: + name: cache + type: keyvalue + property: connectionString + - key: AUTH_HOST + fromService: + name: auth + type: pserv + property: hostport + - key: JWT_SECRET + generateValue: true + - key: STRIPE_KEY + sync: false + - fromGroup: shared-config + + - type: pserv + name: auth + runtime: node + plan: starter + buildCommand: npm ci + startCommand: npm start + + - type: keyvalue + name: cache + plan: starter + maxmemoryPolicy: allkeys-lru + ipAllowList: [] # Internal access only + +databases: + - name: db + plan: basic-256mb + +envVarGroups: + - name: shared-config + envVars: + - key: LOG_LEVEL + value: info +``` + +--- + +## Edge Cases + +- **fromService/fromDatabase can reference services outside the Blueprint** but the referenced service must already exist in the workspace. diff --git a/.agents/skills/render-debug/SKILL.md b/.agents/skills/render-debug/SKILL.md new file mode 100644 index 0000000..8bf9788 --- /dev/null +++ b/.agents/skills/render-debug/SKILL.md @@ -0,0 +1,249 @@ +--- +name: render-debug +description: Debug failed Render deployments by analyzing logs, metrics, and database state. Identifies errors (missing env vars, port binding, OOM, etc.) and suggests fixes. Use when deployments fail, services won't start, or users mention errors, logs, or debugging. +license: MIT +compatibility: Requires Render MCP tools or CLI +metadata: + author: Render + version: "1.1.0" + category: debugging +--- + +# Debug Render Deployments + +Analyze deployment failures using logs, metrics, and database queries. Identify root causes and apply fixes. + +## When to Use This Skill + +Activate this skill when: +- Deployment fails on Render +- Service won't start or keeps crashing +- User mentions errors, logs, or debugging +- Health checks are timing out +- Application errors in production +- Performance issues (slow responses) +- Database connection problems + +## Render Access + +Before reading logs, metrics, or database state, follow `references/render-access.md` to establish access and verify the intended workspace. Prefer MCP when available; the CLI can provide logs and deploy status, while metrics and structured database queries require MCP. + +--- + +## Debugging Workflow + +When the failure involves configuration or secrets, read `references/environment-variables.md` before inspecting or changing service variables. +When the failure involves deploy state, rollout, health checks, restart, rollback, or shutdown, read `references/deployments.md` before diagnosing it. + +### Step 1: Identify Failed Service + +``` +list_services() +``` + +If MCP isn't configured, ask whether to set it up (preferred) or continue with CLI. Then proceed. + +Look for services with failed status. Get details: + +``` +get_service(serviceId: "") +``` + +### Step 2: Retrieve Logs + +**Build/Deploy Logs (most failures):** +``` +list_logs(resource: [""], type: ["build"], limit: 200) +``` + +**Runtime Error Logs:** +``` +list_logs(resource: [""], level: ["error"], limit: 100) +``` + +**Search for Specific Errors:** +``` +list_logs(resource: [""], text: ["KeyError", "ECONNREFUSED"], limit: 50) +``` + +**HTTP Error Logs:** +``` +list_logs(resource: [""], statusCode: ["500", "502", "503"], limit: 50) +``` + +### Step 3: Analyze Error Patterns + +Match log errors against known patterns: + +| Error | Log Pattern | Common Fix | +|-------|-------------|------------| +| **MISSING_ENV_VAR** | `KeyError`, `not defined` | Add to render.yaml or `update_environment_variables` | +| **PORT_BINDING** | `EADDRINUSE` | Use `0.0.0.0:$PORT` | +| **MISSING_DEPENDENCY** | `Cannot find module` | Add to package.json/requirements.txt | +| **DATABASE_CONNECTION** | `ECONNREFUSED :5432` | Check DATABASE_URL, DB status | +| **HEALTH_CHECK** | `Health check timeout` | Add /health endpoint, check port binding | +| **OUT_OF_MEMORY** | `heap out of memory`, exit 137 | Optimize memory or upgrade plan | +| **BUILD_FAILURE** | `Command failed` | Fix build command or dependencies | + +Full error catalog: [references/error-patterns.md](references/error-patterns.md) + +**If errors repeat across deploys:** Switch from incremental fixes to a broader sweep. Scan the codebase/config for all likely causes in that error class (related env vars, build config, dependencies, or type errors) and address them together before the next redeploy. + +### Step 4: Check Metrics (Performance Issues) + +For crashes, slow responses, or resource issues: + +``` +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "memory_usage", "memory_limit"] +) +``` + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpLatencyQuantile: 0.95 +) +``` + +Detailed metrics guide: [references/metrics-debugging.md](references/metrics-debugging.md) + +### Step 5: Debug Database Issues + +For database-related errors: + +``` +# Check database status +list_postgres_instances() + +# Check connections +get_metrics(resourceId: "", metricTypes: ["active_connections"]) + +# Query directly +query_render_postgres( + postgresId: "", + sql: "SELECT state, count(*) FROM pg_stat_activity GROUP BY state" +) +``` + +Detailed database guide: [references/database-debugging.md](references/database-debugging.md) + +### Step 6: Apply Fix + +**For environment variables:** +``` +update_environment_variables( + serviceId: "", + envVars: [{"key": "MISSING_VAR", "value": "value"}] +) +``` + +**For code changes:** +1. Edit the source file +2. Commit and push +3. Deploy triggers automatically (if auto-deploy enabled) + +### Step 7: Verify Fix + +``` +# Check deploy status +list_deploys(serviceId: "", limit: 1) + +# Check for new errors +list_logs(resource: [""], level: ["error"], limit: 20) + +# Check metrics +get_metrics(resourceId: "", metricTypes: ["http_request_count"]) +``` + +--- + +## Quick Workflows + +Pre-built debugging sequences for common scenarios: + +| Scenario | Workflow | +|----------|----------| +| Deploy failed | `list_deploys` → `list_logs(type: build)` → fix → redeploy | +| App crashing | `list_logs(level: error)` → `get_metrics(memory)` → fix | +| App slow | `get_metrics(http_latency)` → `get_metrics(cpu)` → `query_postgres` | +| DB connection | `list_postgres` → `get_metrics(connections)` → `query_postgres` | +| Post-deploy check | `list_deploys` → `list_logs(error)` → `get_metrics` | + +Detailed workflows: [references/quick-workflows.md](references/quick-workflows.md) + +--- + +## Quick Reference + +### MCP Tools + +``` +# Service Discovery +list_services() +get_service(serviceId: "") +list_postgres_instances() + +# Logs +list_logs(resource: [""], level: ["error"], limit: 100) +list_logs(resource: [""], type: ["build"], limit: 200) +list_logs(resource: [""], text: ["search"], limit: 50) + +# Metrics +get_metrics(resourceId: "", metricTypes: ["cpu_usage", "memory_usage"]) +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.95) + +# Database +query_render_postgres(postgresId: "", sql: "SELECT ...") + +# Deployments +list_deploys(serviceId: "", limit: 5) + +# Environment Variables +update_environment_variables(serviceId: "", envVars: [{key, value}]) +``` + +### CLI Commands (Fallback) + +```bash +render services -o json +render logs -r --level error -o json +render logs -r --tail -o text +render deploys create --wait +``` + +--- + +## References + +- **Render access:** [references/render-access.md](references/render-access.md) +- **Environment variables:** [references/environment-variables.md](references/environment-variables.md) +- **Compute plans:** [references/compute-plans.md](references/compute-plans.md) +- **Deployments:** [references/deployments.md](references/deployments.md) +- **Error patterns:** [references/error-patterns.md](references/error-patterns.md) +- **Metrics debugging:** [references/metrics-debugging.md](references/metrics-debugging.md) +- **Database debugging:** [references/database-debugging.md](references/database-debugging.md) +- **Quick workflows:** [references/quick-workflows.md](references/quick-workflows.md) +- **Log analysis:** [references/log-analysis.md](references/log-analysis.md) +- **Troubleshooting:** [references/troubleshooting.md](references/troubleshooting.md) + +## Related Skills + +- **render-deploy** — Deploy new applications to Render +- **render-monitor** — Ongoing service health monitoring +- **render-mcp** — MCP server setup and capability discovery + + +## Current documentation retrieval + +Whenever this skill directs you to consult current Render documentation: + +1. Retrieve the linked Markdown document directly with an available URL-fetching tool or HTTP client, such as `curl`. Do not substitute web-search summaries for the document. +2. Confirm that retrieval succeeded and returned the expected document, then read its contents. Saving a file or printing its path is not sufficient. +3. If the request fails or your tool cannot read the Markdown response, open and read the linked HTML version instead. +4. If neither version can be retrieved, disclose that the current reference is unavailable and follow any topic-specific fallback in the skill. Use bundled guidance only for stable constraints, and do not guess at changeable platform details. + +When a task requires multiple references, apply this workflow to each one and distinguish the documents you verified from those that remain unavailable. + diff --git a/.agents/skills/render-debug/references/compute-plans.md b/.agents/skills/render-debug/references/compute-plans.md new file mode 100644 index 0000000..5d0ccc1 --- /dev/null +++ b/.agents/skills/render-debug/references/compute-plans.md @@ -0,0 +1,23 @@ + +## Compute plans + +A compute plan determines the CPU and RAM available to each instance of a Render service. Use **compute plan**, not the former term **instance type**. Do not confuse a service's compute plan with its workspace plan, which controls account-level features and limits. + +Compute plans differ by service type: + +- Web services, private services, background workers, and cron jobs use CPU-and-memory plan IDs such as `0.5c-512mb` and `1c-2g`. +- Render Postgres has its own plan catalog and connection limits. +- Render Key Value uses memory-based plan IDs such as `256mb` and `1g`. +- Workflow tasks select a compute plan in application code; a Workflow service does not set a Blueprint `plan`. +- Static sites do not have compute plans. + +Legacy plan names such as `starter`, `standard`, and `pro` remain valid in Render tooling, including Blueprints and API requests. For new configuration, prefer the current plan ID when the selected configuration surface accepts it. Before passing a plan to an API, MCP tool, or CLI command, inspect that operation's current schema or help and use one of its accepted values; the compute-plan reference describes the product catalog, not every tool version's input contract. Do not rename an existing legacy plan merely for consistency unless the user asks for that change. + +Do not rely on a memorized plan catalog. When a task depends on current plan IDs, specifications, defaults, availability, or pricing, fetch the canonical compute-plan reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/compute-plans.md) or its [HTML version](https://render.com/docs/compute-plans). + +Read the section for the relevant service type. If the document cannot be fetched, do not guess at current plan details. Preserve an existing valid plan where possible, or explain that the plan must be confirmed in the Render Dashboard or current documentation. + +When estimating capacity or cost, remember that every instance of a scaled service uses the selected compute plan and is billed accordingly. Changing the compute plan for Render Postgres, Render Key Value, or a service with an attached persistent disk requires brief downtime; other services normally apply the change with a zero-downtime deploy. + diff --git a/.agents/skills/render-debug/references/database-debugging.md b/.agents/skills/render-debug/references/database-debugging.md new file mode 100644 index 0000000..70e1406 --- /dev/null +++ b/.agents/skills/render-debug/references/database-debugging.md @@ -0,0 +1,299 @@ +# Database Debugging + +Diagnose and fix PostgreSQL database issues on Render using MCP tools. + +## When to Use Database Debugging + +Use these techniques when you see: +- `ECONNREFUSED` or connection errors +- `ETIMEDOUT` on database operations +- Slow queries affecting application performance +- Connection pool exhaustion +- Database CPU/memory alerts + +## Connection Debugging + +### Check Database Status + +``` +list_postgres_instances() +``` + +Verify the database exists and note its ID. + +### Get Database Details + +``` +get_postgres(postgresId: "") +``` + +### Check Connection Metrics + +``` +get_metrics( + resourceId: "", + metricTypes: ["active_connections"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +### Query Active Connections + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT state, count(*) FROM pg_stat_activity GROUP BY state" +) +``` + +**Connection states:** +| State | Meaning | +|-------|---------| +| `active` | Running a query | +| `idle` | Connected but not running query | +| `idle in transaction` | In a transaction, not running query (potential issue) | +| `idle in transaction (aborted)` | Transaction failed, connection stuck | + +### Check Connection Limits + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT max_conn, used, res_for_super, max_conn - used - res_for_super AS available FROM (SELECT count(*) used FROM pg_stat_activity) t, (SELECT setting::int res_for_super FROM pg_settings WHERE name = 'superuser_reserved_connections') t2, (SELECT setting::int max_conn FROM pg_settings WHERE name = 'max_connections') t3" +) +``` + +Connection limits vary by Postgres compute plan. Fetch the current plan table and limits using [compute-plans.md](compute-plans.md), then compare them with the database's live `max_connections` value. + +### Fix Connection Issues + +**Connection pool exhaustion:** +1. Implement connection pooling in your app +2. Reduce connection timeout +3. Close connections properly +4. Upgrade the database compute plan + +**Node.js connection pooling:** +```javascript +const { Pool } = require('pg'); +const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + max: 20, // Maximum connections in pool + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 2000, +}); +``` + +**Python connection pooling:** +```python +from sqlalchemy import create_engine +engine = create_engine( + DATABASE_URL, + pool_size=5, + max_overflow=10, + pool_timeout=30, + pool_recycle=1800 +) +``` + +## Query Performance Debugging + +### Find Slow Queries + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT query, calls, mean_exec_time, total_exec_time, rows FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10" +) +``` + +**Note:** `pg_stat_statements` must be enabled (it is by default on Render). + +### Find Queries by Total Time + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT query, calls, total_exec_time, mean_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10" +) +``` + +This finds queries that consume the most total time (even if individual executions are fast). + +### Analyze Query Plans + +For a specific slow query, run EXPLAIN ANALYZE (be careful in production): + +``` +query_render_postgres( + postgresId: "", + sql: "EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT * FROM users WHERE email = 'test@example.com'" +) +``` + +**Look for:** +- `Seq Scan` on large tables (missing index) +- High `rows` estimates vs actual rows (stale statistics) +- Nested loops with high row counts (N+1 pattern) + +### Check Missing Indexes + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT schemaname, relname, seq_scan, seq_tup_read, idx_scan, idx_tup_fetch FROM pg_stat_user_tables WHERE seq_scan > 0 ORDER BY seq_tup_read DESC LIMIT 10" +) +``` + +Tables with high `seq_scan` and low `idx_scan` may need indexes. + +### Check Index Usage + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT schemaname, relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes ORDER BY idx_scan DESC LIMIT 20" +) +``` + +Indexes with `idx_scan = 0` are unused and could be removed. + +## Lock Debugging + +### Check for Lock Contention + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT blocked_locks.pid AS blocked_pid, blocked_activity.usename AS blocked_user, blocking_locks.pid AS blocking_pid, blocking_activity.usename AS blocking_user, blocked_activity.query AS blocked_statement, blocking_activity.query AS blocking_statement FROM pg_catalog.pg_locks blocked_locks JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype AND blocking_locks.database IS NOT DISTINCT FROM blocked_locks.database AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid AND blocking_locks.pid != blocked_locks.pid JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid WHERE NOT blocked_locks.granted LIMIT 10" +) +``` + +### Check Long-Running Queries + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state FROM pg_stat_activity WHERE (now() - pg_stat_activity.query_start) > interval '1 minute' AND state != 'idle' ORDER BY duration DESC" +) +``` + +## Storage Debugging + +### Check Table Sizes + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT schemaname, relname, pg_size_pretty(pg_total_relation_size(relid)) AS total_size, pg_size_pretty(pg_relation_size(relid)) AS table_size, pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) AS index_size FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 10" +) +``` + +### Check Database Size + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT pg_size_pretty(pg_database_size(current_database())) AS database_size" +) +``` + +### Check Table Bloat + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT schemaname, relname, n_live_tup, n_dead_tup, round(n_dead_tup::numeric / nullif(n_live_tup + n_dead_tup, 0) * 100, 2) AS dead_percentage FROM pg_stat_user_tables WHERE n_dead_tup > 1000 ORDER BY n_dead_tup DESC LIMIT 10" +) +``` + +Tables with high `dead_percentage` (>20%) may need `VACUUM`. + +## Database Resource Metrics + +### Check Database CPU + +``` +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +High database CPU usually indicates: +- Slow queries doing full table scans +- Complex joins without proper indexes +- High query volume + +### Check Database Memory + +``` +get_metrics( + resourceId: "", + metricTypes: ["memory_usage"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +## Quick Diagnosis Workflows + +### "Database connection refused" + +``` +# 1. Check database exists and status +list_postgres_instances() + +# 2. Check connection count (might be at limit) +get_metrics(resourceId: "", metricTypes: ["active_connections"]) + +# 3. Check for stuck connections +query_render_postgres( + postgresId: "", + sql: "SELECT state, count(*) FROM pg_stat_activity GROUP BY state" +) + +# 4. Verify service has correct DATABASE_URL +get_service(serviceId: "") +``` + +### "Database queries are slow" + +``` +# 1. Find slowest queries +query_render_postgres( + postgresId: "", + sql: "SELECT query, mean_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 5" +) + +# 2. Check for missing indexes +query_render_postgres( + postgresId: "", + sql: "SELECT relname, seq_scan, idx_scan FROM pg_stat_user_tables WHERE seq_scan > idx_scan ORDER BY seq_scan DESC LIMIT 5" +) + +# 3. Check database CPU (might be overloaded) +get_metrics(resourceId: "", metricTypes: ["cpu_usage"]) +``` + +### "Database storage full" + +``` +# 1. Check current size +query_render_postgres( + postgresId: "", + sql: "SELECT pg_size_pretty(pg_database_size(current_database()))" +) + +# 2. Find largest tables +query_render_postgres( + postgresId: "", + sql: "SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 5" +) + +# 3. Check for bloat +query_render_postgres( + postgresId: "", + sql: "SELECT relname, n_dead_tup FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5" +) +``` diff --git a/.agents/skills/render-debug/references/deployments.md b/.agents/skills/render-debug/references/deployments.md new file mode 100644 index 0000000..5ca9905 --- /dev/null +++ b/.agents/skills/render-debug/references/deployments.md @@ -0,0 +1,50 @@ + +## Deployments and health checks + +A Render deploy is asynchronous. A successful trigger means only that Render accepted or queued the deploy; it does not mean the new version is live. Before triggering a deploy, confirm the workspace, service, intended source commit or image, and current live deploy. Capture the new deploy ID, monitor it to a terminal state, and do not report success until its status is `live` and the deployed workload has been verified. + +Before configuring or troubleshooting deployments and health checks, fetch the current Render references: + +- [deploys.md](https://render.com/docs/deploys.md) (HTML: ) +- [health-checks.md](https://render.com/docs/health-checks.md) (HTML: ) + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read both references. + +Read the relevant sections of both documents. Confirm current service-type support, command timeouts, health-check thresholds, rollout behavior, and configuration syntax rather than relying on remembered values. + +Automatic deployment behavior depends on the service's source and settings. A service linked to a branch through a connected Git provider can deploy on each commit, wait for supported CI checks, or require manual triggers. Services that pull a prebuilt image and services linked by a public Git repository URL require manual deploys; moving a mutable image tag does not itself trigger one. When manually deploying a historical commit, verify whether that trigger method changes automatic-deploy settings. If automatic deploys remain enabled, a later branch update can replace the selected commit. + +The normal lifecycle is build command, optional pre-deploy command, then start command and readiness checks. If a command fails or times out, the deploy fails and later steps do not run. A pre-deploy command runs after the build on a separate instance before the new version is deployed. Neither the build nor pre-deploy instance can access an attached persistent disk, and pre-deploy filesystem changes do not carry into the running service. Use pre-deploy for release tasks such as database migrations, not for producing runtime artifacts. Pre-deploy commands are supported for paid web services, private services, and background workers. + +Render normally deploys services without downtime by starting the new version before retiring the current one. Web and private services continue routing traffic to the current instances until the new instances are ready. Multi-instance services roll out one instance at a time; if a replacement does not become healthy, Render cancels the rollout and retains or restores the previous version. Attaching a persistent disk disables zero-downtime deploys, so plan explicitly for an interruption. + +A workflow deployment has a different completion model. It builds and caches the image used by future task runs and includes a task-registration step, but it does not execute those tasks. After a workflow deploy succeeds, verify that the expected task definitions are registered. Trigger and monitor a task run separately only when execution is intended. For workflow-specific deployment behavior, fetch the current workflow overview: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/workflows.md) or its [HTML version](https://render.com/docs/workflows). + +Health checks apply to web services and private services. Both use TCP socket checks by default. Only web services support a configured HTTP health-check path. Render sends an HTTP `GET`; any `2xx` or `3xx` response received within five seconds succeeds, while other status codes, timeouts, and connection failures fail. Private services support TCP checks only. + +For a new deploy, all new instances must pass their checks at the same time within the current readiness window, documented as 15 minutes, before Render routes traffic to them. For a running service, consecutive failures currently remove an instance from routing after 15 seconds and restart it after 60 seconds. Treat these thresholds as platform behavior, not user-tunable health-check interval settings, and verify them in the fetched reference before relying on exact timing. + +Design an HTTP health endpoint to represent readiness for production traffic. Keep it fast and side-effect free. Check critical dependencies only when losing that dependency should make the entire instance unavailable; otherwise a transient dependency failure can unnecessarily remove healthy application capacity. Verify the configured path, response status, response time, listening port, and `0.0.0.0` binding when checks fail. + +After traffic moves, Render gives the previous instance a drain period, then sends `SIGTERM`. The application should stop accepting new work, finish or safely abandon in-flight work, close connections, and exit within its shutdown delay. Ensure the actual application process receives the signal: container entrypoints and shell wrappers should use `exec` or explicitly forward signals. Render sends `SIGKILL` if the process remains running after the delay. The documented default shutdown delay is 30 seconds and the usual maximum is 300 seconds, but support varies by service configuration; confirm the current reference and Blueprint or API validation before setting `maxShutdownDelaySeconds`. + +A service restart is a special deploy of the same commit and user-defined environment-variable values as the current running instance. It does not incorporate configuration changes saved after that deploy. Use a standard deploy when pending configuration must take effect. + +Only one deploy runs at a time for a service. A workspace's overlapping-deploy policy determines whether a new trigger waits or cancels the in-progress deploy. Do not assume the policy or wait for every intermediate revision: inspect the workspace setting and identify the deploy that actually became live. + +Treat rollback as a new deploy based on a retained previous build artifact, not as restoration of the entire service to an earlier point in time. It does not reverse database migrations, messages, external writes, or other side effects from the release, so confirm that the previous application version remains compatible with current external state. Disks and their data are not rolled back, some settings continue using current configuration, mutable image tags can resolve to a different image, and eligible artifacts are retained only for a limited period. Before rolling back, fetch the current rollback reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/rollbacks.md) or its [HTML version](https://render.com/docs/rollbacks). + +Read which configuration comes from the target deploy and which remains current. After the rollback is created, inspect the service's resulting automatic-deploy setting instead of assuming whether it remains enabled, and deliberately restore the intended setting after the underlying issue is resolved. + +Deploy hooks are secret credentials that authorize deploys. Never print, commit, or expose their full URLs. Before using one, fetch the current deploy-hook reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/deploy-hooks.md) or its [HTML version](https://render.com/docs/deploy-hooks). + +Distinguish an immediately started deploy from a queued one, and continue monitoring the resulting deploy rather than treating the HTTP response as completion. + +After a deploy becomes live, verify the behavior appropriate to the service type: make a request to a web or private service, confirm a worker is processing work, confirm a cron job or workflow invocation completes, and inspect recent runtime logs for new errors. If a deploy fails, diagnose the first failed lifecycle stage before retrying. + diff --git a/.agents/skills/render-debug/references/environment-variables.md b/.agents/skills/render-debug/references/environment-variables.md new file mode 100644 index 0000000..e9de03c --- /dev/null +++ b/.agents/skills/render-debug/references/environment-variables.md @@ -0,0 +1,38 @@ + +## Environment variables and secrets + +Render environment-variable values are strings. Applications must explicitly parse values that represent booleans, numbers, lists, or structured data; for example, the string `"false"` is truthy in many languages. + +Environment variables can be managed through the Render Dashboard, Blueprints, environment groups, and supported API, MCP, or CLI operations. Before changing a service, determine which mechanism is intended to be the source of truth. Do not make parallel Dashboard and infrastructure-as-code edits without explaining how future syncs or deploys will reconcile them. + +Never commit secret values to application source, `render.yaml`, checked-in `.env` files, fixtures, examples, or logs. Keep local secret-bearing `.env` files out of version control. Do not print or repeat secret values returned by the user, Render, or another provider. Use Render's supported secret mechanisms or an external secret manager appropriate to the user's workflow. + +Before configuring environment variables, secret files, or environment groups, fetch the current Render configuration reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/configure-environment-variables.md) or its [HTML version](https://render.com/docs/configure-environment-variables). + +Read the sections relevant to the configuration surface being used. Dashboard save options can rebuild and deploy, deploy the existing build, or save without deploying; do not assume a changed value is active until the applicable deploy occurs. + +For Blueprint-managed variables, also consult the current Blueprint YAML reference before writing syntax or predicting update behavior. In particular: + +- Use literal `value` entries only for non-sensitive configuration. +- `generateValue: true` creates a platform-generated secret when the variable does not already exist. +- `sync: false` prompts for a value only during initial Blueprint creation. It is ignored for existing services during later Blueprint updates, is not included in preview environments, and is not valid in environment groups. +- Use current `fromDatabase`, `fromService`, and `fromGroup` syntax instead of hardcoding connection strings or copying shared values. + +Blueprint syncs preserve existing service environment variables that are omitted from the Blueprint; omission does not delete them. Values defined with `fromDatabase` or `fromService` refresh on each Blueprint sync, not immediately when the referenced property or variable changes. + +Environment groups provide shared variables and secret files to linked services. A variable defined directly on a service takes precedence over the same key from a linked group. Precedence between multiple linked groups with the same key is not guaranteed; avoid collisions instead of depending on group creation order. Respect project-environment scoping when linking groups to services. + +Use secret files for credentials or configuration that must be read from the filesystem rather than an environment variable. Confirm current size and runtime-path rules in the fetched reference. Treat secret-file contents with the same precautions as other credentials. + +Render also injects documented default environment variables. Do not maintain a memorized catalog. Fetch the current default-variable reference when a task depends on a variable's name, availability, build/runtime scope, or semantics: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/environment-variables.md) or its [HTML version](https://render.com/docs/environment-variables). + +Depend only on documented platform variables. Other `RENDER_*` variables are internal and can change without notice. + +Treat environment-variable changes as service configuration mutations. Confirm the target workspace and service, inspect the existing keys without exposing their values, and preserve variables outside the user's requested scope. Before using an API, MCP, or CLI operation, check whether it patches individual keys or replaces the complete collection. After the applicable deploy, verify that required keys are present and that the service starts successfully without logging secret values. + +If the current references or live configuration cannot be inspected, do not guess at secret behavior, precedence, or replacement semantics. Preserve existing configuration where possible and explain what must be confirmed before making the change. + diff --git a/.agents/skills/render-debug/references/error-patterns.md b/.agents/skills/render-debug/references/error-patterns.md new file mode 100644 index 0000000..fd243ca --- /dev/null +++ b/.agents/skills/render-debug/references/error-patterns.md @@ -0,0 +1,859 @@ +# Render Deployment Error Patterns + +Comprehensive catalog of common deployment errors on Render, their causes, and fixes. Organized by frequency and category. + +## MCP Quick Detection + +Use these MCP queries to quickly detect each error pattern: + +| Error Type | MCP Detection Query | +|------------|-------------------| +| Missing Env Var | `list_logs(resource: [""], text: ["KeyError", "not defined", "undefined"], limit: 50)` | +| Port Binding | `list_logs(resource: [""], text: ["EADDRINUSE", "address already in use"], limit: 20)` | +| Missing Dependency | `list_logs(resource: [""], text: ["Cannot find module", "ModuleNotFoundError"], limit: 50)` | +| Database Connection | `list_logs(resource: [""], text: ["ECONNREFUSED", "could not connect"], limit: 50)` | +| Health Check | `list_logs(resource: [""], text: ["Health check", "failed to become healthy"], limit: 20)` | +| OOM | `list_logs(resource: [""], text: ["heap out of memory", "OOMKilled", "exit code 137"], limit: 20)` | +| Build Failure | `list_logs(resource: [""], type: ["build"], text: ["error", "failed"], limit: 100)` | + +--- + +## Most Common Errors + +### 1. MISSING_ENV_VAR (Most Common) + +**Description:** Application crashes because required environment variable is not set. + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["KeyError", "not defined", "undefined", "Missing required environment"], + limit: 50 +) +``` + +**Patterns to Match:** +- `ReferenceError: DATABASE_URL is not defined` +- `TypeError: Cannot read property 'DATABASE_URL' of undefined` +- `KeyError: 'API_KEY'` +- `KeyError: 'JWT_SECRET'` +- `Environment variable not found: DATABASE_URL` +- `Missing required environment variable` +- `process.env.DATABASE_URL is undefined` +- `os.environ['DATABASE_URL'] KeyError` + +**Common Variables:** +- `DATABASE_URL` - PostgreSQL connection string +- `REDIS_URL` - Key Value connection string +- `JWT_SECRET` - Authentication secret +- `API_KEY` - Third-party API keys +- `SECRET_KEY` - Django secret key +- `NEXTAUTH_SECRET` - NextAuth.js secret +- `SESSION_SECRET` - Session encryption key + +**Root Causes:** +1. Variable not declared in render.yaml +2. Variable marked with `sync: false` but user didn't fill in Dashboard +3. Typo in variable name (case-sensitive!) +4. Variable added to code but not to render.yaml + +**Fix Strategy:** + +1. Read [environment-variables.md](environment-variables.md) and determine whether the service is managed through a Blueprint, Dashboard configuration, or an API/MCP operation. +2. Inspect existing keys without exposing values, then add only the missing configuration through the intended source of truth. +3. Use current Blueprint resource references rather than copied connection strings, and use an appropriate secret mechanism for sensitive values. +4. Apply the applicable deploy and verify successful startup in logs. + +**Prevention:** +- Keep the chosen configuration source authoritative +- Never commit or print secret values +- Double-check variable names (case-sensitive) +- Keep local secret-bearing `.env` files out of version control + +--- + +### 2. PORT_BINDING_ERROR (Second Most Common) + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["EADDRINUSE", "address already in use", "cannot assign requested address"], + limit: 20 +) +``` + +**Description:** Application not binding to correct port or host. + +**Patterns to Match:** +- `EADDRINUSE: address already in use` +- `Error: listen EADDRINUSE: address already in use 0.0.0.0:3000` +- `Address already in use (os error 48)` +- `Failed to bind to 0.0.0.0:3000` +- `Health check timeout` (often caused by wrong port) +- `cannot assign requested address` + +**Root Causes:** +1. App hardcodes port instead of using `$PORT` environment variable +2. App binds to `localhost` or `127.0.0.1` instead of `0.0.0.0` +3. Multiple services trying to use same port +4. App doesn't read PORT environment variable + +**Fix Strategy:** + +**Node.js / Express:** +```javascript +// Before (WRONG) +app.listen(3000); +app.listen(3000, 'localhost'); + +// After (CORRECT) +const PORT = process.env.PORT || 3000; +app.listen(PORT, '0.0.0.0', () => { + console.log(`Server running on port ${PORT}`); +}); +``` + +**Python / Flask:** +```python +# Before (WRONG) +app.run(port=5000) +app.run(host='localhost', port=5000) + +# After (CORRECT) +import os +port = int(os.environ.get('PORT', 5000)) +app.run(host='0.0.0.0', port=port) +``` + +**Python / Django (gunicorn):** +```yaml +# In render.yaml startCommand +startCommand: gunicorn config.wsgi:application --bind 0.0.0.0:$PORT +``` + +**Go:** +```go +// Before (WRONG) +http.ListenAndServe(":3000", handler) + +// After (CORRECT) +port := os.Getenv("PORT") +if port == "" { + port = "3000" +} +http.ListenAndServe(":"+port, handler) +``` + +**Prevention:** +- Always use `process.env.PORT` (or equivalent) +- Always bind to `0.0.0.0` +- Test with PORT=10000 locally + +--- + +### 3. MISSING_DEPENDENCY + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["Cannot find module", "ModuleNotFoundError", "ImportError", "package not found"], + limit: 50 +) +``` + +**Description:** Required package or module not installed. + +**Patterns to Match:** +- `Cannot find module 'express'` +- `Error: Cannot find module './config'` +- `ModuleNotFoundError: No module named 'django'` +- `ImportError: No module named flask` +- `package not found: github.com/gin-gonic/gin` +- `error: could not find `tokio` in the list of imported crates` + +**Root Causes:** +1. Dependency not in package.json/requirements.txt/go.mod +2. Wrong build command +3. Build cache issues +4. Dependency only in devDependencies + +**Fix Strategy:** + +**Node.js:** +```json +// Add to package.json +{ + "dependencies": { + "express": "^4.18.0", + "pg": "^8.11.0" + } +} +``` + +**Python:** +``` +# Add to requirements.txt +django==4.2.0 +psycopg2-binary==2.9.5 +``` + +**Go:** +```bash +# Update go.mod +go get github.com/gin-gonic/gin +``` + +**Prevention:** +- Keep dependencies in sync with code +- Use lock files (package-lock.json, Pipfile.lock) +- Test build locally first + +--- + +## Configuration Errors + +### 4. DATABASE_CONNECTION_FAILED + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["ECONNREFUSED", "could not connect to server", "connection refused", "ETIMEDOUT"], + limit: 50 +) +``` + +**MCP Investigation:** +``` +# Check database status +list_postgres_instances() + +# Check connection metrics +get_metrics( + resourceId: "", + metricTypes: ["active_connections"] +) + +# Query database directly +query_render_postgres( + postgresId: "", + sql: "SELECT count(*) FROM pg_stat_activity" +) +``` + +**Description:** Cannot connect to database. + +**Patterns to Match:** +- `ECONNREFUSED 127.0.0.1:5432` +- `could not connect to server: Connection refused` +- `FATAL: password authentication failed` +- `connect ETIMEDOUT` +- `Redis connection to 127.0.0.1:6379 failed` +- `SSL SYSCALL error: EOF detected` + +**Root Causes:** +1. DATABASE_URL not set +2. Wrong connection string format +3. Database not provisioned +4. SSL settings incorrect +5. Connection timeout too short + +**Fix Strategy:** + +**Step 1:** Verify DATABASE_URL is set in render.yaml +```yaml +envVars: + - key: DATABASE_URL + fromDatabase: + name: postgres + property: connectionString +``` + +**Step 2:** Enable SSL if needed (Node.js example) +```javascript +const { Pool } = require('pg'); +const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + ssl: process.env.NODE_ENV === 'production' ? { + rejectUnauthorized: false + } : false +}); +``` + +**Step 3:** Check database provisioned +```bash +render services -o json +# Verify database exists and is active +``` + +--- + +### 5. INVALID_BUILD_COMMAND + +**Description:** Build command fails. + +**Patterns to Match:** +- `npm ERR! missing script: build` +- `sh: line 1: webpack: command not found` +- `error: failed to compile` +- `SyntaxError: Unexpected token` +- `Error: Command failed with exit code 1` + +**Root Causes:** +1. Wrong build script name +2. Build tools not installed +3. Syntax errors in code +4. Build script doesn't exist + +**Fix Strategy:** + +**Node.js - Check package.json:** +```json +{ + "scripts": { + "build": "tsc", // or webpack, vite, etc. + "start": "node dist/index.js" + } +} +``` + +**Render.yaml:** +```yaml +buildCommand: npm ci && npm run build +``` + +**Python - No build step needed:** +```yaml +buildCommand: pip install -r requirements.txt +``` + +--- + +## Runtime Errors + +### 6. HEALTH_CHECK_TIMEOUT + +Read [deployments.md](deployments.md) for current health-check behavior, timing, and service-type support before interpreting this failure. + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["Health check", "failed to become healthy", "timeout"], + limit: 30 +) +``` + +**MCP Investigation:** +``` +# Check if service is binding correctly +list_logs( + resource: [""], + text: ["listening", "started", "running on port"], + limit: 20 +) + +# Check CPU/Memory during startup +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "memory_usage"] +) +``` + +**Description:** Service doesn't respond to health checks within timeout period. + +**Patterns to Match:** +- `Health check timeout` +- `failed to become healthy` +- `Service did not pass health check` +- `GET / returned status 404` + +**Root Causes:** +1. Configured health check endpoint is missing or incorrect +2. App not binding to correct port +3. Slow application startup +4. Health check path incorrect +5. Application crashes during startup + +**Fix Strategy:** + +**Step 1:** Add health check endpoint + +**Node.js:** +```javascript +app.get('/health', (req, res) => { + res.status(200).json({ status: 'ok', timestamp: Date.now() }); +}); +``` + +**Python / Flask:** +```python +@app.route('/health') +def health(): + return {'status': 'ok'}, 200 +``` + +**Step 2:** Configure in render.yaml +```yaml +healthCheckPath: /health +``` + +**Step 3:** Ensure fast startup +- Move slow initialization to after server start +- Use lazy loading for heavy operations + +--- + +### 7. OUT_OF_MEMORY (OOM) + +**MCP Detection:** +``` +list_logs( + resource: [""], + text: ["heap out of memory", "Killed", "OOMKilled", "exit code 137", "cannot allocate memory"], + limit: 30 +) +``` + +**MCP Investigation:** +``` +# Check memory usage trend +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "memory_limit"] +) + +# Check if memory usage spiked +get_metrics( + resourceId: "", + metricTypes: ["memory_usage"], + startTime: "" +) +``` + +**Description:** Application exceeds available memory. + +**Patterns to Match:** +- `JavaScript heap out of memory` +- `FATAL ERROR: Reached heap limit Allocation failed` +- `Killed` (exit code 137) +- `OOMKilled` +- `cannot allocate memory` + +**Root Causes:** +1. Memory leak in application +2. Processing too much data at once +3. Free tier limit (512 MB) exceeded +4. Large dependency tree +5. No garbage collection optimization + +**Fix Strategy:** + +**Short-term fixes:** + +**Node.js - Increase heap size (if on paid plan):** +```yaml +envVars: + - key: NODE_OPTIONS + value: --max-old-space-size=2048 +``` + +**Python - Optimize memory:** +```python +# Process data in chunks +for chunk in pd.read_csv('large_file.csv', chunksize=1000): + process(chunk) +``` + +**Long-term fixes:** +1. Profile memory usage +2. Fix memory leaks +3. Optimize data structures +4. Upgrade to higher plan with more RAM + +--- + +### 8. UNCAUGHT_EXCEPTION + +**Description:** Unhandled error crashes the application. + +**Patterns to Match:** +- `UnhandledPromiseRejectionWarning` +- `Uncaught Error:` +- `Traceback (most recent call last):` +- `panic: runtime error:` +- `Fatal error:` + +**Root Causes:** +1. Missing error handling +2. Async errors not caught +3. Null pointer exceptions +4. Division by zero + +**Fix Strategy:** + +**Node.js - Add error handlers:** +```javascript +// Catch all errors +process.on('uncaughtException', (err) => { + console.error('Uncaught Exception:', err); + process.exit(1); +}); + +process.on('unhandledRejection', (reason, promise) => { + console.error('Unhandled Rejection:', reason); + process.exit(1); +}); + +// Express error handler +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).json({ error: 'Internal server error' }); +}); +``` + +**Python - Add try/catch:** +```python +try: + # Your code + result = risky_operation() +except Exception as e: + logger.error(f"Error: {e}") + # Handle gracefully +``` + +--- + +## Build Errors + +### 9. BUILD_TIMEOUT + +**Description:** Build takes longer than allowed time. + +**Patterns to Match:** +- `Build timed out after 120 minutes` +- `Command timed out` +- `Build exceeded time limit` + +**Root Causes:** +1. Too many dependencies +2. Large dependency compilation (native modules) +3. Slow build scripts +4. Network issues downloading packages + +**Fix Strategy:** + +**Optimize dependencies:** +```json +// Remove unused dependencies +{ + "dependencies": { + // Only what you actually use + } +} +``` + +**Use faster build commands:** +```yaml +buildCommand: npm ci --prefer-offline && npm run build +``` + +If the build cannot complete within the 120-minute command limit, move expensive artifact generation to CI/CD or another build stage and deploy the resulting artifact or image. + +--- + +### 10. DOCKER_BUILD_FAILED + +**Description:** Docker image build fails. + +**Patterns to Match:** +- `failed to solve with frontend dockerfile.v0` +- `ERROR [internal] load metadata for` +- `failed to compute cache key` +- `COPY failed:` +- `RUN returned a non-zero code` + +**Root Causes:** +1. Invalid Dockerfile syntax +2. Base image not found +3. COPY source doesn't exist +4. RUN command fails +5. Build context too large + +**Fix Strategy:** + +**Check Dockerfile:** +```dockerfile +# Use valid base image +FROM node:20-alpine + +# Set working directory +WORKDIR /app + +# Copy dependency files first +COPY package*.json ./ +RUN npm ci + +# Then copy source +COPY . . + +# Build +RUN npm run build + +# Expose port +EXPOSE 10000 + +# Start +CMD ["npm", "start"] +``` + +**Add .dockerignore:** +``` +node_modules +.git +.env +*.log +``` + +--- + +## Database Errors + +### 11. DATABASE_MIGRATION_FAILED + +**Description:** Database migration fails during build. + +**Patterns to Match:** +- `ProgrammingError: relation "users" already exists` +- `django.db.migrations.exceptions.InconsistentMigrationHistory` +- `Prisma migration failed` +- `Migration failed to apply` + +**Root Causes:** +1. Migration conflicts +2. Database already has schema +3. Migration dependencies missing +4. Database locked + +**Fix Strategy:** + +**Django:** +```bash +# Check migration status +python manage.py showmigrations + +# Fake initial migration if schema exists +python manage.py migrate --fake-initial +``` + +**Rails:** +```bash +# Check schema exists +bundle exec rails db:migrate:status + +# Reset if needed (CAUTION: data loss) +bundle exec rails db:reset +``` + +**Prisma:** +```bash +# Deploy migrations +npx prisma migrate deploy + +# Or generate client only +npx prisma generate +``` + +--- + +## Security & Permission Errors + +### 12. PERMISSION_DENIED + +**Description:** Application doesn't have permission to access resource. + +**Patterns to Match:** +- `EACCES: permission denied` +- `Error: EPERM: operation not permitted` +- `PermissionError: [Errno 13] Permission denied` + +**Root Causes:** +1. Trying to write to read-only filesystem +2. Wrong file permissions +3. Trying to bind to privileged port (<1024) + +**Fix Strategy:** + +**Use allowed directories:** +- `/tmp` - writable temporary storage +- `/var` - avoid, not writable +- Use environment variables for file paths + +**Use correct port:** +```yaml +envVars: + - key: PORT + value: 10000 # Use 10000, not 80 or 443 +``` + +--- + +## Dependency Version Errors + +### 13. VERSION_MISMATCH + +**Description:** Incompatible dependency versions. + +**Patterns to Match:** +- `npm ERR! peer dep missing` +- `npm ERR! ERESOLVE unable to resolve dependency tree` +- `Requires: Python >=3.8, but current version is 3.7` +- `requires Go version 1.20 or later` + +**Fix Strategy:** + +**Node.js - Fix peer dependencies:** +```bash +npm install --legacy-peer-deps +``` + +Or update package.json: +```json +{ + "engines": { + "node": ">=18.0.0", + "npm": ">=9.0.0" + } +} +``` + +**Python - Specify version:** +``` +# runtime.txt +python-3.11.5 +``` + +**Go - Update go.mod:** +```go +go 1.21 +``` + +--- + +## Resource Errors + +### 14. DISK_SPACE_EXCEEDED + +**Description:** Running out of disk space during build or runtime. + +**Patterns to Match:** +- `No space left on device` +- `ENOSPC: no space left on device` +- `Disk quota exceeded` + +**Root Causes:** +1. Large build artifacts +2. Log files growing too large +3. Too many dependencies + +**Fix Strategy:** + +**Clean build artifacts:** +```yaml +buildCommand: npm ci && npm run build && npm prune --production +``` + +**Remove unnecessary files:** +```bash +# In build command +rm -rf .git tests/ docs/ +``` + +--- + +## Networking Errors + +### 15. EXTERNAL_API_TIMEOUT + +**Description:** External API calls timing out. + +**Patterns to Match:** +- `ETIMEDOUT` +- `ESOCKETTIMEDOUT` +- `Request timeout` +- `connect ETIMEDOUT` + +**Root Causes:** +1. API endpoint down +2. Network issues +3. Timeout too short +4. Rate limiting + +**Fix Strategy:** + +**Add retries and timeout:** +```javascript +const axios = require('axios'); + +const api = axios.create({ + timeout: 10000, + retry: { + retries: 3, + retryDelay: (retryCount) => retryCount * 1000 + } +}); +``` + +--- + +## Quick Reference Matrix + +| Error Pattern | Frequency | Severity | Typical Fix Time | +|---------------|-----------|----------|------------------| +| MISSING_ENV_VAR | Very High | High | 5 minutes | +| PORT_BINDING_ERROR | High | High | 10 minutes | +| MISSING_DEPENDENCY | High | Medium | 5 minutes | +| DATABASE_CONNECTION | Medium | High | 15 minutes | +| HEALTH_CHECK_TIMEOUT | Medium | Medium | 15 minutes | +| OUT_OF_MEMORY | Medium | Medium | 30+ minutes | +| BUILD_TIMEOUT | Low | Medium | 30+ minutes | +| UNCAUGHT_EXCEPTION | Medium | High | Varies | + +## Debugging Priority Order + +1. **Check environment variables first** (Most common) +2. **Verify port binding** (Second most common) +3. **Check build logs for errors** +4. **Verify database connections** +5. **Check for missing dependencies** +6. **Review application logs** +7. **Check resource usage** + +## Exit Code Reference + +Common exit codes and their meanings: + +| Exit Code | Signal | Meaning | Common Cause | +|-----------|--------|---------|--------------| +| 0 | - | Success | Normal termination | +| 1 | - | General error | Application error, uncaught exception | +| 2 | - | Misuse | Invalid arguments, bad command usage | +| 126 | - | Cannot execute | Permission denied | +| 127 | - | Not found | Command or binary not found | +| 128+N | Signal N | Killed by signal | See signal codes below | +| 130 | SIGINT (2) | Interrupted | Ctrl+C, manual interrupt | +| 137 | SIGKILL (9) | Killed | Out of memory (OOM), forced kill | +| 139 | SIGSEGV (11) | Segmentation fault | Memory access violation | +| 143 | SIGTERM (15) | Terminated | Graceful shutdown request | + +**Note:** Exit codes 128+N indicate the process was terminated by signal N. For example, 137 = 128 + 9 (SIGKILL). + +## Next Steps + +After identifying error pattern: +1. Review [troubleshooting.md](troubleshooting.md) for detailed fix procedures +2. Review [log-analysis.md](log-analysis.md) for log reading tips +3. Apply fix and monitor deployment diff --git a/.agents/skills/render-debug/references/log-analysis.md b/.agents/skills/render-debug/references/log-analysis.md new file mode 100644 index 0000000..c27fe0d --- /dev/null +++ b/.agents/skills/render-debug/references/log-analysis.md @@ -0,0 +1,479 @@ +# Render Log Analysis Guide + +How to read, interpret, and analyze Render logs to identify deployment and runtime issues. + +## Understanding Render Logs + +### Log Types + +Render provides different log types for different purposes: + +1. **Deploy Logs** - Build and deployment process +2. **Runtime Logs** - Application output after deployment +3. **System Logs** - Render platform events + +### Log Levels + +Logs are categorized by severity: + +- **error** - Critical errors requiring attention +- **warn** - Warning messages (potential issues) +- **info** - Informational messages +- **debug** - Detailed debugging information + +## CLI Commands for Logs + +### Basic Log Retrieval + +**Get deploy logs (build/deployment phase):** +```bash +render logs -r --type deploy -o json +``` + +**Get runtime logs (after service starts):** +```bash +render logs -r -o json +``` + +**Get error logs only:** +```bash +render logs -r --level error -o json +``` + +**Get recent logs (limit output):** +```bash +render logs -r --limit 200 -o json +``` + +**Stream logs in real-time:** +```bash +render logs -r --tail -o text +``` + +### Advanced Filtering + +**Combine filters:** +```bash +render logs -r --type deploy --level error --limit 100 -o json +``` + +**Output formats:** +- `-o json` - JSON format (easier to parse) +- `-o text` - Plain text (human-readable) +- `-o yaml` - YAML format + +## Reading Deploy Logs + +Deploy logs show the build and deployment process. Read them **sequentially** from top to bottom. + +### Typical Deploy Log Structure + +``` +1. Repository cloning + → Cloning repository from git remote + +2. Environment setup + → Setting up build environment + → Installing runtime (node, python, etc.) + +3. Build phase + → Running buildCommand + → Installing dependencies + → Compiling code + +4. Pre-deploy checks + → Validating configuration + → Checking for required files + +5. Deploy phase + → Running startCommand + → Starting service + +6. Health checks + → Waiting for service to respond + → Verifying health check endpoint + +7. Success or failure + → Deploy succeeded + → OR: Deploy failed with error +``` + +### Key Sections to Check + +**1. Build Command Execution:** +``` +==> Running 'npm ci' +npm WARN deprecated package@1.0.0 +added 250 packages in 15s +``` + +Look for: +- `npm ERR!` - npm errors +- `error: ` - compilation errors +- `FATAL:` - critical build errors + +**2. Start Command Execution:** +``` +==> Running 'npm start' +> app@1.0.0 start +> node server.js + +Server listening on port 10000 +``` + +Look for: +- Server startup messages +- Port binding confirmation +- Error messages during startup + +**3. Health Check Results:** +``` +==> Checking service health at https://myapp.onrender.com/ +Health check passed +Deploy succeeded +``` + +Look for: +- `Health check timeout` - Service not responding +- `Health check failed` - Service responding with error +- `Health check passed` - Success + +## Reading Runtime Logs + +Runtime logs show application output after successful deployment. + +### Understanding Runtime Log Entries + +Each log entry typically contains: +```json +{ + "timestamp": "2024-01-24T10:30:45.123Z", + "level": "error", + "message": "Database connection failed", + "service": "web-app", + "instance": "srv-abc123-instance-1" +} +``` + +### Common Runtime Log Patterns + +**1. Application Startup:** +``` +Server started successfully +Listening on port 10000 +Database connected +``` + +**2. Request Handling:** +``` +GET /api/users 200 - 45ms +POST /api/auth 401 - 12ms +``` + +**3. Errors:** +``` +Error: Cannot find module 'express' +UnhandledPromiseRejectionWarning: Error: Connection timeout +TypeError: Cannot read property 'id' of undefined +``` + +**4. Database Operations:** +``` +Connected to PostgreSQL +Query executed: SELECT * FROM users +Database connection pool: 5/20 active +``` + +## Identifying Error Location + +### Finding the Error Line + +**Look for these keywords:** +- `Error:` +- `Exception:` +- `FATAL:` +- `failed` +- `crashed` +- `timeout` +- `refused` + +**Error message structure:** +``` +Error: Cannot find module 'express' + at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) + at Function.Module._load (internal/modules/cjs/loader.js:725:27) + at Module.require (internal/modules/cjs/loader.js:952:19) + at require (internal/modules/cjs/helpers.js:88:18) + at Object. (/app/server.js:1:17) ← YOUR CODE +``` + +The first line with `/app/` is usually your code. + +### Stack Trace Analysis + +**Reading stack traces:** + +1. **Error message** - Top line describes the error +2. **Stack frames** - Lines below show call path +3. **File locations** - Look for paths starting with `/app/` +4. **Line numbers** - Shows exact line in your code + +**Example:** +``` +ReferenceError: DATABASE_URL is not defined + at connectDatabase (/app/database.js:15:23) ← Error on line 15 + at startup (/app/server.js:10:5) ← Called from line 10 + at Object. (/app/server.js:50:1) ← App entry point +``` + +**Action:** Open `/app/database.js` line 15 to see the issue. + +## Common Log Patterns by Error Type + +### Missing Environment Variable + +``` +Error: DATABASE_URL is not defined + at /app/config.js:12:45 + +ReferenceError: process.env.API_KEY is undefined + +KeyError: 'JWT_SECRET' +``` + +**Action:** Add to render.yaml envVars + +### Port Binding Error + +``` +Error: listen EADDRINUSE: address already in use 0.0.0.0:3000 + at Server.setupListenHandle [as _listen2] (net.js:1313:16) + +Address already in use (os error 48) +``` + +**Action:** Update code to use `process.env.PORT` + +### Database Connection Error + +``` +Error: connect ECONNREFUSED 127.0.0.1:5432 + at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16) + +could not connect to server: Connection refused + Is the server running on host "127.0.0.1" and accepting + TCP/IP connections on port 5432? +``` + +**Action:** Verify DATABASE_URL and database status + +### Health Check Timeout + +``` +==> Checking service health at https://myapp.onrender.com/ +Health check timeout after 300 seconds +Deploy failed +``` + +**Action:** Check port binding and add /health endpoint + +### Out of Memory + +``` +<--- Last few GCs ---> + +FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory +``` + +**Action:** Optimize memory usage or upgrade plan + +## Filtering Relevant Logs + +### What to Focus On + +**For Build Failures:** +1. Look at build command output +2. Find first error in build logs +3. Check dependency installation section +4. Review compilation errors + +**For Runtime Failures:** +1. Look at start command output +2. Check first few seconds of runtime logs +3. Look for startup errors +4. Check health check section + +### What to Ignore (Usually) + +- Deprecation warnings (unless they cause errors) +- Info-level messages +- Successful operation logs +- Normal request logs (200 responses) + +## Tips for Efficient Log Analysis + +### 1. Start with Error-Level Logs + +```bash +render logs -r --level error -o json +``` + +This filters out noise and shows only critical issues. + +### 2. Use JSON Output for Parsing + +JSON format is easier to search and parse programmatically: + +```bash +render logs -r -o json | grep "DATABASE_URL" +``` + +### 3. Limit Output + +Don't retrieve all logs at once: + +```bash +render logs -r --limit 200 -o json +``` + +Most errors appear in recent logs. + +### 4. Focus on Deployment Logs First + +If deployment failed, deploy logs contain the error: + +```bash +render logs -r --type deploy --level error -o json +``` + +### 5. Use Real-Time Streaming + +Watch logs as deployment happens: + +```bash +render logs -r --tail -o text +``` + +### 6. Search for Specific Patterns + +Look for common error keywords: +- "Error:" +- "Exception" +- "failed" +- "timeout" +- "refused" +- "undefined" +- "not found" + +## Troubleshooting Workflow + +**Step 1:** Get error-level logs +```bash +render logs -r --level error -o json --limit 100 +``` + +**Step 2:** Identify error type +- Missing env var? +- Port binding issue? +- Build failure? +- Database connection? + +**Step 3:** Get context +```bash +render logs -r --limit 500 -o json +``` + +Read logs around the error for context. + +**Step 4:** Match to error pattern +Refer to [error-patterns.md](error-patterns.md) for known patterns. + +**Step 5:** Apply fix +Refer to [troubleshooting.md](troubleshooting.md) for fix procedures. + +## Log Examples + +### Example 1: Successful Deployment + +``` +==> Cloning from https://github.com/user/repo... +==> Running build command 'npm ci' +added 250 packages in 15s +==> Running start command 'npm start' +Server listening on port 10000 +==> Health check passed +Deploy succeeded +``` + +### Example 2: Missing Environment Variable + +``` +==> Running start command 'npm start' +Server starting... +ReferenceError: DATABASE_URL is not defined + at connectDatabase (/app/database.js:15:23) +Process exited with code 1 +Deploy failed +``` + +### Example 3: Port Binding Error + +``` +==> Running start command 'npm start' +Server starting on port 3000... +Error: listen EADDRINUSE: address already in use 0.0.0.0:3000 +Process exited with code 1 +Deploy failed +``` + +### Example 4: Health Check Timeout + +``` +==> Running start command 'npm start' +Server started +==> Checking service health at https://myapp.onrender.com/ +Health check timeout after 300 seconds +Deploy failed +``` + +## Quick Reference + +### Log Commands Cheat Sheet + +```bash +# Error logs only +render logs -r --level error -o json + +# Deploy logs +render logs -r --type deploy -o json + +# Stream logs +render logs -r --tail -o text + +# Recent logs +render logs -r --limit 200 -o json + +# All options combined +render logs -r --type deploy --level error --limit 100 -o json +``` + +### Error Keywords to Search For + +- `Error:` +- `Exception` +- `FATAL` +- `failed` +- `timeout` +- `refused` +- `undefined` +- `not found` +- `cannot` +- `invalid` + +## Next Steps + +After analyzing logs: +1. Identify error pattern in [error-patterns.md](error-patterns.md) +2. Follow fix procedure in [troubleshooting.md](troubleshooting.md) +3. Apply fix and redeploy +4. Monitor logs during next deployment diff --git a/.agents/skills/render-debug/references/metrics-debugging.md b/.agents/skills/render-debug/references/metrics-debugging.md new file mode 100644 index 0000000..7334053 --- /dev/null +++ b/.agents/skills/render-debug/references/metrics-debugging.md @@ -0,0 +1,297 @@ +# Metrics-Based Debugging + +Use Render metrics to diagnose performance issues, resource constraints, and application health problems. + +## When to Use Metrics + +Use metrics debugging when you see: +- Out of memory errors (OOM, exit code 137) +- Slow response times +- Service crashes or restarts +- Health check timeouts +- Autoscaling issues + +## CPU Metrics + +### Get CPU Usage + +``` +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "cpu_limit"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +### Interpreting CPU + +| CPU Usage | Status | Action | +|-----------|--------|--------| +| <70% | Healthy | No action needed | +| 70-85% | Warning | Monitor trends | +| >85% sustained | Critical | Optimize or upgrade plan | + +**High CPU causes:** +- Inefficient algorithms +- Missing database indexes (N+1 queries) +- Synchronous blocking operations +- Large JSON parsing/serialization + +**CPU Fixes:** +1. Profile code to find hot paths +2. Add caching for repeated computations +3. Optimize database queries +4. Use async/non-blocking operations +5. Upgrade to higher plan + +## Memory Metrics + +### Get Memory Usage + +``` +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "memory_limit"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +### Interpreting Memory + +| Memory % of Limit | Status | Action | +|-------------------|--------|--------| +| <70% | Healthy | No action needed | +| 70-85% | Warning | Monitor for leaks | +| 85-95% | Danger | Investigate immediately | +| >95% | Critical | OOM imminent | + +Use the resource's reported memory limit instead of inferring capacity from a legacy plan name. When the current plan specification matters, fetch it using [compute-plans.md](compute-plans.md). + +**High memory causes:** +- Memory leaks (objects not garbage collected) +- Large in-memory caches +- Processing large files/datasets in memory +- Too many concurrent connections + +**Memory Fixes:** + +**Node.js:** +```javascript +// Increase heap size (if on paid plan) +// Set NODE_OPTIONS=--max-old-space-size=2048 + +// Process data in streams +const stream = fs.createReadStream('large-file.json'); +stream.pipe(parser).on('data', processChunk); +``` + +**Python:** +```python +# Process data in chunks +for chunk in pd.read_csv('large_file.csv', chunksize=1000): + process(chunk) + +# Use generators instead of lists +def process_items(): + for item in large_dataset: + yield transform(item) +``` + +## HTTP Performance Metrics + +### Get Latency + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpLatencyQuantile: 0.95, + startTime: "<1-hour-ago-ISO8601>" +) +``` + +**Common quantiles:** +- `0.5` (p50) - Median, typical experience +- `0.95` (p95) - Most users' worst experience +- `0.99` (p99) - Tail latency, outliers + +### Interpreting Latency + +| p95 Latency | Status | Likely Cause | +|-------------|--------|--------------| +| <200ms | Excellent | - | +| 200-500ms | Good | Complex queries | +| 500ms-1s | Concerning | DB or external API | +| 1-2s | Poor | Multiple slow operations | +| >2s | Critical | Major bottleneck | + +### Get Request Count + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_request_count"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +**Aggregate by status code to find error rates:** +``` +get_metrics( + resourceId: "", + metricTypes: ["http_request_count"], + aggregateHttpRequestCountsBy: "statusCode" +) +``` + +**Calculate error rate:** +``` +error_rate = 5xx_count / total_count * 100 +``` +Target: <0.1% error rate + +### Filter by Endpoint + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpPath: "/api/users", + httpHost: "api.example.com" +) +``` + +## Instance Metrics + +### Get Instance Count + +``` +get_metrics( + resourceId: "", + metricTypes: ["instance_count"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +### Interpreting Instance Changes + +| Pattern | Meaning | +|---------|---------| +| Increasing | Autoscaling up (traffic increase) | +| Decreasing | Autoscaling down (traffic decrease) | +| Stuck at 1 | Autoscaling may not be enabled | +| Rapid fluctuation | Possible instability | + +### Check Autoscaling Targets + +``` +get_metrics( + resourceId: "", + metricTypes: ["cpu_target", "memory_target"] +) +``` + +## Bandwidth Metrics + +### Get Bandwidth Usage + +``` +get_metrics( + resourceId: "", + metricTypes: ["bandwidth_usage"], + startTime: "<1-hour-ago-ISO8601>" +) +``` + +**High bandwidth causes:** +- Large API responses +- Uncompressed responses +- File downloads +- Verbose logging to external services + +**Bandwidth fixes:** +1. Enable gzip/brotli compression +2. Paginate large responses +3. Use CDN for static assets +4. Optimize image sizes + +## Correlation Analysis + +### Correlate Metrics with Deploys + +``` +# Get deploy times +list_deploys(serviceId: "", limit: 10) + +# Check metrics around deploy time +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "memory_usage", "http_latency"], + startTime: "", + endTime: "" +) +``` + +### Correlate with Errors + +``` +# Get error timestamps +list_logs( + resource: [""], + level: ["error"], + limit: 50 +) + +# Check metrics at error time +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "cpu_usage"], + startTime: "", + endTime: "" +) +``` + +## Quick Diagnostics + +### OOM Diagnosis + +``` +# 1. Check if memory was at limit before crash +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "memory_limit"], + startTime: "" +) + +# 2. Look for memory growth pattern +# Steady growth = memory leak +# Sudden spike = large request or data load +``` + +### Slow Response Diagnosis + +``` +# 1. Check if CPU-bound +get_metrics(resourceId: "", metricTypes: ["cpu_usage"]) + +# 2. Check latency percentiles +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.5) +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.99) + +# 3. If p99 >> p50, you have outlier requests causing issues +# 4. Check slow endpoints +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpPath: "/api/slow-endpoint") +``` + +### Crash Loop Diagnosis + +``` +# 1. Check instance count for restarts +get_metrics(resourceId: "", metricTypes: ["instance_count"]) + +# 2. Check memory at crash times +get_metrics(resourceId: "", metricTypes: ["memory_usage"]) + +# 3. Check logs for crash reason +list_logs(resource: [""], level: ["error"], limit: 100) +``` diff --git a/.agents/skills/render-debug/references/quick-workflows.md b/.agents/skills/render-debug/references/quick-workflows.md new file mode 100644 index 0000000..e2613ea --- /dev/null +++ b/.agents/skills/render-debug/references/quick-workflows.md @@ -0,0 +1,297 @@ +# Quick Debugging Workflows + +Step-by-step MCP tool sequences for common debugging scenarios. + +## Deploy Failures + +### "Why did my deploy fail?" + +``` +# 1. Find the failed deploy +list_deploys(serviceId: "", limit: 5) +# Look for status: build_failed, update_failed, or canceled + +# 2. Get deploy details +get_deploy(serviceId: "", deployId: "") +# Check finishedAt, status, and any error messages + +# 3. Check build logs +list_logs( + resource: [""], + type: ["build"], + limit: 200 +) +# Look for error messages, failed commands, missing dependencies + +# 4. Search for specific errors +list_logs( + resource: [""], + text: ["error", "failed", "not found"], + limit: 100 +) +``` + +**Common causes:** +- Missing dependencies in package.json/requirements.txt +- Build command syntax errors +- Missing environment variables during build +- Build timeout (120-minute build-command limit) + +--- + +## Runtime Crashes + +### "Why is my app crashing?" + +``` +# 1. Get runtime error logs +list_logs( + resource: [""], + level: ["error"], + limit: 100 +) + +# 2. Check for missing env vars (most common) +list_logs( + resource: [""], + text: ["KeyError", "undefined", "not defined"], + limit: 50 +) + +# 3. Check memory usage (OOM crashes) +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "memory_limit"] +) + +# 4. Get service config to review +get_service(serviceId: "") +# Check envVars, startCommand, healthCheckPath +``` + +**Common causes:** +- Missing environment variables +- Port binding to localhost instead of 0.0.0.0 +- Unhandled exceptions +- Out of memory (exit code 137) + +--- + +## Performance Issues + +### "Why is my app slow?" + +``` +# 1. Check HTTP latency (p95) +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpLatencyQuantile: 0.95 +) +# >500ms p95 indicates performance issues + +# 2. Check CPU usage (might be compute-bound) +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "cpu_limit"] +) +# >80% sustained CPU = upgrade or optimize + +# 3. Check for slow endpoints (5xx errors often indicate timeouts) +list_logs( + resource: [""], + statusCode: ["500", "502", "503", "504"], + limit: 50 +) + +# 4. If database-related, check slow queries +query_render_postgres( + postgresId: "", + sql: "SELECT query, mean_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10" +) +``` + +**Common causes:** +- Slow database queries (missing indexes) +- External API timeouts +- CPU-intensive operations +- Memory pressure causing GC pauses + +--- + +## Database Issues + +### "Why can't my app connect to the database?" + +``` +# 1. Check for connection errors in logs +list_logs( + resource: [""], + text: ["ECONNREFUSED", "connection refused", "ETIMEDOUT"], + limit: 50 +) + +# 2. Verify database exists and is running +list_postgres_instances() +# Check status is active + +# 3. Check database connection count +get_metrics( + resourceId: "", + metricTypes: ["active_connections"] +) +# Near max = connection pool exhaustion + +# 4. Query connection status directly +query_render_postgres( + postgresId: "", + sql: "SELECT state, count(*) FROM pg_stat_activity GROUP BY state" +) + +# 5. Verify DATABASE_URL is set in service +get_service(serviceId: "") +# Check envVars includes DATABASE_URL +``` + +**Common causes:** +- DATABASE_URL not set or incorrect +- Connection pool exhaustion +- Database not provisioned yet +- SSL configuration issues + +--- + +## Health Verification + +### "Is my app healthy after deploy?" + +``` +# 1. Check deploy status +list_deploys(serviceId: "", limit: 1) +# Should show status: "live" + +# 2. Wait 2-3 min, then check for errors +list_logs( + resource: [""], + level: ["error"], + limit: 20 +) +# Should be empty or only expected errors + +# 3. Check HTTP requests are coming through +get_metrics( + resourceId: "", + metricTypes: ["http_request_count"] +) +# Should see requests if service is being used + +# 4. Check resource usage is normal +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "memory_usage"] +) +# CPU <70%, Memory <80% of limit +``` + +--- + +## Specific Error Patterns + +### Missing Environment Variable + +``` +# 1. Identify missing variable from logs +list_logs( + resource: [""], + text: ["KeyError", "undefined", "not defined"], + limit: 20 +) + +# 2. Check current service config +get_service(serviceId: "") + +# 3. Add missing variable +update_environment_variables( + serviceId: "", + envVars: [{"key": "MISSING_VAR", "value": "value"}] +) + +# 4. Redeploy happens automatically, verify +list_deploys(serviceId: "", limit: 1) +``` + +### Port Binding Error + +``` +# 1. Check for port errors +list_logs( + resource: [""], + text: ["EADDRINUSE", "address already in use"], + limit: 20 +) + +# 2. Check service configuration +get_service(serviceId: "") +# Verify startCommand uses $PORT + +# 3. Fix requires code change: +# - Read PORT from environment +# - Bind to 0.0.0.0, not localhost +# - Push fix and redeploy +``` + +### Out of Memory + +``` +# 1. Confirm OOM from logs +list_logs( + resource: [""], + text: ["heap out of memory", "Killed", "OOMKilled"], + limit: 20 +) + +# 2. Check memory trend before crash +get_metrics( + resourceId: "", + metricTypes: ["memory_usage", "memory_limit"], + startTime: "<1-hour-before-crash>" +) + +# 3. If steady growth = memory leak +# If sudden spike = large request/data + +# 4. Options: +# - Optimize memory usage in code +# - Process data in streams/chunks +# - Upgrade to higher plan +``` + +### Health Check Timeout + +``` +# 1. Check for health check errors +list_logs( + resource: [""], + text: ["Health check", "failed to become healthy"], + limit: 20 +) + +# 2. Check if app started successfully +list_logs( + resource: [""], + text: ["listening", "started", "running"], + limit: 20 +) + +# 3. Check startup time via CPU +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage"] +) +# High sustained CPU during startup = slow initialization + +# 4. Verify: +# - App binds to 0.0.0.0:$PORT +# - Configured health check endpoint exists and responds quickly +# - App becomes ready within the current window documented in deployments.md +``` diff --git a/.agents/skills/render-debug/references/render-access.md b/.agents/skills/render-debug/references/render-access.md new file mode 100644 index 0000000..8858a61 --- /dev/null +++ b/.agents/skills/render-debug/references/render-access.md @@ -0,0 +1,52 @@ + +## Accessing Render + +Prefer the hosted Render MCP server for structured access to Render resources when its tools are available. Use the Render CLI when MCP is unavailable or does not support the required operation, and use the Render Dashboard or API for capabilities exposed by neither. Do not assume that a remembered MCP tool or CLI command is still available; inspect the tools in the current environment or consult the current documentation. + +The hosted Render MCP server uses streamable HTTP at: + +```text +https://mcp.render.com/mcp +``` + +Official Render plugins and connectors can authenticate MCP with browser-based OAuth. Manual and non-interactive configurations can use a Render API key as a bearer token. Never write an API key or OAuth token into a repository, skill, command output, chat response, or log. Prefer the client's supported secret storage or environment-variable mechanism. If a client requires a credential in local configuration, keep that file out of version control and restrict access to it. + +Treat MCP responses as potentially sensitive even when the server attempts to minimize credential exposure. Request connection strings, credentials, secret environment variables, or other sensitive fields only when the task requires them. Do not repeat sensitive values in the response or persist them in files or logs. + +Before configuring or troubleshooting MCP, fetch the current setup and capability reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/mcp-server.md) or its [HTML version](https://render.com/docs/mcp-server). + +Read the relevant client setup, supported-actions, and limitations sections. Prefer the hosted server unless the user's environment requires a local MCP server. After installing, updating, or reconfiguring an MCP integration, reload the client as required and verify the connection with a read-only operation such as listing services. + +Render resource operations are workspace-scoped. With MCP, list workspaces when needed to establish the intended workspace, then pass its confirmed `workspaceId` on every related resource call that supports it. Reuse the workspace already confirmed in the conversation. Implicit session-based workspace selection is deprecated and can be lost on reconnect; do not rely on it when explicit targeting is available. For older tools without `workspaceId`, inspect their current workspace-selection mechanism and verify the selected workspace before proceeding. + +For CLI operations, check the active workspace before reading or changing resources. If the intended workspace is ambiguous, list the available workspaces and have the user identify the correct one. Do not silently switch workspace context or infer it from a resource name. Commands for authentication, help, CLI configuration, and workspace discovery or selection do not require an already selected workspace. + +For interactive CLI use, authenticate with `render login`. For automation, use a securely stored `RENDER_API_KEY`; an API key takes precedence over a saved CLI token. Verify CLI access and the active workspace with read-only commands before operating on resources: + +```bash +render whoami --output json +render workspace current --output json +``` + +For CLI installation, authentication, workspace setup, and usage patterns, fetch the current CLI overview: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/cli.md) or its [HTML version](https://render.com/docs/cli). + +For exact command syntax and flags, prefer the help text from the installed CLI because it matches the version being used: + +```bash +render help +``` + +The published CLI command reference is generated automatically from the CLI's help text. Use it to browse the full command surface or when the CLI is not installed: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/cli-reference.md) or its [HTML version](https://render.com/docs/cli-reference). + +When an agent or automation invokes the CLI, select a non-interactive output format such as `--output json`, `--output yaml`, or `--output text` so results can be inspected reliably. The global `--confirm` flag skips confirmation prompts; use it for a mutating command only after that mutation is authorized. It is an execution convenience, not permission to perform the action. + +Authentication establishes access; it does not establish user authorization for every available action. Use read-only discovery to resolve workspace, resource identity, and current state before a mutation. Perform changes only when they are within the user's requested scope, and retain normal approval requirements for consequential operations such as creation, configuration changes, deploys, restarts, scaling, or deletion. + +When authentication or connectivity fails, report which access path failed, preserve the underlying error without exposing credentials, and either use an available supported fallback or explain what the user must configure before the task can continue. + diff --git a/.agents/skills/render-debug/references/troubleshooting.md b/.agents/skills/render-debug/references/troubleshooting.md new file mode 100644 index 0000000..d78494f --- /dev/null +++ b/.agents/skills/render-debug/references/troubleshooting.md @@ -0,0 +1,619 @@ +# Render Troubleshooting Guide + +Systematic debugging procedures and fix strategies for common Render deployment issues. + +## General Debugging Process + +### The 5-Step Debugging Method + +1. **Identify** - What's failing? (Build, deploy, runtime?) +2. **Locate** - Where's the error? (Logs, error messages) +3. **Diagnose** - Why is it failing? (Root cause) +4. **Fix** - Apply appropriate solution +5. **Verify** - Test the fix works + +### Debug Priority Checklist + +When facing deployment issues, check in this order: + +- [ ] Environment variables (Most common) +- [ ] Port binding (Second most common) +- [ ] Dependencies installed correctly +- [ ] Database connections configured +- [ ] Build command successful +- [ ] Start command correct +- [ ] Health check endpoint exists +- [ ] Resource limits (memory, CPU) + +## Issue Category 1: Environment Variables + +### Problem: Missing Environment Variable + +**Symptoms:** +- `ReferenceError: DATABASE_URL is not defined` +- `KeyError: 'API_KEY'` +- Service crashes immediately after start + +**Diagnosis Steps:** + +1. Check logs for variable name: +```bash +render logs -r --level error -o json | grep "not defined" +``` + +2. List current environment variables: +```bash +# In Dashboard or render.yaml +``` + +3. Identify which variable is missing + +**Fix Procedure:** + +1. Read [environment-variables.md](environment-variables.md), identify the intended source of truth, and inspect existing keys without exposing values. +2. Add the missing key through that configuration surface, using current Blueprint wiring for resource references and an appropriate secret mechanism for sensitive values. +3. Commit and push if the service is Blueprint-managed; otherwise apply the authorized service configuration change. +4. Trigger the applicable deploy so the new value becomes active. + +**Verification:** +```bash +render logs -r --tail -o text +# Should see successful startup +``` + +--- + +## Issue Category 2: Port Binding + +### Problem: Port Binding Error + +**Symptoms:** +- `EADDRINUSE: address already in use` +- `Health check timeout` +- Service starts but doesn't receive traffic + +**Diagnosis Steps:** + +1. Check if app hardcodes port: +```bash +# Look for hardcoded ports in code +grep -r "listen(3000" . +grep -r "port.*=" . | grep -v "process.env" +``` + +2. Check if binding to localhost: +```bash +grep -r "localhost" . +grep -r "127.0.0.1" . +``` + +**Fix Procedure by Language:** + +**Node.js / Express:** + +Before (WRONG): +```javascript +app.listen(3000); +// or +app.listen(3000, 'localhost'); +``` + +After (CORRECT): +```javascript +const PORT = process.env.PORT || 3000; +app.listen(PORT, '0.0.0.0', () => { + console.log(`Server running on port ${PORT}`); +}); +``` + +**Python / Flask:** + +Before (WRONG): +```python +app.run(port=5000) +``` + +After (CORRECT): +```python +import os + +if __name__ == '__main__': + port = int(os.environ.get('PORT', 5000)) + app.run(host='0.0.0.0', port=port) +``` + +**Python / Django:** + +Ensure gunicorn uses $PORT: +```yaml +# In render.yaml +startCommand: gunicorn config.wsgi:application --bind 0.0.0.0:$PORT +``` + +**Go:** + +Before (WRONG): +```go +http.ListenAndServe(":3000", handler) +``` + +After (CORRECT): +```go +port := os.Getenv("PORT") +if port == "" { + port = "3000" +} +http.ListenAndServe(":"+port, handler) +``` + +**Verification:** +```bash +# Should see message like "Server running on port 10000" +render logs -r --tail -o text +``` + +--- + +## Issue Category 3: Database Connection + +### Problem: Cannot Connect to Database + +**Symptoms:** +- `ECONNREFUSED 127.0.0.1:5432` +- `could not connect to server` +- `Connection refused` + +**Diagnosis Steps:** + +1. Check if DATABASE_URL is set: +```bash +# Look in render.yaml +grep "DATABASE_URL" render.yaml +``` + +2. Verify database is provisioned: +```bash +render services -o json +# Look for database service +``` + +3. Check connection code + +**Fix Procedure:** + +**Step 1:** Ensure DATABASE_URL in render.yaml +```yaml +envVars: + - key: DATABASE_URL + fromDatabase: + name: postgres + property: connectionString + +databases: + - name: postgres + databaseName: myapp_prod + plan: free +``` + +**Step 2:** Configure SSL if needed + +**Node.js / pg:** +```javascript +const { Pool } = require('pg'); + +const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + ssl: process.env.NODE_ENV === 'production' ? { + rejectUnauthorized: false + } : false +}); +``` + +**Python / psycopg2:** +```python +import psycopg2 + +conn = psycopg2.connect( + os.environ['DATABASE_URL'], + sslmode='require' +) +``` + +**Step 3:** Add connection pooling + +**Node.js:** +```javascript +const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + max: 20, # Maximum connections + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 2000, +}); +``` + +**Python:** +```python +from sqlalchemy import create_engine +from sqlalchemy.pool import QueuePool + +engine = create_engine( + os.environ['DATABASE_URL'], + poolclass=QueuePool, + pool_size=10, + max_overflow=20 +) +``` + +**Step 4:** Test connection +```javascript +// Add health check with DB ping +app.get('/health', async (req, res) => { + try { + await pool.query('SELECT 1'); + res.status(200).json({ status: 'ok', database: 'connected' }); + } catch (err) { + res.status(500).json({ status: 'error', database: 'disconnected' }); + } +}); +``` + +--- + +## Issue Category 4: Build Failures + +### Problem: Build Command Fails + +**Symptoms:** +- `npm ERR!` +- `error: failed to compile` +- Build timeout + +**Diagnosis Steps:** + +1. Check build logs: +```bash +render logs -r --type deploy --level error -o json +``` + +2. Identify error type: +- Missing dependency? +- Compilation error? +- Build timeout? + +**Fix Procedures:** + +**Missing Dependency:** + +Check package.json/requirements.txt: +```json +{ + "dependencies": { + "express": "^4.18.0" // Add missing package + } +} +``` + +**Build Command Wrong:** + +Fix in render.yaml: +```yaml +# Node.js +buildCommand: npm ci && npm run build + +# Python +buildCommand: pip install -r requirements.txt + +# Go +buildCommand: go build -o bin/app . +``` + +**Build Timeout (120-minute build-command limit):** + +Optimize: +```yaml +# Use ci instead of install (faster) +buildCommand: npm ci --prefer-offline && npm run build + +# Remove unused dependencies +# Consider pre-building expensive artifacts in CI/CD +``` + +--- + +## Issue Category 5: Health Check Failures + +### Problem: Health Check Timeout + +Read [deployments.md](deployments.md) for current health-check behavior, timing, and service-type support before diagnosing this failure. + +**Symptoms:** +- `Health check timeout` +- `failed to become healthy` + +**Diagnosis Steps:** + +1. Check if app is binding to correct port +2. Check whether the configured health check endpoint exists and returns an accepted response +3. Check startup time + +**Fix Procedure:** + +**Step 1:** Add health endpoint + +**Node.js:** +```javascript +app.get('/health', (req, res) => { + res.status(200).json({ + status: 'ok', + timestamp: new Date().toISOString() + }); +}); +``` + +**Python / Flask:** +```python +@app.route('/health') +def health(): + return {'status': 'ok'}, 200 +``` + +**Python / FastAPI:** +```python +@app.get("/health") +async def health(): + return {"status": "ok"} +``` + +**Go:** +```go +http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) +}) +``` + +**Step 2:** Configure in render.yaml +```yaml +healthCheckPath: /health +``` + +**Step 3:** Optimize startup time + +Move slow operations after server start: +```javascript +// Start server first +const server = app.listen(PORT, '0.0.0.0', () => { + console.log(`Server running on port ${PORT}`); + + // Then do slow operations + initializeCache(); + warmupConnections(); +}); +``` + +--- + +## Issue Category 6: Memory Issues + +### Problem: Out of Memory + +**Symptoms:** +- `JavaScript heap out of memory` +- `Killed` (exit code 137) +- Service crashes randomly + +**Diagnosis Steps:** + +1. Check logs for OOM errors +2. Monitor memory usage +3. Identify memory leaks + +**Fix Procedures:** + +**Immediate Fix (Node.js):** + +Increase heap size (if on paid plan): +```yaml +envVars: + - key: NODE_OPTIONS + value: --max-old-space-size=2048 # 2GB +``` + +**Long-term Fixes:** + +1. **Profile memory usage:** +```javascript +// Add memory monitoring +setInterval(() => { + const used = process.memoryUsage(); + console.log(`Memory: ${Math.round(used.heapUsed / 1024 / 1024)}MB`); +}, 60000); +``` + +2. **Optimize data processing:** +```javascript +// Process in chunks instead of all at once +for (let i = 0; i < data.length; i += 1000) { + const chunk = data.slice(i, i + 1000); + await processChunk(chunk); +} +``` + +3. **Fix memory leaks:** +- Clear intervals/timeouts +- Remove event listeners +- Close database connections +- Clear caches periodically + +4. **Upgrade plan:** +- Free: 512 MB +- Starter: 512 MB +- Standard: 2 GB +- Pro: 4 GB+ + +--- + +## Issue Category 7: Runtime Crashes + +### Problem: Service Crashes After Start + +**Symptoms:** +- Service starts then exits +- `Process exited with code 1` +- Uncaught exceptions + +**Diagnosis Steps:** + +1. Get runtime logs: +```bash +render logs -r --level error -o json +``` + +2. Look for uncaught errors: +- Unhandled Promise rejections +- Uncaught exceptions +- Fatal errors + +**Fix Procedure:** + +**Add error handlers:** + +**Node.js:** +```javascript +// Catch all uncaught errors +process.on('uncaughtException', (err) => { + console.error('Uncaught Exception:', err); + process.exit(1); +}); + +process.on('unhandledRejection', (reason, promise) => { + console.error('Unhandled Rejection at:', promise, 'reason:', reason); + process.exit(1); +}); + +// Express error handler (add last) +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).json({ error: 'Internal server error' }); +}); +``` + +**Python:** +```python +import logging + +logging.basicConfig(level=logging.ERROR) +logger = logging.getLogger(__name__) + +try: + # Your code + app.run() +except Exception as e: + logger.error(f"Fatal error: {e}", exc_info=True) + raise +``` + +--- + +## Decision Tree: Where to Start + +``` +Deployment Failed? +├─ Build phase failed? +│ ├─ Check build logs for errors +│ ├─ Verify buildCommand is correct +│ ├─ Check dependencies installed +│ └─ Fix compilation errors +│ +├─ Deploy phase failed? +│ ├─ Check start command +│ ├─ Verify port binding +│ ├─ Check environment variables +│ └─ Check health check endpoint +│ +└─ Runtime failures? + ├─ Check for uncaught exceptions + ├─ Verify database connections + ├─ Check memory usage + └─ Review application logs +``` + +## Debugging Checklist + +Before asking for help, verify: + +- [ ] Required environment-variable keys exist in the intended configuration source +- [ ] Secret configuration is complete without exposing values +- [ ] App binds to `process.env.PORT` (or equivalent) +- [ ] App binds to `0.0.0.0` (not localhost) +- [ ] Build command is non-interactive +- [ ] Dependencies are in package.json/requirements.txt +- [ ] DATABASE_URL is set if using database +- [ ] /health endpoint exists (if using health checks) +- [ ] Local build works (`npm ci && npm run build`) +- [ ] Start command is correct + +## Quick Fixes Reference + +| Problem | Quick Fix | +|---------|-----------| +| Missing env var | Add to render.yaml envVars | +| Port binding | Use `process.env.PORT` + `0.0.0.0` | +| Database connection | Add DATABASE_URL with `fromDatabase` | +| Missing dependency | Add to package.json/requirements.txt | +| Build timeout | Optimize build, use `npm ci` | +| Health check timeout | Add `/health` endpoint | +| OOM | Optimize memory or upgrade plan | +| Uncaught exception | Add error handlers | + +## Advanced Troubleshooting + +### Enable Debug Logging + +**Node.js:** +```yaml +envVars: + - key: DEBUG + value: "*" # Enable all debug logs + - key: NODE_ENV + value: development # More verbose logs +``` + +### Test Locally First + +```bash +# Simulate Render environment +export PORT=10000 +export DATABASE_URL="postgresql://..." +npm ci && npm run build && npm start +``` + +### Check Render Status + +Sometimes issues are platform-wide: +- https://status.render.com + +## Getting Help + +If stuck after trying these steps: + +1. **Gather information:** + - Service ID + - Error messages from logs + - render.yaml content + - Steps to reproduce + +2. **Check documentation:** + - https://render.com/docs + +3. **Community support:** + - Render Community Forum + - Discord server + +## Next Steps + +After fixing issues: +- Monitor service health in Dashboard +- Set up alerts for failures +- Document any custom configuration +- Consider implementing monitoring/observability diff --git a/.agents/skills/render-env-vars/SKILL.md b/.agents/skills/render-env-vars/SKILL.md new file mode 100644 index 0000000..1f18314 --- /dev/null +++ b/.agents/skills/render-env-vars/SKILL.md @@ -0,0 +1,77 @@ +--- +name: render-env-vars +description: >- + Configures environment variables, secrets, and env groups on Render. Use when + the user needs to set env vars, wire secrets between services, create env + groups, use generateValue, set sync: false, or troubleshoot missing or + incorrect environment variable values in Blueprints or the Dashboard. +license: MIT +compatibility: Render Dashboard, CLI, or MCP tools +metadata: + author: Render + version: "1.0.0" + category: configuration +--- + +# Environment Variables on Render + +Before inspecting or changing environment variables, secrets, secret files, or environment groups, read `references/environment-variables.md` for the current documentation, source-of-truth, safety, and mutation workflow. + +Blueprint wiring examples and language-specific application notes live under `references/`. + +## When to Use This Skill + +Use this skill when users want to: + +- Add, change, or remove environment variables or secrets +- Understand Dashboard vs Blueprint vs API/MCP flows +- Use **environment groups** for shared configuration +- Wire `fromDatabase`, `fromService`, `fromGroup`, `sync: false`, or `generateValue` in Blueprints +- Debug missing vars, secret files, precedence, or platform-injected names + +For full Blueprint authoring, pair with **render-blueprints**. For first-time deploys, **render-deploy**. For web service behavior and ports, **render-web-services**. + +## Blueprint Wiring (Summary) + +After reading `references/environment-variables.md`, use `references/wiring-reference.md` for task-specific `fromDatabase`, `fromService`, and `fromGroup` examples. Consult **render-blueprints** for the complete Blueprint workflow. + +## Platform-Injected Variables + +Use the current default-variable reference fetched through `references/environment-variables.md` instead of relying on a fixed catalog. Language-specific application notes remain in `references/platform-variables.md`. + +## Runtime-Specific Defaults + +Always bind HTTP servers to **`0.0.0.0`** and **`PORT`** (or the stack’s documented port env) unless using a static site or custom Docker entrypoint. + +- When diagnosing a port-binding failure, first establish whether the service uses a native runtime or Docker and inspect its actual start command; the applicable defaults differ. +- For a web service, `PORT` defaults to **`10000`**. Prefer reading `$PORT` in the start command rather than hardcoding that number or setting `PORT` merely to match an arbitrary hardcoded port. +- Native Python services currently receive `GUNICORN_CMD_ARGS` with a default bind to **`0.0.0.0:10000`**. A custom Gunicorn start command should bind to **`0.0.0.0:$PORT`** so the process and Render's health checks use the same port. + +## Common Issues + +`WEB_CONCURRENCY` defaults differ for some older and newer services. When debugging worker counts, compare service creation date and explicit overrides, then confirm current behavior using `references/environment-variables.md` and `references/platform-variables.md`. + +## References + +- `references/environment-variables.md` — Current configuration docs, secret handling, groups, platform variables, and mutation safety +- `references/wiring-reference.md` — Blueprint cross-resource wiring examples and workspace edge cases +- `references/platform-variables.md` — Concurrency, native-runtime versus Docker behavior, and application parsing notes + +## Related Skills + +- **render-blueprints** — Full Blueprint authoring, validation, multi-service layouts +- **render-deploy** — First deploy, repo requirements, MCP vs YAML +- **render-web-services** — Ports, health checks, scaling behavior tied to env-driven servers + + +## Current documentation retrieval + +Whenever this skill directs you to consult current Render documentation: + +1. Retrieve the linked Markdown document directly with an available URL-fetching tool or HTTP client, such as `curl`. Do not substitute web-search summaries for the document. +2. Confirm that retrieval succeeded and returned the expected document, then read its contents. Saving a file or printing its path is not sufficient. +3. If the request fails or your tool cannot read the Markdown response, open and read the linked HTML version instead. +4. If neither version can be retrieved, disclose that the current reference is unavailable and follow any topic-specific fallback in the skill. Use bundled guidance only for stable constraints, and do not guess at changeable platform details. + +When a task requires multiple references, apply this workflow to each one and distinguish the documents you verified from those that remain unavailable. + diff --git a/.agents/skills/render-env-vars/references/environment-variables.md b/.agents/skills/render-env-vars/references/environment-variables.md new file mode 100644 index 0000000..e9de03c --- /dev/null +++ b/.agents/skills/render-env-vars/references/environment-variables.md @@ -0,0 +1,38 @@ + +## Environment variables and secrets + +Render environment-variable values are strings. Applications must explicitly parse values that represent booleans, numbers, lists, or structured data; for example, the string `"false"` is truthy in many languages. + +Environment variables can be managed through the Render Dashboard, Blueprints, environment groups, and supported API, MCP, or CLI operations. Before changing a service, determine which mechanism is intended to be the source of truth. Do not make parallel Dashboard and infrastructure-as-code edits without explaining how future syncs or deploys will reconcile them. + +Never commit secret values to application source, `render.yaml`, checked-in `.env` files, fixtures, examples, or logs. Keep local secret-bearing `.env` files out of version control. Do not print or repeat secret values returned by the user, Render, or another provider. Use Render's supported secret mechanisms or an external secret manager appropriate to the user's workflow. + +Before configuring environment variables, secret files, or environment groups, fetch the current Render configuration reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/configure-environment-variables.md) or its [HTML version](https://render.com/docs/configure-environment-variables). + +Read the sections relevant to the configuration surface being used. Dashboard save options can rebuild and deploy, deploy the existing build, or save without deploying; do not assume a changed value is active until the applicable deploy occurs. + +For Blueprint-managed variables, also consult the current Blueprint YAML reference before writing syntax or predicting update behavior. In particular: + +- Use literal `value` entries only for non-sensitive configuration. +- `generateValue: true` creates a platform-generated secret when the variable does not already exist. +- `sync: false` prompts for a value only during initial Blueprint creation. It is ignored for existing services during later Blueprint updates, is not included in preview environments, and is not valid in environment groups. +- Use current `fromDatabase`, `fromService`, and `fromGroup` syntax instead of hardcoding connection strings or copying shared values. + +Blueprint syncs preserve existing service environment variables that are omitted from the Blueprint; omission does not delete them. Values defined with `fromDatabase` or `fromService` refresh on each Blueprint sync, not immediately when the referenced property or variable changes. + +Environment groups provide shared variables and secret files to linked services. A variable defined directly on a service takes precedence over the same key from a linked group. Precedence between multiple linked groups with the same key is not guaranteed; avoid collisions instead of depending on group creation order. Respect project-environment scoping when linking groups to services. + +Use secret files for credentials or configuration that must be read from the filesystem rather than an environment variable. Confirm current size and runtime-path rules in the fetched reference. Treat secret-file contents with the same precautions as other credentials. + +Render also injects documented default environment variables. Do not maintain a memorized catalog. Fetch the current default-variable reference when a task depends on a variable's name, availability, build/runtime scope, or semantics: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/environment-variables.md) or its [HTML version](https://render.com/docs/environment-variables). + +Depend only on documented platform variables. Other `RENDER_*` variables are internal and can change without notice. + +Treat environment-variable changes as service configuration mutations. Confirm the target workspace and service, inspect the existing keys without exposing their values, and preserve variables outside the user's requested scope. Before using an API, MCP, or CLI operation, check whether it patches individual keys or replaces the complete collection. After the applicable deploy, verify that required keys are present and that the service starts successfully without logging secret values. + +If the current references or live configuration cannot be inspected, do not guess at secret behavior, precedence, or replacement semantics. Preserve existing configuration where possible and explain what must be confirmed before making the change. + diff --git a/.agents/skills/render-env-vars/references/platform-variables.md b/.agents/skills/render-env-vars/references/platform-variables.md new file mode 100644 index 0000000..3bfd78a --- /dev/null +++ b/.agents/skills/render-env-vars/references/platform-variables.md @@ -0,0 +1,17 @@ +# Runtime-specific environment-variable notes + +Read [environment-variables.md](environment-variables.md) and fetch the current default-variable reference before depending on a Render-injected variable's name, availability, build/runtime scope, or semantics. Do not use this file as a platform-variable catalog. + +## Worker concurrency + +Services created after December 8, 2025 use updated default `WEB_CONCURRENCY` behavior compared with older services. When debugging unexpected worker counts, compare the service creation date, explicit `WEB_CONCURRENCY` overrides, and the currently documented concurrency and CPU variables. + +Treat platform-provided concurrency values as starting points. Tune worker counts with both CPU and memory constraints in mind, and validate them under representative load. + +## Native runtimes and Docker + +Language-version environment variables primarily apply to Render native build pipelines. Docker-based services should encode toolchain versions in the image or its build configuration. Confirm the supported version-selection mechanism in the current runtime documentation before changing it. + +## Application parsing + +Environment-variable values arrive as strings. Parse integers with explicit error handling, and handle values such as `"false"` and the empty string deliberately in boolean logic. diff --git a/.agents/skills/render-env-vars/references/wiring-reference.md b/.agents/skills/render-env-vars/references/wiring-reference.md new file mode 100644 index 0000000..8186240 --- /dev/null +++ b/.agents/skills/render-env-vars/references/wiring-reference.md @@ -0,0 +1,174 @@ +# Blueprint environment variable wiring + +Read [environment-variables.md](environment-variables.md) first for current syntax discovery, secret handling, precedence, and mutation safety. This reference retains task-specific cross-resource wiring examples. Pair it with the **render-blueprints** skill for service structure, previews, and validation. + +## `fromDatabase` — database properties + +Reference a database defined in the same Blueprint (name must match the resource’s `name`). + +Available **properties** (use the subset your app needs): + +- `connectionString` +- `connectionPoolString` (when managed PgBouncer is enabled) +- `host` +- `port` +- `user` +- `password` +- `database` + +```yaml +databases: + - name: mydb + databaseName: myapp + user: myuser + +services: + - type: web + name: api + envVars: + - key: DATABASE_URL + fromDatabase: + name: mydb + property: connectionString + - key: DATABASE_POOL_URL + fromDatabase: + name: mydb + property: connectionPoolString + - key: PGHOST + fromDatabase: + name: mydb + property: host + - key: PGPORT + fromDatabase: + name: mydb + property: port + - key: PGUSER + fromDatabase: + name: mydb + property: user + - key: PGPASSWORD + fromDatabase: + name: mydb + property: password + - key: PGDATABASE + fromDatabase: + name: mydb + property: database +``` + +## `fromService` — Key Value + +Use `type: keyvalue` with one of: `connectionString`, `host`, or `port`. If an application needs `host:port`, combine the separate `host` and `port` values. + +```yaml +services: + - type: keyvalue + name: cache + ipAllowList: [] + + - type: web + name: api + envVars: + - key: REDIS_URL + fromService: + name: cache + type: keyvalue + property: connectionString + - key: REDIS_HOST + fromService: + name: cache + type: keyvalue + property: host + - key: REDIS_PORT + fromService: + name: cache + type: keyvalue + property: port +``` + +## `fromService` — private service or web service + +For **private services** (`pserv`) or **web** services, typical properties: + +- `host` — internal hostname +- `hostport` — `host:port` combined + +Alternatively, reference a **specific env var** exposed by the other service with `envVarKey` (when supported for that link type—confirm in Dashboard-generated Blueprints for your service types). + +```yaml +services: + - type: pserv + name: internal-api + runtime: docker + # ... + + - type: web + name: gateway + envVars: + - key: INTERNAL_API_HOST + fromService: + name: internal-api + type: pserv + property: host + - key: INTERNAL_API_HOSTPORT + fromService: + name: internal-api + type: pserv + property: hostport +``` + +```yaml + - key: UPSTREAM_TOKEN + fromService: + name: internal-api + type: web + envVarKey: SERVICE_TOKEN +``` + +(Adjust `type` to match the target service: `web`, `pserv`, etc.) + +## `fromGroup` — environment group + +Links **all** variables from the named group. Group must exist (or be created in the same Blueprint workflow, depending on your org’s pattern). + +```yaml +services: + - type: web + name: app + envVars: + - fromGroup: shared-config + - key: SERVICE_SPECIFIC + value: only-on-app +``` + +## Edge cases + +- **`fromService` / `fromDatabase` outside the Blueprint file** — You may reference resources that are **not** declared in `render.yaml` **only if** they **already exist** in the same Render **workspace** (same team/account context) and names match. Otherwise provision fails at apply time. + +## Minimal multi-pattern example + +```yaml +services: + - type: web + name: full-example + runtime: node + buildCommand: npm install && npm run build + startCommand: npm start + envVars: + - fromGroup: baseline + - key: PUBLIC_API_URL + value: https://api.example.com + - key: WEBHOOK_SIGNING_SECRET + generateValue: true + - key: THIRD_PARTY_API_KEY + sync: false + - key: DATABASE_URL + fromDatabase: + name: prod-db + property: connectionString + - key: REDIS_URL + fromService: + name: sessions-kv + type: keyvalue + property: connectionString +``` diff --git a/.agents/skills/render-monitor/SKILL.md b/.agents/skills/render-monitor/SKILL.md new file mode 100644 index 0000000..b339231 --- /dev/null +++ b/.agents/skills/render-monitor/SKILL.md @@ -0,0 +1,314 @@ +--- +name: render-monitor +description: Monitor Render services in real-time. Check health, performance metrics, logs, and resource usage. Use when users want to check service status, view metrics, monitor performance, or verify deployments are healthy. +license: MIT +compatibility: Requires Render MCP tools or CLI +metadata: + author: Render + version: "1.0.0" + category: monitoring +--- + +# Monitor Render Services + +Real-time monitoring of Render services including health checks, performance metrics, and logs. + +## When to Use This Skill + +Activate this skill when users want to: +- Check if services are healthy +- View performance metrics +- Monitor logs +- Verify a deployment is working +- Investigate slow performance +- Check database health + +## Render Access + +Before reading service state, logs, metrics, or database health, follow `references/render-access.md` to establish access and verify the intended workspace. Prefer MCP when available; the CLI can provide service status and logs, while metrics and database queries require MCP. + +Before interpreting deploy or health-check state, read `references/deployments.md`. + +--- + +## Quick Health Check + +Run these 5 checks to assess service health: + +``` +# 1. Check service status +list_services() + +# 2. Check latest deploy +list_deploys(serviceId: "", limit: 1) + +# 3. Check for errors +list_logs(resource: [""], level: ["error"], limit: 20) + +# 4. Check resource usage +get_metrics(resourceId: "", metricTypes: ["cpu_usage", "memory_usage"]) + +# 5. Check latency +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.95) +``` + +--- + +## Service Health + +### Check Status + +``` +list_services() +``` + +``` +get_service(serviceId: "") +``` + +### Check Deployments + +``` +list_deploys(serviceId: "", limit: 5) +``` + +Follow `references/deployments.md` to interpret asynchronous and terminal states, identify the specific deploy, and verify the workload after it becomes live. + +### Check Errors + +``` +list_logs(resource: [""], level: ["error"], limit: 50) +``` + +``` +list_logs(resource: [""], statusCode: ["500", "502", "503"], limit: 50) +``` + +--- + +## Performance Metrics + +### CPU & Memory + +``` +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage", "memory_usage", "cpu_limit", "memory_limit"] +) +``` + +| Metric | Healthy | Warning | Critical | +|--------|---------|---------|----------| +| CPU | <70% | 70-85% | >85% | +| Memory | <80% | 80-90% | >90% | + +### HTTP Latency + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpLatencyQuantile: 0.95 +) +``` + +| p95 Latency | Status | +|-------------|--------| +| <200ms | Excellent | +| 200-500ms | Good | +| 500ms-1s | Concerning | +| >1s | Problem | + +### Request Count + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_request_count"] +) +``` + +### Filter by Endpoint + +``` +get_metrics( + resourceId: "", + metricTypes: ["http_latency"], + httpPath: "/api/users" +) +``` + +Detailed metrics guide: [references/metrics-guide.md](references/metrics-guide.md) + +--- + +## Database Monitoring + +### PostgreSQL Status + +``` +list_postgres_instances() +get_postgres(postgresId: "") +``` + +### Connection Count + +``` +get_metrics(resourceId: "", metricTypes: ["active_connections"]) +``` + +### Query Database + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT state, count(*) FROM pg_stat_activity GROUP BY state" +) +``` + +### Find Slow Queries + +``` +query_render_postgres( + postgresId: "", + sql: "SELECT query, mean_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10" +) +``` + +### Key-Value Store + +``` +list_key_value() +get_key_value(keyValueId: "") +``` + +--- + +## Log Monitoring + +### Recent Logs + +``` +list_logs(resource: [""], limit: 100) +``` + +### Error Logs + +``` +list_logs(resource: [""], level: ["error"], limit: 50) +``` + +### Search Logs + +``` +list_logs(resource: [""], text: ["timeout", "error"], limit: 50) +``` + +### Filter by Time + +``` +list_logs( + resource: [""], + startTime: "2024-01-15T10:00:00Z", + endTime: "2024-01-15T11:00:00Z" +) +``` + +### Stream Logs (CLI) + +```bash +render logs -r --tail -o text +``` + +--- + +## Quick Reference + +### MCP Tools + +``` +# Services +list_services() +get_service(serviceId: "") +list_deploys(serviceId: "", limit: 5) + +# Logs +list_logs(resource: [""], level: ["error"], limit: 100) +list_logs(resource: [""], text: ["search"], limit: 50) + +# Metrics +get_metrics(resourceId: "", metricTypes: ["cpu_usage", "memory_usage"]) +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.95) +get_metrics(resourceId: "", metricTypes: ["http_request_count"]) + +# Database +list_postgres_instances() +get_postgres(postgresId: "") +query_render_postgres(postgresId: "", sql: "SELECT ...") +get_metrics(resourceId: "", metricTypes: ["active_connections"]) + +# Key-Value +list_key_value() +get_key_value(keyValueId: "") +``` + +### CLI Commands (Fallback) + +Use these if MCP tools are unavailable: + +```bash +# Service status +render services -o json +render services instances + +# Deployments +render deploys list -o json + +# Logs +render logs -r --tail -o text # Stream logs +render logs -r --level error -o json # Error logs +render logs -r --type deploy -o json # Build logs + +# Database +render psql # Connect to PostgreSQL + +# SSH for live debugging +render ssh +``` + +### Healthy Service Indicators + +| Indicator | Healthy | Warning | Critical | +|-----------|---------|---------|----------| +| Error Rate | <0.1% | 0.1-1% | >1% | +| p95 Latency | <500ms | 500ms-2s | >2s | +| CPU Usage | <70% | 70-90% | >90% | +| Memory Usage | <80% | 80-95% | >95% | + +--- + +## References + +- **Render access:** [references/render-access.md](references/render-access.md) +- **Compute plans:** [references/compute-plans.md](references/compute-plans.md) +- **Deployments:** [references/deployments.md](references/deployments.md) +- **Metrics guide:** [references/metrics-guide.md](references/metrics-guide.md) + +## Related Skills + +- **render-deploy** — Deploy new applications to Render +- **render-debug** — Diagnose and fix deployment failures +- **render-mcp** — MCP server setup and capability discovery + + +## Current documentation retrieval + +Whenever this skill directs you to consult current Render documentation: + +1. Retrieve the linked Markdown document directly with an available URL-fetching tool or HTTP client, such as `curl`. Do not substitute web-search summaries for the document. +2. Confirm that retrieval succeeded and returned the expected document, then read its contents. Saving a file or printing its path is not sufficient. +3. If the request fails or your tool cannot read the Markdown response, open and read the linked HTML version instead. +4. If neither version can be retrieved, disclose that the current reference is unavailable and follow any topic-specific fallback in the skill. Use bundled guidance only for stable constraints, and do not guess at changeable platform details. + +When a task requires multiple references, apply this workflow to each one and distinguish the documents you verified from those that remain unavailable. + diff --git a/.agents/skills/render-monitor/references/compute-plans.md b/.agents/skills/render-monitor/references/compute-plans.md new file mode 100644 index 0000000..5d0ccc1 --- /dev/null +++ b/.agents/skills/render-monitor/references/compute-plans.md @@ -0,0 +1,23 @@ + +## Compute plans + +A compute plan determines the CPU and RAM available to each instance of a Render service. Use **compute plan**, not the former term **instance type**. Do not confuse a service's compute plan with its workspace plan, which controls account-level features and limits. + +Compute plans differ by service type: + +- Web services, private services, background workers, and cron jobs use CPU-and-memory plan IDs such as `0.5c-512mb` and `1c-2g`. +- Render Postgres has its own plan catalog and connection limits. +- Render Key Value uses memory-based plan IDs such as `256mb` and `1g`. +- Workflow tasks select a compute plan in application code; a Workflow service does not set a Blueprint `plan`. +- Static sites do not have compute plans. + +Legacy plan names such as `starter`, `standard`, and `pro` remain valid in Render tooling, including Blueprints and API requests. For new configuration, prefer the current plan ID when the selected configuration surface accepts it. Before passing a plan to an API, MCP tool, or CLI command, inspect that operation's current schema or help and use one of its accepted values; the compute-plan reference describes the product catalog, not every tool version's input contract. Do not rename an existing legacy plan merely for consistency unless the user asks for that change. + +Do not rely on a memorized plan catalog. When a task depends on current plan IDs, specifications, defaults, availability, or pricing, fetch the canonical compute-plan reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/compute-plans.md) or its [HTML version](https://render.com/docs/compute-plans). + +Read the section for the relevant service type. If the document cannot be fetched, do not guess at current plan details. Preserve an existing valid plan where possible, or explain that the plan must be confirmed in the Render Dashboard or current documentation. + +When estimating capacity or cost, remember that every instance of a scaled service uses the selected compute plan and is billed accordingly. Changing the compute plan for Render Postgres, Render Key Value, or a service with an attached persistent disk requires brief downtime; other services normally apply the change with a zero-downtime deploy. + diff --git a/.agents/skills/render-monitor/references/deployments.md b/.agents/skills/render-monitor/references/deployments.md new file mode 100644 index 0000000..5ca9905 --- /dev/null +++ b/.agents/skills/render-monitor/references/deployments.md @@ -0,0 +1,50 @@ + +## Deployments and health checks + +A Render deploy is asynchronous. A successful trigger means only that Render accepted or queued the deploy; it does not mean the new version is live. Before triggering a deploy, confirm the workspace, service, intended source commit or image, and current live deploy. Capture the new deploy ID, monitor it to a terminal state, and do not report success until its status is `live` and the deployed workload has been verified. + +Before configuring or troubleshooting deployments and health checks, fetch the current Render references: + +- [deploys.md](https://render.com/docs/deploys.md) (HTML: ) +- [health-checks.md](https://render.com/docs/health-checks.md) (HTML: ) + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read both references. + +Read the relevant sections of both documents. Confirm current service-type support, command timeouts, health-check thresholds, rollout behavior, and configuration syntax rather than relying on remembered values. + +Automatic deployment behavior depends on the service's source and settings. A service linked to a branch through a connected Git provider can deploy on each commit, wait for supported CI checks, or require manual triggers. Services that pull a prebuilt image and services linked by a public Git repository URL require manual deploys; moving a mutable image tag does not itself trigger one. When manually deploying a historical commit, verify whether that trigger method changes automatic-deploy settings. If automatic deploys remain enabled, a later branch update can replace the selected commit. + +The normal lifecycle is build command, optional pre-deploy command, then start command and readiness checks. If a command fails or times out, the deploy fails and later steps do not run. A pre-deploy command runs after the build on a separate instance before the new version is deployed. Neither the build nor pre-deploy instance can access an attached persistent disk, and pre-deploy filesystem changes do not carry into the running service. Use pre-deploy for release tasks such as database migrations, not for producing runtime artifacts. Pre-deploy commands are supported for paid web services, private services, and background workers. + +Render normally deploys services without downtime by starting the new version before retiring the current one. Web and private services continue routing traffic to the current instances until the new instances are ready. Multi-instance services roll out one instance at a time; if a replacement does not become healthy, Render cancels the rollout and retains or restores the previous version. Attaching a persistent disk disables zero-downtime deploys, so plan explicitly for an interruption. + +A workflow deployment has a different completion model. It builds and caches the image used by future task runs and includes a task-registration step, but it does not execute those tasks. After a workflow deploy succeeds, verify that the expected task definitions are registered. Trigger and monitor a task run separately only when execution is intended. For workflow-specific deployment behavior, fetch the current workflow overview: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/workflows.md) or its [HTML version](https://render.com/docs/workflows). + +Health checks apply to web services and private services. Both use TCP socket checks by default. Only web services support a configured HTTP health-check path. Render sends an HTTP `GET`; any `2xx` or `3xx` response received within five seconds succeeds, while other status codes, timeouts, and connection failures fail. Private services support TCP checks only. + +For a new deploy, all new instances must pass their checks at the same time within the current readiness window, documented as 15 minutes, before Render routes traffic to them. For a running service, consecutive failures currently remove an instance from routing after 15 seconds and restart it after 60 seconds. Treat these thresholds as platform behavior, not user-tunable health-check interval settings, and verify them in the fetched reference before relying on exact timing. + +Design an HTTP health endpoint to represent readiness for production traffic. Keep it fast and side-effect free. Check critical dependencies only when losing that dependency should make the entire instance unavailable; otherwise a transient dependency failure can unnecessarily remove healthy application capacity. Verify the configured path, response status, response time, listening port, and `0.0.0.0` binding when checks fail. + +After traffic moves, Render gives the previous instance a drain period, then sends `SIGTERM`. The application should stop accepting new work, finish or safely abandon in-flight work, close connections, and exit within its shutdown delay. Ensure the actual application process receives the signal: container entrypoints and shell wrappers should use `exec` or explicitly forward signals. Render sends `SIGKILL` if the process remains running after the delay. The documented default shutdown delay is 30 seconds and the usual maximum is 300 seconds, but support varies by service configuration; confirm the current reference and Blueprint or API validation before setting `maxShutdownDelaySeconds`. + +A service restart is a special deploy of the same commit and user-defined environment-variable values as the current running instance. It does not incorporate configuration changes saved after that deploy. Use a standard deploy when pending configuration must take effect. + +Only one deploy runs at a time for a service. A workspace's overlapping-deploy policy determines whether a new trigger waits or cancels the in-progress deploy. Do not assume the policy or wait for every intermediate revision: inspect the workspace setting and identify the deploy that actually became live. + +Treat rollback as a new deploy based on a retained previous build artifact, not as restoration of the entire service to an earlier point in time. It does not reverse database migrations, messages, external writes, or other side effects from the release, so confirm that the previous application version remains compatible with current external state. Disks and their data are not rolled back, some settings continue using current configuration, mutable image tags can resolve to a different image, and eligible artifacts are retained only for a limited period. Before rolling back, fetch the current rollback reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/rollbacks.md) or its [HTML version](https://render.com/docs/rollbacks). + +Read which configuration comes from the target deploy and which remains current. After the rollback is created, inspect the service's resulting automatic-deploy setting instead of assuming whether it remains enabled, and deliberately restore the intended setting after the underlying issue is resolved. + +Deploy hooks are secret credentials that authorize deploys. Never print, commit, or expose their full URLs. Before using one, fetch the current deploy-hook reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/deploy-hooks.md) or its [HTML version](https://render.com/docs/deploy-hooks). + +Distinguish an immediately started deploy from a queued one, and continue monitoring the resulting deploy rather than treating the HTTP response as completion. + +After a deploy becomes live, verify the behavior appropriate to the service type: make a request to a web or private service, confirm a worker is processing work, confirm a cron job or workflow invocation completes, and inspect recent runtime logs for new errors. If a deploy fails, diagnose the first failed lifecycle stage before retrying. + diff --git a/.agents/skills/render-monitor/references/metrics-guide.md b/.agents/skills/render-monitor/references/metrics-guide.md new file mode 100644 index 0000000..6af9a7f --- /dev/null +++ b/.agents/skills/render-monitor/references/metrics-guide.md @@ -0,0 +1,297 @@ +# Render Metrics Interpretation Guide + +Comprehensive guide to understanding and acting on Render service metrics. + +## Available Metrics + +| Metric | Description | Applicable Resources | +|--------|-------------|---------------------| +| `cpu_usage` | CPU utilization percentage | Services, Postgres, KV | +| `cpu_limit` | CPU limit/allocation | Services | +| `cpu_target` | Autoscaling CPU target | Services | +| `memory_usage` | Memory utilization | Services, Postgres, KV | +| `memory_limit` | Memory limit/allocation | Services | +| `memory_target` | Autoscaling memory target | Services | +| `http_request_count` | Number of HTTP requests | Services | +| `http_latency` | Response time (quantile-based) | Services | +| `bandwidth_usage` | Network bandwidth used | Services | +| `instance_count` | Number of running instances | Services | +| `active_connections` | Database connections | Postgres, KV | + +--- + +## CPU Metrics + +### cpu_usage + +**What it measures:** Percentage of allocated CPU being used. + +Interpret CPU utilization relative to the service's selected compute plan and workload. Use [compute-plans.md](compute-plans.md) when current CPU specifications matter instead of inferring them from legacy plan names. + +**Actions for high CPU:** +1. Profile code for inefficient operations +2. Add caching for repeated computations +3. Optimize database queries +4. Upgrade to a larger compute plan +5. Enable autoscaling + +### cpu_limit + +**What it measures:** Maximum CPU allocated to the service. + +**Use case:** Compare `cpu_usage` to `cpu_limit` to determine if throttling is occurring. + +**Formula:** `throttle_risk = cpu_usage / cpu_limit` +- `>0.9` = High throttling risk +- `>0.8` = Moderate risk +- `<0.7` = Safe + +--- + +## Memory Metrics + +### memory_usage + +**What it measures:** Memory being used by the service in bytes. + +Interpret memory relative to the resource's reported limit rather than mapping legacy plan names to memorized byte values. Use [compute-plans.md](compute-plans.md) when current memory specifications matter. + +**Actions for high memory:** +1. Profile for memory leaks +2. Reduce in-memory caching +3. Process data in streams/chunks +4. Optimize data structures +5. Upgrade plan + +### memory_limit + +**What it measures:** Maximum memory allocated. + +**OOM Risk Formula:** `oom_risk = memory_usage / memory_limit` +- `>0.95` = Imminent OOM +- `>0.90` = High risk +- `>0.80` = Moderate risk +- `<0.70` = Safe + +--- + +## HTTP Metrics + +### http_latency + +**What it measures:** Response time at a given percentile. + +**Common quantiles:** +- `0.5` (p50/median) - Typical user experience +- `0.95` (p95) - Most users' worst experience +- `0.99` (p99) - Tail latency, outliers + +**Healthy latency targets:** +| Endpoint Type | p50 | p95 | p99 | +|--------------|-----|-----|-----| +| Static content | <50ms | <100ms | <200ms | +| API (simple) | <100ms | <300ms | <500ms | +| API (complex) | <200ms | <500ms | <1s | +| Database-heavy | <300ms | <1s | <2s | + +**Actions for high latency:** +1. Add database indexes +2. Implement caching with Key Value +3. Optimize N+1 queries +4. Use connection pooling +5. Add CDN for static assets +6. Scale horizontally + +### http_request_count + +**What it measures:** Number of HTTP requests received. + +**Use cases:** +- Detect traffic spikes +- Correlate with error rates +- Capacity planning +- Usage billing estimation + +**Aggregation options:** +- By `host` - Traffic per domain +- By `statusCode` - Success vs error rates + +**Calculating error rate:** +``` +error_rate = (5xx_requests / total_requests) * 100 +``` + +Target: <0.1% error rate + +--- + +## Instance Metrics + +### instance_count + +**What it measures:** Number of running service instances. + +**Interpreting changes:** +- Increasing: Autoscaling up (good if traffic increasing) +- Decreasing: Autoscaling down (cost optimization) +- Fluctuating: Possible instability or aggressive scaling +- Stuck at 1: May not have autoscaling enabled + +**Autoscaling health check:** +Compare `instance_count` trends with `cpu_usage` and `http_request_count`: +- CPU high + instances not scaling = Check autoscaling config +- Instances scaling + latency still high = Hit max instances or DB bottleneck + +--- + +## Database Metrics + +### active_connections + +**What it measures:** Number of active database connections. + +Connection limits vary by Postgres compute plan. Fetch the current limit through [compute-plans.md](compute-plans.md), then compare active connections with that limit. + +**Actions for high connections:** +1. Implement connection pooling (PgBouncer) +2. Close idle connections +3. Reduce connection timeouts +4. Fix connection leaks in code +5. Upgrade the database compute plan + +### Database CPU/Memory + +Same interpretation as service metrics, but: +- High CPU often indicates slow queries +- High memory often indicates large result sets or missing indexes + +--- + +## Bandwidth Metrics + +### bandwidth_usage + +**What it measures:** Network data transfer (egress). + +**Considerations:** +- Spikes correlate with large responses or file downloads +- Sustained high bandwidth may indicate inefficient API design +- Consider compression (gzip/brotli) to reduce bandwidth + +**Cost implications:** +- Render includes bandwidth in plans +- Usage beyond the included allowance can incur additional cost; confirm current details at [Render pricing](https://render.com/pricing) + +--- + +## Time-Based Analysis + +### Choosing Time Ranges + +| Analysis Type | Start Time | Resolution | +|--------------|------------|------------| +| Real-time | 5 minutes ago | 30 seconds | +| Recent issue | 1 hour ago | 1 minute | +| Trend analysis | 24 hours ago | 5 minutes | +| Weekly pattern | 7 days ago | 1 hour | + +### Correlating Events + +When investigating issues, align metrics with: +1. Deploy times (`list_deploys`) +2. Error log timestamps (`list_logs`) +3. Traffic patterns (`http_request_count`) +4. External events (marketing campaigns, etc.) + +--- + +## Alert Thresholds Recommendations + +### Critical Alerts (Immediate Action) + +| Metric | Threshold | Action | +|--------|-----------|--------| +| Error rate | >5% | Page on-call | +| p99 latency | >5s | Investigate immediately | +| Memory usage | >95% | Scale or restart | +| CPU usage | >95% sustained | Scale up | +| DB connections | >95% max | Add pooling | + +### Warning Alerts (Investigate Soon) + +| Metric | Threshold | Action | +|--------|-----------|--------| +| Error rate | >1% | Investigate within 1 hour | +| p95 latency | >2s | Review slow endpoints | +| Memory usage | >85% | Plan capacity increase | +| CPU usage | >80% sustained | Consider optimization | +| DB connections | >80% max | Review connection usage | + +--- + +## Metric Query Examples + +### Service Health Dashboard + +``` +# CPU trend +get_metrics(resourceId: "", metricTypes: ["cpu_usage"], resolution: 300) + +# Memory trend +get_metrics(resourceId: "", metricTypes: ["memory_usage"], resolution: 300) + +# Request rate +get_metrics(resourceId: "", metricTypes: ["http_request_count"], resolution: 60) + +# Latency percentiles +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.5) +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.95) +get_metrics(resourceId: "", metricTypes: ["http_latency"], httpLatencyQuantile: 0.99) +``` + +### Capacity Planning + +``` +# Peak CPU over last 24h +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage"], + cpuUsageAggregationMethod: "MAX", + startTime: "<24-hours-ago>", + resolution: 3600 +) + +# Peak memory over last 24h +get_metrics( + resourceId: "", + metricTypes: ["memory_usage"], + startTime: "<24-hours-ago>", + resolution: 3600 +) + +# Traffic patterns +get_metrics( + resourceId: "", + metricTypes: ["http_request_count"], + startTime: "<7-days-ago>", + resolution: 3600 +) +``` + +### Database Performance + +``` +# Connection usage +get_metrics( + resourceId: "", + metricTypes: ["active_connections"], + startTime: "<1-hour-ago>" +) + +# Database CPU (indicates query load) +get_metrics( + resourceId: "", + metricTypes: ["cpu_usage"], + startTime: "<1-hour-ago>" +) +``` diff --git a/.agents/skills/render-monitor/references/render-access.md b/.agents/skills/render-monitor/references/render-access.md new file mode 100644 index 0000000..8858a61 --- /dev/null +++ b/.agents/skills/render-monitor/references/render-access.md @@ -0,0 +1,52 @@ + +## Accessing Render + +Prefer the hosted Render MCP server for structured access to Render resources when its tools are available. Use the Render CLI when MCP is unavailable or does not support the required operation, and use the Render Dashboard or API for capabilities exposed by neither. Do not assume that a remembered MCP tool or CLI command is still available; inspect the tools in the current environment or consult the current documentation. + +The hosted Render MCP server uses streamable HTTP at: + +```text +https://mcp.render.com/mcp +``` + +Official Render plugins and connectors can authenticate MCP with browser-based OAuth. Manual and non-interactive configurations can use a Render API key as a bearer token. Never write an API key or OAuth token into a repository, skill, command output, chat response, or log. Prefer the client's supported secret storage or environment-variable mechanism. If a client requires a credential in local configuration, keep that file out of version control and restrict access to it. + +Treat MCP responses as potentially sensitive even when the server attempts to minimize credential exposure. Request connection strings, credentials, secret environment variables, or other sensitive fields only when the task requires them. Do not repeat sensitive values in the response or persist them in files or logs. + +Before configuring or troubleshooting MCP, fetch the current setup and capability reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/mcp-server.md) or its [HTML version](https://render.com/docs/mcp-server). + +Read the relevant client setup, supported-actions, and limitations sections. Prefer the hosted server unless the user's environment requires a local MCP server. After installing, updating, or reconfiguring an MCP integration, reload the client as required and verify the connection with a read-only operation such as listing services. + +Render resource operations are workspace-scoped. With MCP, list workspaces when needed to establish the intended workspace, then pass its confirmed `workspaceId` on every related resource call that supports it. Reuse the workspace already confirmed in the conversation. Implicit session-based workspace selection is deprecated and can be lost on reconnect; do not rely on it when explicit targeting is available. For older tools without `workspaceId`, inspect their current workspace-selection mechanism and verify the selected workspace before proceeding. + +For CLI operations, check the active workspace before reading or changing resources. If the intended workspace is ambiguous, list the available workspaces and have the user identify the correct one. Do not silently switch workspace context or infer it from a resource name. Commands for authentication, help, CLI configuration, and workspace discovery or selection do not require an already selected workspace. + +For interactive CLI use, authenticate with `render login`. For automation, use a securely stored `RENDER_API_KEY`; an API key takes precedence over a saved CLI token. Verify CLI access and the active workspace with read-only commands before operating on resources: + +```bash +render whoami --output json +render workspace current --output json +``` + +For CLI installation, authentication, workspace setup, and usage patterns, fetch the current CLI overview: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/cli.md) or its [HTML version](https://render.com/docs/cli). + +For exact command syntax and flags, prefer the help text from the installed CLI because it matches the version being used: + +```bash +render help +``` + +The published CLI command reference is generated automatically from the CLI's help text. Use it to browse the full command surface or when the CLI is not installed: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/cli-reference.md) or its [HTML version](https://render.com/docs/cli-reference). + +When an agent or automation invokes the CLI, select a non-interactive output format such as `--output json`, `--output yaml`, or `--output text` so results can be inspected reliably. The global `--confirm` flag skips confirmation prompts; use it for a mutating command only after that mutation is authorized. It is an execution convenience, not permission to perform the action. + +Authentication establishes access; it does not establish user authorization for every available action. Use read-only discovery to resolve workspace, resource identity, and current state before a mutation. Perform changes only when they are within the user's requested scope, and retain normal approval requirements for consequential operations such as creation, configuration changes, deploys, restarts, scaling, or deletion. + +When authentication or connectivity fails, report which access path failed, preserve the underlying error without exposing credentials, and either use an available supported fallback or explain what the user must configure before the task can continue. + diff --git a/.agents/skills/render-web-services/SKILL.md b/.agents/skills/render-web-services/SKILL.md new file mode 100644 index 0000000..4da3686 --- /dev/null +++ b/.agents/skills/render-web-services/SKILL.md @@ -0,0 +1,117 @@ +--- +name: render-web-services +description: >- + Configures Render web services—port binding, TLS, health checks, custom + domains, auto-deploy, PR previews, persistent disks, and deploy lifecycle. + Use when the user needs to set up a web service, fix health check failures, + add a custom domain, configure zero-downtime deploys, or troubleshoot port + binding issues. +license: MIT +compatibility: Render web services (native runtimes or Docker) +metadata: + author: Render + version: "1.0.0" + category: compute +--- + +# Render Web Services + +This skill covers **Web Service** behavior on Render: how traffic reaches your process, how deploys go live, and how optional features (domains, disks, auto-deploy) interact. Use it alongside Blueprint and networking skills when wiring `render.yaml` or Dashboard settings. + +## When to Use + +- Configuring or debugging **port binding**, **PORT**, or **multi-port** web services +- **TLS/HTTPS** expectations at the edge vs inside the container +- **Health checks** blocking or rolling back deploys +- **Custom domains**, DNS, and certificate provisioning +- **Auto-deploy**, **CI-gated deploys**, and **PR preview** generation +- **Persistent disks** and their impact on scaling and zero-downtime +- **Deploy lifecycle**: build, pre-deploy, swap, drain, **rollback**, shutdown delay + +Deeper patterns live under `references/` (health checks, domains, deploy phases). + +Before configuring or troubleshooting deploys and health checks, read `references/deployments.md`. +Before attaching or changing a persistent disk, read `references/persistent-disks.md`. +Before configuring or troubleshooting private connectivity or additional ports, read `references/private-networking.md`. + +## Port Binding + +- Listen on **`0.0.0.0`** (all interfaces). Binding only to **`localhost`** or **`127.0.0.1`** prevents Render’s proxy from reaching your app. +- Use the **`PORT`** environment variable for the HTTP listen port. Render sets it for you; the **default is often `10000`** and you can change the configured value in the service **Settings** in the Dashboard. +- **Reserved ports** (do **not** bind your application to these for normal traffic): **`18012`**, **`18013`**, **`19099`**. + +### Multi-port Web Services + +- Only **one** port receives **public** HTTP traffic: the port aligned with **`PORT`**. +- **Additional** open ports are reachable on Render’s **private network** only (not from the public internet through the same public URL pattern). + +## TLS and HTTPS + +- **TLS terminates at Render’s edge.** The edge speaks HTTPS to clients; your process typically receives **plain HTTP** on `PORT`. +- **HTTPS redirect** for clients is handled by the platform; users hitting HTTP are redirected appropriately at the edge. +- **Do not terminate TLS inside the app** for the primary public listener unless you have a rare, explicit need—standard Web Services assume HTTP behind the proxy. + +## Health Checks + +Follow `references/deployments.md` for current platform behavior. For endpoint implementations and common failure patterns, see `references/health-check-patterns.md`. + +## Custom Domains + +- Point DNS with a **CNAME** to **`[service-name].onrender.com`** (use your service’s hostname from the Dashboard). +- Render **automatically provisions and renews** TLS certificates for verified domains. +- **Apex** (root) domains need provider-specific **CNAME-like** or flattened records where plain CNAME at `@` is unsupported. +- **Wildcard** domains (e.g. `*.example.com`) are supported when configured and verified. +- Multiple custom domains per service are supported; Blueprints can list them under the **`domains`** field. + +See `references/custom-domains.md` for Dashboard steps, verification, and troubleshooting. + +## Auto-Deploy and PR Previews + +- Follow `references/deployments.md` for auto-deploy behavior and manual triggers. +- **PR previews** are configured under Blueprint **`previews.generation`** (and related preview settings); generation behavior depends on repo integration and plan. + +## Persistent Disks + +- A disk-backed web service stays **single-instance** and cannot scale horizontally. +- Attaching a disk disables **zero-downtime deploys**. +- The disk is available only to the running service, not during builds or pre-deploy commands. +- If the workload needs horizontal scaling or uninterrupted deploys, use shared external storage instead of a service-attached disk. +- Follow `references/persistent-disks.md` for current support, configuration, mount-path, runtime-access, sizing, and snapshot behavior. + +## Deploy Lifecycle + +For paid web services, use `preDeployCommand` for database migrations and other release tasks that must succeed before the new version receives traffic. It runs after the build on separate compute; if it fails, the deploy is canceled and the previous live version continues serving. Follow `references/deployments.md` for the full build, readiness, traffic-switching, draining, rollback, restart, and deploy-hook behavior. + +## Free Tier Notes + +Free Web Services have **separate limits**: services **spin down after inactivity** (cold starts on the next request), and they do not support scaling beyond a single instance or persistent disks. Treat free-tier behavior as distinct from paid Web Service defaults when advising on uptime and scaling. + +## References + +| Topic | File | +|--------|------| +| Health check design, timeouts, pitfalls | `references/health-check-patterns.md` | +| Domains, DNS, TLS verification | `references/custom-domains.md` | +| Deploy lifecycle, health checks, rollback, triggers | `references/deployments.md` | +| Persistent disk constraints and configuration | `references/persistent-disks.md` | +| Private-network addressing, ports, discovery, and troubleshooting | `references/private-networking.md` | + +## Related Skills + +- **render-deploy** — Blueprints, first-time deploy, `render.yaml` structure +- **render-docker** — Docker-based Web Services and image/runtime details +- **render-networking** — Private network, internal URLs, multi-port private listeners +- **render-scaling** — Instance counts, plans, and scaling constraints (including disk interactions) + + +## Current documentation retrieval + +Whenever this skill directs you to consult current Render documentation: + +1. Retrieve the linked Markdown document directly with an available URL-fetching tool or HTTP client, such as `curl`. Do not substitute web-search summaries for the document. +2. Confirm that retrieval succeeded and returned the expected document, then read its contents. Saving a file or printing its path is not sufficient. +3. If the request fails or your tool cannot read the Markdown response, open and read the linked HTML version instead. +4. If neither version can be retrieved, disclose that the current reference is unavailable and follow any topic-specific fallback in the skill. Use bundled guidance only for stable constraints, and do not guess at changeable platform details. + +When a task requires multiple references, apply this workflow to each one and distinguish the documents you verified from those that remain unavailable. + diff --git a/.agents/skills/render-web-services/references/custom-domains.md b/.agents/skills/render-web-services/references/custom-domains.md new file mode 100644 index 0000000..3cee76e --- /dev/null +++ b/.agents/skills/render-web-services/references/custom-domains.md @@ -0,0 +1,58 @@ +# Custom domains on Render Web Services + +Custom domains let clients reach your Web Service on your own hostnames while Render terminates TLS and proxies to your app. + +## Adding a domain (Dashboard) + +1. Open the **Render Dashboard** → select the **Web Service**. +2. Go to **Settings** → **Custom Domains**. +3. Add the hostname (e.g. `www.example.com` or `api.example.com`). +4. Follow the shown **DNS** and **verification** instructions. + +## DNS: CNAME to onrender.com + +- For a **subdomain**, create a **CNAME** record pointing to your service’s Render hostname: **`[service-name].onrender.com`** (copy the exact target from the Dashboard). +- **Propagation** can take minutes to hours depending on TTL and provider caching. + +## Apex (root) domains + +Plain **CNAME at the zone apex** (`example.com`) is **not supported** by DNS RFCs at many providers. + +- Use provider features such as **ALIAS**, **ANAME**, or **CNAME flattening** that synthesize A/AAAA records from a CNAME-like target, **or** use a **redirect** subdomain (e.g. `www`) as the canonical hostname. +- Follow Render’s Dashboard guidance for the exact record type your provider needs. + +## Wildcard domains + +- You can add **wildcard** hostnames such as **`*.example.com`** when your plan and workflow support it. +- DNS must include the matching **wildcard** record per your provider’s rules; TLS certificates are provisioned after **verification**. + +## TLS certificates + +- Render **auto-provisions** certificates for verified custom domains. +- Certificates **renew automatically**; avoid serving your own cert on the public listener for standard Web Services (TLS is at the edge). + +## Verification + +- Render verifies **control** of the domain via **DNS** (and/or instructions shown in the UI). +- Until verification succeeds, the domain may not serve traffic or may show certificate warnings. + +## Multiple domains + +- **Several hostnames** can point at the **same** Web Service; add each in **Custom Domains** or list them in a Blueprint **`domains`** field as a **list of strings** (hostnames). + +Example Blueprint fragment: + +```yaml +domains: + - www.example.com + - api.example.com +``` + +## Troubleshooting + +| Issue | What to check | +|--------|----------------| +| Domain does not resolve | CNAME/ALIAS target typos; **TTL**; old records still cached | +| Certificate pending or invalid | Verification not complete; **conflicting** A/AAAA/CNAME records | +| Wrong site | CNAME points to a **different** `[service-name].onrender.com` | +| Apex not working | Provider lacks **flattening**; use **www** or ALIAS/ANAME | diff --git a/.agents/skills/render-web-services/references/deployments.md b/.agents/skills/render-web-services/references/deployments.md new file mode 100644 index 0000000..295e0b6 --- /dev/null +++ b/.agents/skills/render-web-services/references/deployments.md @@ -0,0 +1,58 @@ + +## Deployments and health checks + +A Render deploy is asynchronous. A successful trigger means only that Render accepted or queued the deploy; it does not mean the new version is live. Before triggering a deploy, confirm the workspace, service, intended source commit or image, and current live deploy. Capture the new deploy ID, monitor it to a terminal state, and do not report success until its status is `live` and the deployed workload has been verified. + +Before configuring or troubleshooting deployments and health checks, fetch the current Render references: + +- [deploys.md](https://render.com/docs/deploys.md) (HTML: ) +- [health-checks.md](https://render.com/docs/health-checks.md) (HTML: ) + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read both references. + +Read the relevant sections of both documents. Confirm current service-type support, command timeouts, health-check thresholds, rollout behavior, and configuration syntax rather than relying on remembered values. + +Automatic deployment behavior depends on the service's source and settings. A service linked to a branch through a connected Git provider can deploy on each commit, wait for supported CI checks, or require manual triggers. Services that pull a prebuilt image and services linked by a public Git repository URL require manual deploys; moving a mutable image tag does not itself trigger one. When manually deploying a historical commit, verify whether that trigger method changes automatic-deploy settings. If automatic deploys remain enabled, a later branch update can replace the selected commit. + +The normal lifecycle is build command, optional pre-deploy command, then start command and readiness checks. If a command fails or times out, the deploy fails and later steps do not run. A pre-deploy command runs after the build on a separate instance before the new version is deployed. Neither the build nor pre-deploy instance can access an attached persistent disk, and pre-deploy filesystem changes do not carry into the running service. Use pre-deploy for release tasks such as database migrations, not for producing runtime artifacts. Pre-deploy commands are supported for paid web services, private services, and background workers. + +Render normally deploys services without downtime by starting the new version before retiring the current one. Web and private services continue routing traffic to the current instances until the new instances are ready. Multi-instance services roll out one instance at a time; if a replacement does not become healthy, Render cancels the rollout and retains or restores the previous version. Attaching a persistent disk disables zero-downtime deploys, so plan explicitly for an interruption. + +A workflow deployment has a different completion model. It builds and caches the image used by future task runs and includes a task-registration step, but it does not execute those tasks. After a workflow deploy succeeds, verify that the expected task definitions are registered. Trigger and monitor a task run separately only when execution is intended. For workflow-specific deployment behavior, fetch the current workflow overview: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/workflows.md) or its [HTML version](https://render.com/docs/workflows). + +Health checks apply to web services and private services. Both use TCP socket checks by default. Only web services support a configured HTTP health-check path. Render sends an HTTP `GET`; any `2xx` or `3xx` response received within five seconds succeeds, while other status codes, timeouts, and connection failures fail. Private services support TCP checks only. + +For a new deploy, all new instances must pass their checks at the same time within the current readiness window, documented as 15 minutes, before Render routes traffic to them. For a running service, consecutive failures currently remove an instance from routing after 15 seconds and restart it after 60 seconds. Treat these thresholds as platform behavior, not user-tunable health-check interval settings, and verify them in the fetched reference before relying on exact timing. + +Design an HTTP health endpoint to represent readiness for production traffic. Keep it fast and side-effect free. Check critical dependencies only when losing that dependency should make the entire instance unavailable; otherwise a transient dependency failure can unnecessarily remove healthy application capacity. Verify the configured path, response status, response time, listening port, and `0.0.0.0` binding when checks fail. + +After traffic moves, Render gives the previous instance a drain period, then sends `SIGTERM`. The application should stop accepting new work, finish or safely abandon in-flight work, close connections, and exit within its shutdown delay. Ensure the actual application process receives the signal: container entrypoints and shell wrappers should use `exec` or explicitly forward signals. Render sends `SIGKILL` if the process remains running after the delay. The documented default shutdown delay is 30 seconds and the usual maximum is 300 seconds, but support varies by service configuration; confirm the current reference and Blueprint or API validation before setting `maxShutdownDelaySeconds`. + +A service restart is a special deploy of the same commit and user-defined environment-variable values as the current running instance. It does not incorporate configuration changes saved after that deploy. Use a standard deploy when pending configuration must take effect. + +Only one deploy runs at a time for a service. A workspace's overlapping-deploy policy determines whether a new trigger waits or cancels the in-progress deploy. Do not assume the policy or wait for every intermediate revision: inspect the workspace setting and identify the deploy that actually became live. + +Treat rollback as a new deploy based on a retained previous build artifact, not as restoration of the entire service to an earlier point in time. It does not reverse database migrations, messages, external writes, or other side effects from the release, so confirm that the previous application version remains compatible with current external state. Disks and their data are not rolled back, some settings continue using current configuration, mutable image tags can resolve to a different image, and eligible artifacts are retained only for a limited period. Before rolling back, fetch the current rollback reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/rollbacks.md) or its [HTML version](https://render.com/docs/rollbacks). + +Read which configuration comes from the target deploy and which remains current. After the rollback is created, inspect the service's resulting automatic-deploy setting instead of assuming whether it remains enabled, and deliberately restore the intended setting after the underlying issue is resolved. + +Deploy hooks are secret credentials that authorize deploys. Never print, commit, or expose their full URLs. Before using one, fetch the current deploy-hook reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/deploy-hooks.md) or its [HTML version](https://render.com/docs/deploy-hooks). + +Distinguish an immediately started deploy from a queued one, and continue monitoring the resulting deploy rather than treating the HTTP response as completion. + +After a deploy becomes live, verify the behavior appropriate to the service type: make a request to a web or private service, confirm a worker is processing work, confirm a cron job or workflow invocation completes, and inspect recent runtime logs for new errors. If a deploy fails, diagnose the first failed lifecycle stage before retrying. + + +## Web-service-specific guidance + +- Pair CI-gated automatic deploys with branch protection so the required checks match the repository's intended release gates. +- Configure build filters when only changes to particular paths should trigger a build. Fetch the current Blueprint specification before choosing the YAML fields. +- PR previews are configured with the current Blueprint preview settings and require a connected repository. Fetch the current Blueprint specification before writing that configuration. +- For long-lived requests such as large uploads or streams, choose a shutdown delay that gives in-flight requests time to finish. A shorter delay replaces instances faster but can interrupt more requests. +- Manual deploys can be triggered from the Dashboard or supported CLI, API, and hook flows. Consult the current CLI command reference or local `render deploys --help` output before constructing a command. diff --git a/.agents/skills/render-web-services/references/health-check-patterns.md b/.agents/skills/render-web-services/references/health-check-patterns.md new file mode 100644 index 0000000..56754c8 --- /dev/null +++ b/.agents/skills/render-web-services/references/health-check-patterns.md @@ -0,0 +1,72 @@ +# Health check patterns for Render Web Services + +Read [deployments.md](deployments.md) first for current Render health-check behavior, timing, and deploy effects. This reference focuses on application endpoint design. + +## Endpoint design + +- Prefer a **dedicated** path such as **`/health`** or **`/healthz`**. +- Return **`200 OK`** with a small body or empty body; avoid heavy work on every request. +- The path must be served by the **same process and port** that handles production traffic (i.e. whatever listens on **`PORT`**). + +### What to verify (in order of usefulness) + +1. **Application has finished starting** — routes registered, server accepting connections. +2. **Optional: critical dependencies** — e.g. can open a **database** connection or run a trivial query *if* you accept that DB blips mark the whole service unhealthy (often desirable for strict readiness). +3. Avoid equating “process alive” with “ready for traffic” if initialization is slow (migrations, cache warm-up, etc.). + +Do **not** use health checks that always return 200 before the server is actually listening on **`PORT`**. + +## Framework examples + +These are minimal illustrations; adapt paths and ports to your app. + +### Express.js (Node) + +```js +app.get("/health", (_req, res) => { + res.status(200).send("ok"); +}); +``` + +### Flask (Python) + +```python +@app.get("/health") +def health(): + return "", 200 +``` + +### Django (Python) + +```python +# urls.py +path("health", lambda r: HttpResponse(status=200)), +``` + +### Go (net/http) + +```go +http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +}) +``` + +### Rust (Actix-web) + +```rust +#[get("/health")] +async fn health() -> impl Responder { + HttpResponse::Ok().finish() +} +``` + +## Common issues + +| Symptom | Likely cause | +|--------|----------------| +| Deploy never goes live | Health path returns **4xx/5xx**, wrong path, or server not up yet | +| Connection refused | App bound to **127.0.0.1** only, or wrong **port** vs **`PORT`** | +| Intermittent failures | Timeouts too aggressive vs cold start; DB check flapping | +| Wrong service | Health path hits a different process or static file only in old deploy | + +Always confirm **`healthCheckPath`** matches a **GET** route on the service that listens on **`0.0.0.0:$PORT`**. diff --git a/.agents/skills/render-web-services/references/persistent-disks.md b/.agents/skills/render-web-services/references/persistent-disks.md new file mode 100644 index 0000000..3ba9242 --- /dev/null +++ b/.agents/skills/render-web-services/references/persistent-disks.md @@ -0,0 +1,29 @@ + +## Persistent disks + +Use this guidance only for service-attached persistent disks and for architecture or configuration decisions directly affected by them. Do not apply it to Render Postgres or Key Value storage, object storage, build caches, or ordinary ephemeral filesystem tasks. + +By default, a Render service's filesystem is ephemeral. Files created or changed at runtime are lost when the service is redeployed or restarted. Use a persistent disk only when a supported service must retain local filesystem data across those events. + +Before designing, configuring, or troubleshooting a persistent disk, fetch the current documentation: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/disks.md) or its [HTML version](https://render.com/docs/disks). + +Read the relevant sections before relying on details that can change, including supported service types, size limits and pricing, mount-path restrictions, snapshot cadence and retention, transfer methods, and current scaling or deployment limitations. If the document cannot be fetched, do not guess those details from memory. + +A persistent disk belongs to one service and is mounted at one absolute path. Only files written under that mount path persist; the rest of the service filesystem remains ephemeral. Make sure the application writes every intended durable file beneath the configured mount path. A disk is not shared storage, and another service cannot access it. + +Under the documented generally available behavior, a disk-backed service runs as a single instance and cannot use autoscaling or zero-downtime deploys. During a deploy, Render stops the existing instance before starting its replacement, so expect a short interruption. If the workload needs horizontal scaling, shared state, or stronger availability, use an external or managed datastore instead of a service-attached disk. + +The disk is available only to the running service. Builds, pre-deploy commands, and one-off jobs run on separate compute and cannot access it. Do not design a build step, pre-deploy command, or one-off job that depends on files stored on the mounted disk. + +The documented supported service types are paid web services, private services, and background workers. For other workload types, use an appropriate external datastore or reconsider the service architecture rather than assuming a disk can be attached. + +Disk capacity can be increased but not decreased. Confirm current limits and pricing in the fetched documentation, and choose capacity using observed usage plus reasonable headroom. + +Treat attaching, resizing, or restoring a disk as a stateful mutation. After attaching, verify that the service deploys successfully and that reads and writes use the mounted path. + +Snapshots are a disaster-recovery mechanism, not a substitute for application-consistent database backups. A snapshot restore replaces the entire disk; it cannot restore individual files, and it discards changes made after that snapshot. Do not use a disk snapshot to recover a custom database, because a filesystem-level snapshot can restore the database into an inconsistent or corrupted state. Use the database engine's native backup and restore tools instead. Check the current documentation before promising a particular snapshot schedule, retention period, or restore procedure. + +Mount paths must be absolute and must satisfy Render's current restrictions. Fetch the documentation instead of reproducing its forbidden-path list or runtime-specific path suggestions from memory. When declaring a disk in a Blueprint, also fetch the current Blueprint specification and follow its disk schema rather than relying on remembered syntax. + diff --git a/.agents/skills/render-web-services/references/private-networking.md b/.agents/skills/render-web-services/references/private-networking.md new file mode 100644 index 0000000..d68d6be --- /dev/null +++ b/.agents/skills/render-web-services/references/private-networking.md @@ -0,0 +1,25 @@ + +## Private networking + +Render services can communicate over a private network without traversing the public internet. Private-network peers must belong to the same workspace and run in the same region. An isolated project environment can additionally block traffic both to and from resources outside that environment, so workspace and region matching alone do not guarantee connectivity. + +Before designing, configuring, or troubleshooting private-network communication, fetch the current Render private-network reference: + +Using the documentation-retrieval workflow in the root `SKILL.md`, retrieve and read the [Markdown reference](https://render.com/docs/private-network.md) or its [HTML version](https://render.com/docs/private-network). + +Read the relevant sections. Confirm current service-type capabilities, port restrictions, environment-isolation behavior, discovery-hostname guidance, and plan requirements instead of relying on a memorized catalog. + +Web services and private services have internal hostnames and can receive private-network traffic. A private service must bind at least one port; use a background worker instead when a workload does not need to accept inbound connections. Render Postgres and Key Value instances provide internal connection URLs. Workflows, background workers, and cron jobs can initiate private-network connections but do not have an internal address for receiving them. Static sites are not on the private network. Free web services can initiate private-network connections but cannot receive them. + +Prefer the internal address or URL shown under **Connect > Internal** in the Render Dashboard. Include the protocol when the client or server requires one; an address such as `service:10000` does not by itself establish whether to use HTTP, HTTPS, or another protocol. A process that receives traffic must listen on the intended port and on an interface reachable outside its own container, such as `0.0.0.0`, rather than only on loopback. + +For Blueprint-managed connections, fetch the current Blueprint specification and use supported service or database references instead of copying a generated hostname, port, credential, or connection string. Web and private services currently expose `host`, `port`, and `hostport` properties. A Blueprint can obtain another service's discovery hostname by referencing that service's `RENDER_DISCOVERY_SERVICE` environment variable with `fromService.envVarKey`; the discovery hostname is not a service property. The fetched specification is authoritative for the syntax and supported references. + +A service can expose at most 75 ports on the private network. Ports `18012`, `18013`, and `19099` are unavailable for private-network communication. Port `10000` is not generally blocked: for a web service, private traffic to port `10000` routes to its primary HTTP server even when that server binds to another port. In that case, both port `10000` and the actual primary HTTP port route to the same server. + +Use a service's normal internal hostname for ordinary service-to-service traffic. For advanced per-instance communication, each web or private service has a discovery hostname, conventionally formed by appending `-discovery` to its internal hostname, that resolves to all active instance IP addresses. A service receives its own discovery hostname in `RENDER_DISCOVERY_SERVICE`. Use DNS APIs that honor the system resolver configuration, and do not persist resolved instance IPs because they can change between deploys. Prefer hostname-based communication unless per-instance addressing or custom load balancing is specifically required. + +When a private-network connection fails, verify the workspace, region, project-environment isolation settings, whether the destination service type accepts inbound traffic, the internal hostname or URL, protocol, port, listening interface, current deploy health, and DNS resolution. Do not substitute a public URL or expose a private service merely to bypass a private-network configuration problem. + +AWS PrivateLink is a separate Pro-or-higher feature for connecting a Render private network to compatible AWS-hosted systems. Fetch its current documentation before proposing or configuring it; do not treat ordinary Render service-to-service networking and PrivateLink as interchangeable. + diff --git a/.ai/mcp.servers.json b/.ai/mcp.servers.json index 369e055..29f6ae7 100644 --- a/.ai/mcp.servers.json +++ b/.ai/mcp.servers.json @@ -13,6 +13,11 @@ "supabase": { "type": "http", "url": "https://mcp.supabase.com/mcp?project_ref=gpfgnpnzwwdwcfbdrqcw&read_only=true" + }, + "render": { + "type": "http", + "url": "https://mcp.render.com/mcp", + "oauth_client_ids": { "claude": "claude", "cursor": "cursor", "codex": "codex" } } } } diff --git a/.codex/config.toml b/.codex/config.toml index 2c91a5e..0b01a9b 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -14,4 +14,9 @@ url = "https://mcp.vercel.com" [mcp_servers.supabase] url = "https://mcp.supabase.com/mcp?project_ref=gpfgnpnzwwdwcfbdrqcw&read_only=true" + +[mcp_servers.render] +url = "https://mcp.render.com/mcp" +[mcp_servers.render.oauth] +client_id = "codex" # <<< END generated MCP servers <<< diff --git a/.cursor/mcp.json b/.cursor/mcp.json index 0d831a6..f1b4f79 100644 --- a/.cursor/mcp.json +++ b/.cursor/mcp.json @@ -16,6 +16,12 @@ }, "supabase": { "url": "https://mcp.supabase.com/mcp?project_ref=gpfgnpnzwwdwcfbdrqcw&read_only=true" + }, + "render": { + "url": "https://mcp.render.com/mcp", + "auth": { + "CLIENT_ID": "cursor" + } } } } diff --git a/.mcp.json b/.mcp.json index a1b293b..9634325 100644 --- a/.mcp.json +++ b/.mcp.json @@ -19,6 +19,13 @@ "supabase": { "type": "http", "url": "https://mcp.supabase.com/mcp?project_ref=gpfgnpnzwwdwcfbdrqcw&read_only=true" + }, + "render": { + "type": "http", + "url": "https://mcp.render.com/mcp", + "oauth": { + "clientId": "claude" + } } } } diff --git a/AGENTS.md b/AGENTS.md index 0ffbfec..9e39f90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,6 +41,8 @@ side the evidence supports. Web app first, mobile later. frontend variable must also be added in the Vercel project (tell Hani). - Never print, log, commit or paste API keys or `.env` contents. The team shares keys. - Never connect AI tools to the production database. +- The Render MCP can write. Use it to read logs, metrics and deploys; ask before changing + environment variables (an update replaces the whole set), deploying or creating anything. - Read AI models from settings (`CLAIM_MODEL`, `ANALYSIS_MODEL`); never hardcode a provider. - Ask before adding a dependency, changing CI, or writing a migration that drops or rewrites data. diff --git a/README.md b/README.md index ea6cb47..929e45a 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ conversations between two people. `npm install` and `npm run dev`. 4. Backend: `cd api`, copy `.env.example` to `.env`, fill it in (Hani shares the team keys), then `uv sync` and `uv run uvicorn app.main:app --reload`. -5. Open your AI tool in the repo root and log in to the `supabase` and `vercel` MCP - servers when it asks. +5. Open your AI tool in the repo root and log in to the `supabase`, `vercel` and `render` + MCP servers when it asks. `vercel` and `render` show our project only to Hani until + those accounts are upgraded (see `docs/ai/README.md`). Rules for humans and agents: `AGENTS.md`. Architecture and roadmap: `docs/architecture.md`. AI tooling: `docs/ai/README.md`. diff --git a/docs/ai/README.md b/docs/ai/README.md index ed763e8..f57e3c6 100644 --- a/docs/ai/README.md +++ b/docs/ai/README.md @@ -106,6 +106,18 @@ All shared servers live in `.ai/mcp.servers.json`. | `playwright` | A local browser; pinned to `@playwright/mcp@0.0.86` | generated | generated | generated | | `vercel` | Your Vercel account | generated | generated | generated | | `supabase` | Only the dev project, read-only | generated | generated | generated | +| `render` | Your Render workspace; can read and write | generated | generated | generated | + +**`vercel` and `render` only work fully for Hani for now.** Both team accounts are on free +plans that allow one member, so teammates' logins succeed but show their own (empty) +accounts, not our project. Until the plans change, teammates get Vercel's documentation +search from `vercel` and nothing useful from `render`; the Vercel comment on each PR still +shows its build. To change that: + +- Render: upgrade the workspace to Pro ($25/month flat, unlimited members), planned for + alpha, then invite everyone. +- Vercel: upgrade the team to Pro ($20/month). Viewer seats are free and give read-only + access to deployments; each extra Developer seat is $20/month. Keep MCP package versions pinned. Bump them in a PR so the whole team moves together and the change gets reviewed. The Supabase URL is scoped with `project_ref` and @@ -113,21 +125,18 @@ the change gets reviewed. The Supabase URL is scoped with `project_ref` and types, but every schema change goes through `supabase/migrations/` (see `docs/architecture.md`). Never add the production project here. -**Render MCP is intentionally not in this repo yet.** Two reasons: - -- A free Render workspace has one member (Hani), so nobody else could log in to it. - Revisit when the workspace moves to Pro at alpha. -- Unlike the read-only Supabase server, it can write: it updates environment variables - (replacing the whole set), triggers deploys and creates services or databases. Its - OAuth server has no dynamic client registration, so a plain URL entry in - `.ai/mcp.servers.json` won't work. Claude Code and Cursor use Render's official plugin - (`/plugin install render@claude-plugins-official`, `/add-plugin render`) and Codex needs - `codex mcp add render --url https://mcp.render.com/mcp --oauth-client-id codex`. - `scripts/sync-mcp.py` can't emit that Codex setting today. +Unlike the read-only Supabase server, `render` can write: it can update a service's +environment variables (replacing the whole set), trigger deploys and create services or +databases. It can't delete anything. Use it to read logs, metrics and deploy status, and +make a change only when you mean to. -Until then Hani can install Render's official plugin for himself (not committed). When -adding it for the team, use the `add-shared-tool` skill; the Claude plugin route -(`.claude/settings.json`) fits, and Codex and Cursor stay per person. +Render's OAuth has no dynamic client registration, so the entry uses `oauth_client_ids`: +the public client ID Render registered for each tool (`claude`, `cursor`, `codex`), the +same ones its official plugins use. They are not secrets. We use this instead of Render's +Claude Code plugin because that plugin's hook is a bash script, which fails on Windows. +Five of Render's skills (`render-blueprints`, `render-debug`, `render-env-vars`, +`render-monitor`, `render-web-services`) are installed from `render-oss/skills` and +tracked in `skills-lock.json`. **Open Design is intentionally not in this repo.** Codex users add the Open Design plugin themselves through ChatGPT; everyone else uses the Open Design desktop app. Nothing to @@ -142,6 +151,10 @@ First-use steps per person: `supabase`, authenticate. Cursor: click "Needs login" next to the server. Codex: run `codex mcp login supabase`. The `supabase` and `supabase-postgres-best-practices` skills are in `.agents/skills/`. +- **Render** uses OAuth with your own Render account (see the plan note above). Claude + Code: run `/mcp`, pick `render`, authenticate. Cursor: click "Needs login" next to the + server. Codex: run `codex mcp login render`. Then tell the agent "Set my Render + workspace to "; it asks for this once per session. - **Claude Code** asks for approval the first time it sees project-scoped servers in `.mcp.json`. - **Codex** only reads a project's `.codex/config.toml` for projects you have marked as trusted. @@ -150,12 +163,14 @@ files). It exists because `npx` cannot be spawned directly on native Windows, an wrapping it in `cmd /c` would break Mac. Don't "simplify" it away. Use `"wrap": true` for any new server launched through `npx` or another shim. -If you previously installed Playwright, Vercel, or Supabase yourself (`claude mcp add ...`, -`codex mcp add ...`, a Cursor plugin, or Cursor settings), you can leave it or remove your copy so the tool -doesn't list the server twice. +If you previously installed Playwright, Vercel, Supabase or Render yourself +(`claude mcp add ...`, `codex mcp add ...`, a Claude Code or Cursor plugin, or Cursor +settings), remove your copy so the tool doesn't list the server twice. Render's own +plugins also bring their own copies of the Render skills. Never put secret values in `.ai/mcp.servers.json`. List the variable NAME in `env_vars` -and have each person set it in their own environment. +and have each person set it in their own environment. For a remote server whose OAuth +needs a pre-registered public client ID (like Render), set `oauth_client_ids` per tool. ## Known quirks diff --git a/docs/architecture.md b/docs/architecture.md index 138d2d4..f5ff96d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -62,7 +62,9 @@ The Vercel project `dialectic-ai` builds `web/` (Root Directory `web`, Node.js 2 `https://*-dialectic1.vercel.app/**` for previews. - Plan: Hobby, Hani's account. It works because the repo is public: Hobby can't deploy private organization repos. A Hobby team has one member, so teammates can open preview - links only while Vercel Authentication is off (Settings > Deployment Protection). + links only while Vercel Authentication is off (Settings > Deployment Protection), and + the `vercel` MCP shows the project only to Hani. Pro ($20/month, free read-only Viewer + seats) would let teammates in. ## Backend hosting (Render) @@ -83,8 +85,8 @@ WebSocket connections a live debate needs (browser audio in, claims and fact-che because a sleeping server would stall a live debate. - The account is Hani's. Developers run the API locally; the Render service is the shared deployed copy. A free (Hobby) Render workspace allows one member, so teammates can't - be invited (and so can't use a Render MCP) until it is upgraded to Pro ($25/month flat, - unlimited members). Upgrade at alpha, together with Starter. + be invited until it is upgraded to Pro ($25/month flat, unlimited members). Until then + the `render` MCP shows the service only to Hani. Upgrade at alpha, together with Starter. ## Accounts and keys @@ -134,8 +136,8 @@ MVP, alpha, pilot, beta, public release (web, then iOS and Android). project; schema changes are tested by CI. - **Alpha:** add Docker: a local Supabase per developer (`supabase start`) and containers for consistent local setup. Google sign-in and a custom email sender. Model evaluation. - Render service on the Starter plan, workspace on Pro, then add the shared Render MCP - (see `docs/ai/README.md`). + Render service on the Starter plan, workspace on Pro, then invite the team (the `render` + MCP is already configured). - **Before the pilot:** create the production database (checklist below). Invite-only sign-ups. Hide FastAPI's public API docs in production: `/docs`, `/redoc` and `/openapi.json` are live on Render today. Pass `docs_url=None, redoc_url=None, openapi_url=None` to diff --git a/scripts/sync-mcp.py b/scripts/sync-mcp.py index 1a2b4a4..3ce5550 100644 --- a/scripts/sync-mcp.py +++ b/scripts/sync-mcp.py @@ -15,6 +15,9 @@ command stdio only args stdio only url http only + oauth_client_ids + http only, optional; {target: client_id} for servers whose OAuth needs a + pre-registered public client ID per tool instead of dynamic registration env_vars optional list of env var NAMES to pass through (never put values here) wrap optional; true = run the command through a tiny Node launcher so the same committed config works on native Windows (where `npx` needs a shell) and Mac @@ -61,9 +64,19 @@ def load_servers(): for t in s.get("targets", ALL_TARGETS): if t not in ALL_TARGETS: sys.exit(f"{name}: unknown target '{t}'") + if "oauth_client_ids" in s: + if s["type"] != "http": + sys.exit(f"{name}: oauth_client_ids is only for http servers") + for t in s["oauth_client_ids"]: + if t not in ALL_TARGETS: + sys.exit(f"{name}: unknown target '{t}' in oauth_client_ids") return servers +def oauth_client_id(s, target): + return s.get("oauth_client_ids", {}).get(target) + + def command_and_args(s): if s.get("wrap"): return "node", ["-e", LAUNCHER, "--", s["command"], *s.get("args", [])] @@ -72,7 +85,10 @@ def command_and_args(s): def claude_entry(s): if s["type"] == "http": - return {"type": "http", "url": s["url"]} + entry = {"type": "http", "url": s["url"]} + if client_id := oauth_client_id(s, "claude"): + entry["oauth"] = {"clientId": client_id} + return entry cmd, args = command_and_args(s) entry = {"type": "stdio", "command": cmd, "args": args} if s.get("env_vars"): @@ -82,7 +98,10 @@ def claude_entry(s): def cursor_entry(s): if s["type"] == "http": - return {"url": s["url"]} + entry = {"url": s["url"]} + if client_id := oauth_client_id(s, "cursor"): + entry["auth"] = {"CLIENT_ID": client_id} + return entry cmd, args = command_and_args(s) entry = {"command": cmd, "args": args} if s.get("env_vars"): @@ -114,6 +133,9 @@ def render_codex_block(servers): lines.append(f"[mcp_servers.{name}]") if s["type"] == "http": lines.append(f"url = {toml_str(s['url'])}") + if client_id := oauth_client_id(s, "codex"): + lines.append(f"[mcp_servers.{name}.oauth]") + lines.append(f"client_id = {toml_str(client_id)}") else: cmd, args = command_and_args(s) lines.append(f"command = {toml_str(cmd)}") diff --git a/skills-lock.json b/skills-lock.json index 2a5568b..e0101c5 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -15,6 +15,41 @@ "skillPath": ".agents/skills/impeccable/SKILL.md", "computedHash": "1e75d6ac58c813ea27ca1c9de873829651fbc84d280a01835db8f3c400373d1c" }, + "render-blueprints": { + "source": "render-oss/skills", + "commit": "841f4e3f857f85c86719ca392aecd3a29c7df164", + "sourceType": "github", + "skillPath": "skills/render-blueprints/SKILL.md", + "computedHash": "711d03083f77a855e5916a97082b074adece12ce0e28de2933707fa8d6ef5757" + }, + "render-debug": { + "source": "render-oss/skills", + "commit": "841f4e3f857f85c86719ca392aecd3a29c7df164", + "sourceType": "github", + "skillPath": "skills/render-debug/SKILL.md", + "computedHash": "d482d603724659d284d556ce2a8afcd5098bd90d8bde453f5a430933b3a5b10a" + }, + "render-env-vars": { + "source": "render-oss/skills", + "commit": "841f4e3f857f85c86719ca392aecd3a29c7df164", + "sourceType": "github", + "skillPath": "skills/render-env-vars/SKILL.md", + "computedHash": "7fb2d829c515a2393c917e938d00c867ad69781fce9d1cafc620dae4a8fd5e61" + }, + "render-monitor": { + "source": "render-oss/skills", + "commit": "841f4e3f857f85c86719ca392aecd3a29c7df164", + "sourceType": "github", + "skillPath": "skills/render-monitor/SKILL.md", + "computedHash": "d27fe37bc77a08eff581a7a6331d5b6d5402e9baba68977b8f6dbc075fc36886" + }, + "render-web-services": { + "source": "render-oss/skills", + "commit": "841f4e3f857f85c86719ca392aecd3a29c7df164", + "sourceType": "github", + "skillPath": "skills/render-web-services/SKILL.md", + "computedHash": "1ce3cb317b3749be9c2ff70b46361c1a74b801ff11e755c54632edec599e6978" + }, "supabase": { "source": "supabase/agent-skills", "commit": "c9be0e931b7930f7d02126d04774d904c381e7d7",