{"name": "supabase", "version": "0.1.1", "hash": "sha256:04d0af319154caa12444b94f05a366131e5d33573849f8c4e5183940f430bb45", "files": {"ABSORB_REPORT.md": "# Absorb report: supabase\n\n- **Source:** https://github.com/supabase/supabase at `b6270f4a3167`\n- **Licence:** Apache-2.0\n- **Project names searched for:** supabase\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| api-types | skill | mixed | supabase ×1 | packages/api-types/types/api-v1.d.ts, packages/api-types/types/api-v2.d.ts, packages/api-types/types/platform.d.ts, packages/api-types/types |\n| ask-the-docs | skill | mixed | supabase ×56 | apps/docs, apps/docs/resources, apps/docs/content, packages/common/telemetry-constants.ts, apps/docs/lib, apps/docs/turbo.jsonc, .github/workflows, packages/ui, apps/docs/internals, apps/docs/content/guides, apps/docs/content/_partials, apps/docs/components |\n| clickhouse-logs-queries | skill | mixed | supabase ×3 | apps/studio/data/logs, apps/studio/components/interfaces/Settings/Logs, apps/studio, apps/studio/data/logs/safe-analytics-sql.ts, apps/studio/data/logs/execute-analytics-sql.ts, apps/studio/eslint.config.cjs, apps/studio/data/logs/logs-endpoint.ts, apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.ts, apps/studio/data/logs/otel-log-keys-query.ts |\n| code-review | skill | mechanics |  |  |\n| copywriting | skill | mixed |  | apps/design-system/content/docs/copywriting.mdx |\n| dev-toolbar-review | skill | mixed | supabase ×1 | packages/dev-tools, packages/common/posthog-client.ts, packages/common/feature-flags.tsx, packages/common, apps/studio, apps/www, apps/docs, packages/dev-tools/index.ts, packages/dev-tools/DevToolbar.tsx, packages/dev-tools/utils.ts, packages/dev-tools/DevToolbarContext.tsx, apps/www/pages/_app.tsx |\n| edit-the-docs | skill | mixed | supabase ×6 | apps/docs, apps/docs/content/_partials, apps/docs/content, apps/www, apps/docs/public/markdown/manifest.json |\n| pm-the-docs | skill | mixed | supabase ×23 | apps/docs, docker |\n| react-hook-form | skill | mixed |  | apps/design-system/registry/default/example, apps/design-system/content/docs/ui-patterns/modality.mdx |\n| review-the-docs | skill | mixed | supabase ×38 | apps/docs/content/guides, apps/docs/internals, apps/docs/internals/markdown-schema, apps/docs/components, apps/studio, apps/docs, apps/docs/content, apps/docs/features, apps/docs/AGENTS.md, apps/docs/CONTRIBUTING.md, apps/docs/DEVELOPERS.md, apps/docs/style-guide |\n| safe-sql-execution | skill | mixed | supabase ×9 | apps/studio/lib/sql.ts, apps/studio/data, apps/studio/data/logs/safe-analytics-sql.ts, apps/studio/data/logs/execute-analytics-sql.ts, apps/studio/eslint.config.cjs |\n| studio-e2e-tests | skill | mixed | supabase ×2 | e2e/studio, e2e/studio/features, e2e/studio/utils/storage-helpers.ts |\n| studio-error-handling | skill | mixed | supabase ×1 | apps/studio/components/interfaces/ErrorHandling/README.md |\n| studio-mock-api-tests | skill | mixed | supabase ×1 | apps/studio/data/api.d.ts, apps/studio/tests/vitestSetup.ts, apps/studio/tests/lib/route-mock.ts, apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx, apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx, apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx, apps/studio/tests/lib/msw.ts, apps/studio/tests/lib/custom-render.tsx, apps/studio/tests/lib/msw-global-api-mocks.ts, apps/studio/tests/lib/msw-permissions.ts, apps/studio/tests/lib/test-grant.ts |\n| studio-queries | skill | mixed | supabase ×1 | apps/studio/data, apps/studio/data/table-editor/table-editor-query.ts, apps/studio/data/edge-functions/edge-functions-update-mutation.ts, apps/studio/data/edge-functions/keys.ts |\n| studio-shortcuts | skill | mixed | supabase ×1 | apps/studio/state/shortcuts/registry.ts, apps/studio/state/shortcuts/registry, apps/studio/state/shortcuts/referenceGroups.ts, apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksDeliveryDetailsSheet.tsx, apps/studio/lib/keyboard.ts, apps/studio/state/shortcuts/useShortcut.tsx |\n| studio-testing | skill | mixed | supabase ×1 | e2e/studio/utils, apps/studio/tests/components/Grid/Grid.utils.test.ts, apps/studio/tests/components/Billing/TaxID.utils.test.ts, apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts, apps/studio/tests/features/logs/LogsFilterPopover.test.tsx, apps/studio/tests/components/CopyButton.test.tsx, apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx, apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx, apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx, e2e/studio/features/filter-bar.spec.ts, e2e/studio/utils/filter-bar-helpers.ts, apps/studio/tests/lib/custom-render.tsx |\n| studio-ui-patterns | skill | mixed | supabase ×1 | apps/design-system/content/docs/ui-patterns/layout.mdx, apps/design-system/registry/default/example, apps/design-system/content/docs/ui-patterns/forms.mdx, apps/design-system/content/docs/ui-patterns/tables.mdx, apps/design-system/content/docs/ui-patterns/charts.mdx, apps/design-system/registry/default/block, apps/design-system/content/docs/ui-patterns/empty-states.mdx, apps/design-system/content/docs/ui-patterns/navigation.mdx, apps/design-system/content/docs/ui-patterns/modality.mdx, apps/design-system/content/docs/copywriting.mdx, e2e/studio |\n| telemetry-standards | skill | mixed | supabase ×3 | packages/common/telemetry-constants.ts, apps/studio, packages/common/search-query-telemetry.ts, apps/studio/lib/telemetry/use-track-funnel-error.ts, packages/common/telemetry-utils.ts, packages/common/posthog-client.ts, packages/common/consent-state.ts, packages/common/telemetry-event.ts, packages/common/feature-flags.tsx |\n| test-the-docs | skill | mixed | supabase ×31 | apps/docs/content, supabase/config.toml, examples |\n| turbo-scripts | skill | mixed |  | apps/docs, packages/maybe-turbo, .github/workflows |\n| vercel-composition-patterns | skill | mechanics |  |  |\n| vitest | skill | mechanics |  |  |\n| write-the-docs | skill | mixed | supabase ×9 | apps/docs/content, apps/docs, apps/kb/README.md, apps/kb/src/content, apps/kb/AGENTS.md, apps/docs/spec, apps/docs/generator, apps/kb/src/content/guides, apps/kb/src/content/faqs, apps/docs/content/_partials, apps/docs/lib/redirects/README.md, apps/docs/CONTRIBUTING.md |\n| SessionStart [startup] | hook | mechanics |  |  |\n| PostToolUse [Write|Edit] | hook | mechanics |  |  |\n| permission rules | permissions | mixed | supabase ×1 | packages/api-types/types |\n| supabase | mcp-server | mixed | supabase ×1 |  |\n\n## Needs review before sharing\n\nThese pieces mention the project by name or lean on its files. Move those facts into configuration, or keep the piece out of a shared starter.\n\n- **api-types** (skill): names supabase; paths packages/api-types/types/api-v1.d.ts, packages/api-types/types/api-v2.d.ts, packages/api-types/types/platform.d.ts, packages/api-types/types\n- **ask-the-docs** (skill): names supabase; paths apps/docs, apps/docs/resources, apps/docs/content, packages/common/telemetry-constants.ts, apps/docs/lib, apps/docs/turbo.jsonc, .github/workflows, packages/ui, apps/docs/internals, apps/docs/content/guides, apps/docs/content/_partials, apps/docs/components\n- **clickhouse-logs-queries** (skill): names supabase; paths apps/studio/data/logs, apps/studio/components/interfaces/Settings/Logs, apps/studio, apps/studio/data/logs/safe-analytics-sql.ts, apps/studio/data/logs/execute-analytics-sql.ts, apps/studio/eslint.config.cjs, apps/studio/data/logs/logs-endpoint.ts, apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.ts, apps/studio/data/logs/otel-log-keys-query.ts\n- **copywriting** (skill): paths apps/design-system/content/docs/copywriting.mdx\n- **dev-toolbar-review** (skill): names supabase; paths packages/dev-tools, packages/common/posthog-client.ts, packages/common/feature-flags.tsx, packages/common, apps/studio, apps/www, apps/docs, packages/dev-tools/index.ts, packages/dev-tools/DevToolbar.tsx, packages/dev-tools/utils.ts, packages/dev-tools/DevToolbarContext.tsx, apps/www/pages/_app.tsx\n- **edit-the-docs** (skill): names supabase; paths apps/docs, apps/docs/content/_partials, apps/docs/content, apps/www, apps/docs/public/markdown/manifest.json\n- **pm-the-docs** (skill): names supabase; paths apps/docs, docker\n- **react-hook-form** (skill): paths apps/design-system/registry/default/example, apps/design-system/content/docs/ui-patterns/modality.mdx\n- **review-the-docs** (skill): names supabase; paths apps/docs/content/guides, apps/docs/internals, apps/docs/internals/markdown-schema, apps/docs/components, apps/studio, apps/docs, apps/docs/content, apps/docs/features, apps/docs/AGENTS.md, apps/docs/CONTRIBUTING.md, apps/docs/DEVELOPERS.md, apps/docs/style-guide\n- **safe-sql-execution** (skill): names supabase; paths apps/studio/lib/sql.ts, apps/studio/data, apps/studio/data/logs/safe-analytics-sql.ts, apps/studio/data/logs/execute-analytics-sql.ts, apps/studio/eslint.config.cjs\n- **studio-e2e-tests** (skill): names supabase; paths e2e/studio, e2e/studio/features, e2e/studio/utils/storage-helpers.ts\n- **studio-error-handling** (skill): names supabase; paths apps/studio/components/interfaces/ErrorHandling/README.md\n- **studio-mock-api-tests** (skill): names supabase; paths apps/studio/data/api.d.ts, apps/studio/tests/vitestSetup.ts, apps/studio/tests/lib/route-mock.ts, apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx, apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx, apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx, apps/studio/tests/lib/msw.ts, apps/studio/tests/lib/custom-render.tsx, apps/studio/tests/lib/msw-global-api-mocks.ts, apps/studio/tests/lib/msw-permissions.ts, apps/studio/tests/lib/test-grant.ts\n- **studio-queries** (skill): names supabase; paths apps/studio/data, apps/studio/data/table-editor/table-editor-query.ts, apps/studio/data/edge-functions/edge-functions-update-mutation.ts, apps/studio/data/edge-functions/keys.ts\n- **studio-shortcuts** (skill): names supabase; paths apps/studio/state/shortcuts/registry.ts, apps/studio/state/shortcuts/registry, apps/studio/state/shortcuts/referenceGroups.ts, apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksDeliveryDetailsSheet.tsx, apps/studio/lib/keyboard.ts, apps/studio/state/shortcuts/useShortcut.tsx\n- **studio-testing** (skill): names supabase; paths e2e/studio/utils, apps/studio/tests/components/Grid/Grid.utils.test.ts, apps/studio/tests/components/Billing/TaxID.utils.test.ts, apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts, apps/studio/tests/features/logs/LogsFilterPopover.test.tsx, apps/studio/tests/components/CopyButton.test.tsx, apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx, apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx, apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx, e2e/studio/features/filter-bar.spec.ts, e2e/studio/utils/filter-bar-helpers.ts, apps/studio/tests/lib/custom-render.tsx\n- **studio-ui-patterns** (skill): names supabase; paths apps/design-system/content/docs/ui-patterns/layout.mdx, apps/design-system/registry/default/example, apps/design-system/content/docs/ui-patterns/forms.mdx, apps/design-system/content/docs/ui-patterns/tables.mdx, apps/design-system/content/docs/ui-patterns/charts.mdx, apps/design-system/registry/default/block, apps/design-system/content/docs/ui-patterns/empty-states.mdx, apps/design-system/content/docs/ui-patterns/navigation.mdx, apps/design-system/content/docs/ui-patterns/modality.mdx, apps/design-system/content/docs/copywriting.mdx, e2e/studio\n- **telemetry-standards** (skill): names supabase; paths packages/common/telemetry-constants.ts, apps/studio, packages/common/search-query-telemetry.ts, apps/studio/lib/telemetry/use-track-funnel-error.ts, packages/common/telemetry-utils.ts, packages/common/posthog-client.ts, packages/common/consent-state.ts, packages/common/telemetry-event.ts, packages/common/feature-flags.tsx\n- **test-the-docs** (skill): names supabase; paths apps/docs/content, supabase/config.toml, examples\n- **turbo-scripts** (skill): paths apps/docs, packages/maybe-turbo, .github/workflows\n- **write-the-docs** (skill): names supabase; paths apps/docs/content, apps/docs, apps/kb/README.md, apps/kb/src/content, apps/kb/AGENTS.md, apps/docs/spec, apps/docs/generator, apps/kb/src/content/guides, apps/kb/src/content/faqs, apps/docs/content/_partials, apps/docs/lib/redirects/README.md, apps/docs/CONTRIBUTING.md\n- **permission rules** (permissions): names supabase; paths packages/api-types/types\n- **supabase** (mcp-server): names supabase\n- **SessionStart [startup]**: runs a file of the project that is not in the harness: `${PROJECT_DIR}/.claude/scripts/install_pkgs.sh`\n- **PostToolUse [Write|Edit]**: runs a file of the project that is not in the harness: `${PROJECT_DIR}/.agents/scripts/format_and_lint.sh`\n\n## Not absorbed\n\n- instruction files (AGENTS.md): they describe the project, so they stay with it. Pass --with-instructions to absorb them for review\n- `.claude/scripts/` (1 file(s)): this version of absorb does not read it, so it stays with the project\n\n## Self-test\n\nNo case could be generated.\n2 hook(s) were absorbed. A hook that guards something is only proven once a case shows it blocking: add `block` and `allow` cases for each, then run `baudrier selftest`.\n\n## Warnings\n\n- skipped skills/test-the-docs/sandbox/.gitignore: ignore files inside a skill are not imported\n- PostToolUse hook `\"$CLAUDE_PROJECT_DIR\"/.agents/scripts/format_and_lint.sh`: option(s) statusMessage not carried over\n\n## Changed for the hub\n\nThe SessionStart and PostToolUse hooks were left out: they start scripts of the Supabase repository (`.claude/scripts/install_pkgs.sh`, `.agents/scripts/format_and_lint.sh`) that are not part of this harness, so elsewhere they would only fail. Neither could block anything.\n\nThe self-test cases were drafted with `baudrier selftest --init` (CLI 0.15.0): one for each of the six rules that keep generated files read-only, and one ordinary edit that must pass. Since that version, Codex keeps those rules too: a hook refuses a patch that touches a file they cover.\n", "ATTRIBUTION.md": "# Attribution: supabase\n\nThis harness was absorbed from https://github.com/supabase/supabase at commit `b6270f4a31674bde181ae2a22cc8e2649477cf85` on 2026-11-27 with `baudrier absorb`.\n\n- **Licence:** Apache-2.0. Licence and notice files kept unchanged in this folder: `LICENSE`.\n- **Credit:** every file listed below is the work of the source repository's authors. Files were copied unchanged, except that hook commands name their folder as `${HARNESS_HOOKS}` and slash commands were wrapped as skills.\n\n## Absorbed files\n\n- `skills/api-types/SKILL.md` (skill)\n- `skills/ask-the-docs/SKILL.md` (skill)\n- `skills/ask-the-docs/reference/adding-features.md` (skill)\n- `skills/ask-the-docs/reference/app-map.md` (skill)\n- `skills/ask-the-docs/reference/build-pipeline.md` (skill)\n- `skills/ask-the-docs/reference/ci-and-lint.md` (skill)\n- `skills/ask-the-docs/reference/docs-app-direction.md` (skill)\n- `skills/ask-the-docs/reference/feature-flags.md` (skill)\n- `skills/ask-the-docs/reference/federated-docs.md` (skill)\n- `skills/ask-the-docs/reference/gotchas.md` (skill)\n- `skills/ask-the-docs/reference/graphql-endpoint.md` (skill)\n- `skills/ask-the-docs/reference/known-issues.md` (skill)\n- `skills/ask-the-docs/reference/llm-agent-parity.md` (skill)\n- `skills/ask-the-docs/reference/llm-agent-surface.md` (skill)\n- `skills/ask-the-docs/reference/management-api-reference.md` (skill)\n- `skills/ask-the-docs/reference/search-embeddings.md` (skill)\n- `skills/clickhouse-logs-queries/SKILL.md` (skill)\n- `skills/clickhouse-logs-queries/references/bigquery-migration.md` (skill)\n- `skills/clickhouse-logs-queries/references/codebase-integration.md` (skill)\n- `skills/code-review/SKILL.md` (skill)\n- `skills/copywriting/SKILL.md` (skill)\n- `skills/dev-toolbar-review/SKILL.md` (skill)\n- `skills/edit-the-docs/SKILL.md` (skill)\n- `skills/edit-the-docs/reference/stacked-prs.md` (skill)\n- `skills/pm-the-docs/SKILL.md` (skill)\n- `skills/pm-the-docs/reference/universe-lookup.md` (skill)\n- `skills/pm-the-docs/reference/write-the-docs-checklist.md` (skill)\n- `skills/react-hook-form/SKILL.md` (skill)\n- `skills/review-the-docs/SKILL.md` (skill)\n- `skills/safe-sql-execution/SKILL.md` (skill)\n- `skills/studio-e2e-tests/SKILL.md` (skill)\n- `skills/studio-error-handling/SKILL.md` (skill)\n- `skills/studio-mock-api-tests/SKILL.md` (skill)\n- `skills/studio-queries/SKILL.md` (skill)\n- `skills/studio-shortcuts/SKILL.md` (skill)\n- `skills/studio-testing/SKILL.md` (skill)\n- `skills/studio-ui-patterns/SKILL.md` (skill)\n- `skills/telemetry-standards/SKILL.md` (skill)\n- `skills/test-the-docs/SKILL.md` (skill)\n- `skills/test-the-docs/reference/sandbox-setup.md` (skill)\n- `skills/test-the-docs/reference/snippet-classes.md` (skill)\n- `skills/test-the-docs/reference/verification-report.md` (skill)\n- `skills/test-the-docs/sandbox/.empty/.keep` (skill)\n- `skills/test-the-docs/sandbox/Dockerfile` (skill)\n- `skills/test-the-docs/sandbox/compose.yaml` (skill)\n- `skills/test-the-docs/sandbox/run.sh` (skill)\n- `skills/turbo-scripts/SKILL.md` (skill)\n- `skills/turbo-scripts/scripts/audit.mjs` (skill)\n- `skills/vercel-composition-patterns/SKILL.md` (skill)\n- `skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md` (skill)\n- `skills/vercel-composition-patterns/rules/architecture-compound-components.md` (skill)\n- `skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md` (skill)\n- `skills/vercel-composition-patterns/rules/patterns-explicit-variants.md` (skill)\n- `skills/vercel-composition-patterns/rules/react19-no-forwardref.md` (skill)\n- `skills/vercel-composition-patterns/rules/state-context-interface.md` (skill)\n- `skills/vercel-composition-patterns/rules/state-decouple-implementation.md` (skill)\n- `skills/vercel-composition-patterns/rules/state-lift-state.md` (skill)\n- `skills/vitest/GENERATION.md` (skill)\n- `skills/vitest/SKILL.md` (skill)\n- `skills/vitest/references/advanced-environments.md` (skill)\n- `skills/vitest/references/advanced-projects.md` (skill)\n- `skills/vitest/references/advanced-type-testing.md` (skill)\n- `skills/vitest/references/advanced-vi.md` (skill)\n- `skills/vitest/references/core-cli.md` (skill)\n- `skills/vitest/references/core-config.md` (skill)\n- `skills/vitest/references/core-describe.md` (skill)\n- `skills/vitest/references/core-expect.md` (skill)\n- `skills/vitest/references/core-hooks.md` (skill)\n- `skills/vitest/references/core-test-api.md` (skill)\n- `skills/vitest/references/features-concurrency.md` (skill)\n- `skills/vitest/references/features-context.md` (skill)\n- `skills/vitest/references/features-coverage.md` (skill)\n- `skills/vitest/references/features-filtering.md` (skill)\n- `skills/vitest/references/features-mocking.md` (skill)\n- `skills/vitest/references/features-snapshots.md` (skill)\n- `skills/write-the-docs/SKILL.md` (skill)\n- `skills/write-the-docs/reference/content-type-gate.md` (skill)\n- `skills/write-the-docs/reference/drafting-mechanics.md` (skill)\n", "LICENSE": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2024 Supabase\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: supabase\n  description: 'The Supabase repository''s agent setup: docs and Studio skills, generated files kept read-only, the Supabase MCP server.'\n  version: 0.1.1\n  license: Apache-2.0\nskills:\n- name: api-types\n  source: ./skills/api-types\n- name: ask-the-docs\n  source: ./skills/ask-the-docs\n- name: clickhouse-logs-queries\n  source: ./skills/clickhouse-logs-queries\n- name: code-review\n  source: ./skills/code-review\n- name: copywriting\n  source: ./skills/copywriting\n- name: dev-toolbar-review\n  source: ./skills/dev-toolbar-review\n- name: edit-the-docs\n  source: ./skills/edit-the-docs\n- name: pm-the-docs\n  source: ./skills/pm-the-docs\n- name: react-hook-form\n  source: ./skills/react-hook-form\n- name: review-the-docs\n  source: ./skills/review-the-docs\n- name: safe-sql-execution\n  source: ./skills/safe-sql-execution\n- name: studio-e2e-tests\n  source: ./skills/studio-e2e-tests\n- name: studio-error-handling\n  source: ./skills/studio-error-handling\n- name: studio-mock-api-tests\n  source: ./skills/studio-mock-api-tests\n- name: studio-queries\n  source: ./skills/studio-queries\n- name: studio-shortcuts\n  source: ./skills/studio-shortcuts\n- name: studio-testing\n  source: ./skills/studio-testing\n- name: studio-ui-patterns\n  source: ./skills/studio-ui-patterns\n- name: telemetry-standards\n  source: ./skills/telemetry-standards\n- name: test-the-docs\n  source: ./skills/test-the-docs\n- name: turbo-scripts\n  source: ./skills/turbo-scripts\n- name: vercel-composition-patterns\n  source: ./skills/vercel-composition-patterns\n- name: vitest\n  source: ./skills/vitest\n- name: write-the-docs\n  source: ./skills/write-the-docs\npermissions:\n  tools:\n    deny:\n    - Edit(packages/api-types/types/**)\n    - Edit(**/routeTree.gen.ts)\n    - Edit(**/__generated__/**)\n    - Edit(apps/docs/features/docs/generated/**)\n    - Edit(apps/www/.generated/**)\n    - Edit(supabase/functions/common/database-types.ts)\nmcp-servers:\n  supabase:\n    transport: streamable-http\n    url: https://mcp.supabase.com/mcp\nx-origin:\n  repository: https://github.com/supabase/supabase\n  commit: b6270f4a31674bde181ae2a22cc8e2649477cf85\n  license: Apache-2.0\n  license_basis: detected\n  license_files:\n  - LICENSE\n  absorbed_at: '2026-11-27'\nx-selftest: file://./selftest/cases.yaml\n", "selftest/cases.yaml": "# Self-test cases: each must give the same decision in every runtime the harness\n# is converted to. Check them with `baudrier publish <folder> --verify --dry`.\ncases:\n- name: deny rule Edit(packages/api-types/types/**) blocks editing `packages/api-types/types/example.txt`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: packages/api-types/types/example.txt\n    old_string: a\n    new_string: b\n  expect: block\n- name: deny rule Edit(**/routeTree.gen.ts) blocks editing `src/routeTree.gen.ts`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: src/routeTree.gen.ts\n    old_string: a\n    new_string: b\n  expect: block\n- name: deny rule Edit(**/__generated__/**) blocks editing `src/__generated__/example.txt`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: src/__generated__/example.txt\n    old_string: a\n    new_string: b\n  expect: block\n- name: deny rule Edit(apps/docs/features/docs/generated/**) blocks editing `apps/docs/features/docs/generated/example.txt`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: apps/docs/features/docs/generated/example.txt\n    old_string: a\n    new_string: b\n  expect: block\n- name: deny rule Edit(apps/www/.generated/**) blocks editing `apps/www/.generated/example.txt`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: apps/www/.generated/example.txt\n    old_string: a\n    new_string: b\n  expect: block\n- name: deny rule Edit(supabase/functions/common/database-types.ts) blocks editing `supabase/functions/common/database-types.ts`\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: supabase/functions/common/database-types.ts\n    old_string: a\n    new_string: b\n  expect: block\n- name: an ordinary file can be edited\n  event: PreToolUse\n  tool: Edit\n  input:\n    file_path: src/example.txt\n    old_string: a\n    new_string: b\n  expect: allow\n", "skills/api-types/SKILL.md": "---\nname: api-types\ndescription: Maintain Supabase API types. Use when changing generated API type declarations, OpenAPI schemas, or investigating API type deployment drift.\n---\n\n# API types\n\nThe generated API contract has three specs: API v1, API v2, and Platform. Their committed outputs are `packages/api-types/types/api-v1.d.ts`, `packages/api-types/types/api-v2.d.ts`, and `packages/api-types/types/platform.d.ts`.\n\n## Update types\n\n1. Make the API/schema change and ensure it is deployed to production before relying on a type PR. Production is the merge-gate source of truth.\n2. Update the committed types, either:\n   - Run `pnpm api:codegen` against a running local API environment. It fetches all three local OpenAPI specs and updates the committed files.\n   - Or, if you don't have a local API environment running, run `pnpm api:codegen:prod`. It fetches the three production OpenAPI specs directly and overwrites the committed files with them (no diffing — it always writes).\n3. Inspect and commit only the intended generated type changes.\n4. Run `pnpm api:verify-types`. It fetches the three production OpenAPI specs, regenerates types with the repository tooling, and compares them with the committed files.\n\nComplete the update only when `pnpm api:verify-types` passes after the production deployment is available. If you used `api:codegen:prod`, this should already pass since the committed files came straight from production.\n\n## Interpret verification\n\n- A pass means the committed generated declarations match all three production specs at the time of the check.\n- A mismatch means production and the committed files differ. If the API is not deployed, deploy it and rerun the check. If production is correct, regenerate and review the changed files.\n- A fetch failure means the production schema endpoint could not be read; fix or retry the endpoint before treating the result as a type mismatch.\n\n## Pull requests\n\nThe `Verify production API types` CI job runs when `packages/api-types/types/**` changes and performs the same production comparison. It is a required merge check. Run the local verifier before requesting review and treat a failed CI verification as production drift that must be resolved.\n", "skills/ask-the-docs/SKILL.md": "---\nname: ask-the-docs\ndescription: >-\n  Answer questions about the Supabase docs app (apps/docs) using\n  documented architecture, build pipeline, and review-pattern notes, and\n  apply feature-design principles (codebase reuse, coding minimalism)\n  when proposing or critiquing changes. Use when the user asks \"how does\n  X work in the docs app?\", \"where does Y live?\", \"is this approach OK\n  for the docs app?\", or before writing non-trivial changes under\n  apps/docs/ — especially anything touching the MDX pipeline, markdown\n  generation, content components, federated docs, or contributor-facing\n  authoring patterns, or feature flags and experiments. Can answer architecture questions with Mermaid\n  diagrams when helpful.\n---\n\n# Ask the docs-app librarian\n\nA reference for `apps/docs` knowledge — architecture, build pipeline,\nfederated docs, known fragilities — plus the feature-design principles\nthe codebase rewards: **understand and reuse the existing code before\nwriting new code**, and **practice coding minimalism** to keep the\nsurface area small.\n\nTwo jobs:\n\n1. **Look up what's already documented** about the docs app —\n   architecture, tradeoffs, gotchas, prior decisions — instead of\n   re-deriving from cold reads.\n2. **Pre-empt review feedback** by applying the codebase-reuse /\n   minimalism principles before opening a PR. Catches the \"fix it in the\n   next round\" comments early.\n\n## When to invoke\n\n- User asks about `apps/docs` architecture, conventions, or behavior\n  (\"how does the markdown pipeline work?\", \"where do listings data files\n  go?\", \"why does Troubleshooting have a `.mjs` utils file?\").\n- User asks about LLM/agent consumption (`llms.txt`, markdown negotiation,\n  `searchDocs`, bulk exports, agent onboarding guides, humans vs agents vs\n  crawlers, AI prompt blocks in quickstarts).\n- About to write code under `apps/docs/` that touches: MDX components,\n  `internals/markdown-schema/`, `generate-guides-markdown.ts`, content\n  data modules, the lint pipeline, telemetry events, contributor-facing\n  snippets, federated routes, reference codegen, or Management API /\n  OpenAPI reference pages.\n- Reviewing a docs-app PR and want a sanity check against the documented\n  principles.\n\n**Not for:** general Supabase docs _content_ questions (use\n`write-the-docs`, `edit-the-docs`, or `review-the-docs`), or app-level work outside\n`apps/docs/`.\n\n## Answering with diagrams\n\nArchitecture and pipeline questions are often clearer with a diagram\nthan with prose. Default to including a **Mermaid diagram** in answers\nabout:\n\n- The MDX runtime vs markdown-export pipeline split.\n- Build flow (Turbo task graph → `build` → Vercel).\n- LLM/agent consumption surface (`llms.txt`, negotiation, bulk exports).\n- Federated docs fetch flow.\n- CI / PR flow.\n- Component / data-registry relationships.\n- Management API OpenAPI → codegen → reference page flow.\n\nMermaid fences (`` ```mermaid `````) render natively on GitHub and\nmost Markdown previewers. Several reference files already embed\nMermaid; reuse or adapt them rather than re-deriving.\n\nKeep diagrams **small and one-topic**. If a diagram needs more than a\ndozen nodes, split it.\n\n## Reference files\n\nShort, focused docs under `reference/`. Read whichever apply to the task\nat hand — they cite each other where context matters.\n\n| File                                                                               | What's inside                                                                                                                                                            |\n| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| [`reference/adding-features.md`](./reference/adding-features.md)                   | Best-practices guidance for adding features to `apps/docs`. Inventory existing code first, pick the smallest viable shape, reuse pipelines.                              |\n| [`reference/docs-app-direction.md`](./reference/docs-app-direction.md)             | Refactoring vision and working norms — what new work should align with.                                                                                                  |\n| [`reference/known-issues.md`](./reference/known-issues.md)                         | Living list of broken, fragile, or in-flux systems. Check before depending on anything (federated docs, search, Sentry, reference-page architecture).                    |\n| [`reference/app-map.md`](./reference/app-map.md)                                   | Architecture cheat sheet — directories, the two-pipeline (MDX runtime + markdown export) model, heading/typography contract, telemetry, lint entries.                    |\n| [`reference/build-pipeline.md`](./reference/build-pipeline.md)                     | Turborepo task graph for building `apps/docs` — codegen, markdown generation, sitemap, Vercel deploy. Mermaid diagram included.                                          |\n| [`reference/llm-agent-surface.md`](./reference/llm-agent-surface.md)               | Audience routing, `llms.txt`, content negotiation, bulk exports.                                                                                                         |\n| [`reference/llm-agent-parity.md`](./reference/llm-agent-parity.md)                 | HTML↔markdown fidelity (e.g. AI prompts), search caveat, agent onboarding guides, in-flux wiring.                                                                        |\n| [`reference/federated-docs.md`](./reference/federated-docs.md)                     | How docs pulls markdown from external repos at build time. Routes, `pageMap`, remark/rehype plugins, link transforms, known failure modes.                               |\n| [`reference/ci-and-lint.md`](./reference/ci-and-lint.md)                           | GitHub Actions on every PR — `Docs Tests`, typecheck, oxfmt, Vercel preview gate. Where to add a check before creating a new one.                                       |\n| [`reference/management-api-reference.md`](./reference/management-api-reference.md) | Management API OpenAPI → reference generation, including scoped PAT permission tables; why not to swap in Scalar/Redoc.                                                  |\n| [`reference/graphql-endpoint.md`](./reference/graphql-endpoint.md)                 | The `/api/graphql` endpoint under `apps/docs/resources/` — per-query folder layout, `rootSchema.ts`, connection/field utils, and the steps to add a new top-level query. |\n| [`reference/search-embeddings.md`](./reference/search-embeddings.md)               | The `scripts/search/` embeddings pipeline behind `searchDocs` — content sources, processing flow, change detection, and the `page` / `page_section` tables.              |\n| [`reference/feature-flags.md`](./reference/feature-flags.md)                       | Static `enabled-features` flags and PostHog experiment flags in `apps/docs`: where each resolves, the variant hook pattern, and gotchas.                                 |\n| [`reference/gotchas.md`](./reference/gotchas.md)                                   | Specific traps to watch for. One-liner per item.                                                                                                                         |\n\n## How to use during a chat\n\n1. **Check for drift.** For each reference file you use, run\n   `git log --oneline <Verified at>..HEAD -- apps/docs ':!apps/docs/content'`\n   and read each commit that touches code the answer depends on. A file\n   with no `Verified at` line is unverified.\n2. **Start by reading** `adding-features.md` and `app-map.md` if the\n   question touches design choices or unfamiliar code paths. They're\n   small on purpose — read both, don't skim.\n3. **Verify before recommending.** Reference content may lag behind the\n   live code. Confirm with the actual files (`apps/docs/...`) before\n   acting on remembered claims about file paths, function names, or\n   behavior.\n4. **Cite the principle**, not just the rule. \"Per `adding-features.md`\n   § 'Reuse pipelines, don't fork them', this routes through the\n   existing markdown-schema handler rather than introducing a side\n   path.\"\n5. **Reach for Mermaid** when explaining architecture, flows, or\n   relationships — see [Answering with diagrams](#answering-with-diagrams).\n\n## Updating the librarian\n\nThis skill lives in `.agents/skills/ask-the-docs/` in `supabase/supabase`.\nWhen something in `apps/docs` changes in a way that makes a reference\nfile inaccurate, or a generally-applicable lesson emerges from a PR\nreview, open a pull request against this repo to update the relevant\nfile, same as any other in-repo change.\n\nList each stale fact under \"Skill corrections\" at the end of the answer.\nWith the user's approval, fix it in their open PR if that PR changes\n`apps/docs`, else in a new PR. After you check a whole file, set its\n`Verified at` line to that commit.\n\nKeep each canonical file under ~250 lines; split before they bloat.\nCapture only what a future contributor would benefit from knowing — if\na fact is already obvious from a quick read of the live code, don't\nwrite it down.\n\n## Related skills\n\n- [`pm-the-docs`](../pm-the-docs/SKILL.md) — audience, stage, content type,\n  and placement calls (Frame and Shape stages of the \"Write the docs\" checklist,\n  mirrored in `pm-the-docs`'s reference file). Cross-repo **product** lookup\n  (universe) lives there, not in this skill.\n- [`test-the-docs`](../test-the-docs/SKILL.md) — execute docs snippets against a\n  Docker-isolated local stack; verification report.\n- [`review-the-docs`](../review-the-docs/SKILL.md) — reviewing open docs\n  PRs with type-specific verification.\n", "skills/ask-the-docs/reference/adding-features.md": "# Adding features to `apps/docs`\n\nBest-practices guidance for adding features to the docs app. Read this\n**before** writing code — most \"fix it in the next round\" review comments\ntrace back to skipping one of these steps.\n\nThe premise: `apps/docs` has accumulated significant surface area already.\nAny new file, build step, lint job, or content shape is a permanent\nmaintenance cost. The goal is to deliver the feature with the smallest\ndurable footprint by **understanding the existing code first** and\n**reusing what's already there**.\n\n## The cost lens\n\nEvery change adds one of two things:\n\n- **Reach** — the feature now does more (user-visible value).\n- **Surface** — there is now more code, configuration, or vocabulary to\n  maintain (recurring cost).\n\nA good change maximizes reach per unit of surface. When a design discussion\nstalls, re-frame as: _\"Does the user-visible improvement justify the\nmaintenance cost?\"_ If you cannot answer yes confidently, cut scope before\ndefending the design.\n\nSee [`docs-app-direction.md`](./docs-app-direction.md) for the broader\ncontext — the docs app already carries known tech debt, and the maintainer's\nstated direction is to reduce surface, not extend it.\n\n## Step 1 — Inventory before you write\n\nBefore adding a file, search for what's already there. The docs app has\nexisting systems for almost every common job; using them is faster than\nbuilding parallel ones.\n\n| Need                                        | Look first at                                                                                               |\n| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |\n| Rendering MDX with a custom component       | The MDX component map in `features/docs/MdxBase.shared.tsx`                                                 |\n| Markdown export of a component              | The schema registry in `internals/generate-guides-markdown.ts` and handlers in `internals/markdown-schema/` |\n| Reusable content blocks                     | `<$Partial path=\"...\" />` and `content/_partials/`                                                          |\n| Headings / typography                       | `<Heading>` from `MdxBase.shared.tsx`; prose / `not-prose` classes                                          |\n| Visual primitives (cards, panels, callouts) | `ui-patterns/GlassPanel`, `ui-patterns/IconPanel`, `ui/Admonition`, etc.                                    |\n| Internal vs external link logic             | `withDocsBasePath` / `addBaseUrlPrefix` in `lib/internal-links.ts`                                          |\n| Telemetry                                   | `useSendTelemetryEvent` + `packages/common/telemetry-constants.ts`                                          |\n| Validation / schemas                        | `zod` schemas under `apps/docs/lib/`                                                                        |\n| Code samples in MDX                         | `$CodeSample` directive                                                                                     |\n| Build steps                                 | Turbo `dependsOn` graph in `apps/docs/turbo.jsonc`                                                  |\n| CI checks                                   | Existing workflows under `.github/workflows/`. See [`ci-and-lint.md`](./ci-and-lint.md).                    |\n\nIf something close to what you need already exists, **the default is to\nextend it**, not to build alongside.\n\n## Step 2 — Pick the smallest viable shape\n\nFor most feature requests, the shapes in descending order of preference are:\n\n1. **Pure content change** — MDX edit, partial, or data file. No new code.\n2. **Configuration of an existing component** — pass a new prop to an\n   existing primitive; extend a config object.\n3. **A new data shape consumed by existing components** — a typed\n   `*.data.ts` module read by an already-registered MDX component.\n4. **A thin component that composes existing primitives** — a small file\n   that orchestrates `<Link>`, `<GlassPanel>`, `<Heading>`, etc. Adds an\n   MDX component-map entry but no new visual primitives.\n5. **A new primitive in the design system** — last resort. Justify against\n   `packages/ui` / `ui-patterns`.\n\nMove down the list only when the option above genuinely cannot express the\nfeature. The further down you go, the more you should write down why.\n\n## Step 3 — Reuse pipelines, don't fork them\n\nIf a feature has to render in more than one place (HTML + markdown export,\nruntime + build, etc.), wire both consumers through a **single shared\nshape** — a data registry, a schema, a constant map — instead of\nmaintaining parallel implementations.\n\nPattern that works well in this codebase:\n\n- The MDX component reads from a data registry keyed by an `id`.\n- The markdown-export handler reads from the _same_ registry, using the\n  same `id` carried as a JSX prop.\n- The data shape (zod schema) is the single source of truth.\n\nAntipatterns to avoid:\n\n- Two extraction paths that serialize the same content differently.\n- A bespoke link-wrapper component when `<Link>` + `<GlassPanel>` already\n  covers the pattern — compose at the call site instead.\n- New custom build steps that run alongside the existing turbo\n  task graph when a `dependsOn` entry already fits.\n- A new CI workflow when `Docs Tests` or the existing typecheck/prettier jobs\n  could absorb the check. See\n  [`ci-and-lint.md`](./ci-and-lint.md).\n- A new content vocabulary (custom front-matter block, novel MDX directive,\n  new YAML schema) when a React component + partial would express the same\n  thing.\n\n## Step 4 — Conventions that keep the diff small\n\nThese are the patterns most often called out in PR review. None of them\nmatter individually; together they keep the surface tight.\n\n### File naming\n\nA file's name matches what it exports. If the file exports `Foo`, it's\n`Foo.ts(x)`. The directory listing should answer \"what's in here?\" without\nopening the file. Same for handler files in `internals/markdown-schema/` —\nthe file name is the JSX element name.\n\n### Import aliases\n\n`import { Foo as Bar }` is reserved for genuine name collisions. Aliasing\nfor \"clarity\" or \"consistency with old naming\" adds friction.\n\n### Single-use helpers stay inline\n\nA helper used in one place lives in that place. New files are for shared\ncode. Wandering helpers in unrelated folders make code hard to find.\n\n### Pure helpers live in `*.utils.ts`\n\nSchema files hold schemas. Data / constant files hold data. Helpers —\nincluding lookups like `getXById` over a constant map — live in\n`X.utils.ts`. Predictable location beats \"logical grouping by concept.\"\n\n### Don't override the design system\n\nUse shared primitives (`<Heading>`, `<GlassPanel>`, prose classes) and let\nthem carry typography and spacing. Adding `text-xl` or `font-semibold` to\na new component is the wrong escape hatch.\n\n### Keep `internals/` out of client and MDX code\n\n`apps/docs/internals/` is for build-time markdown generation. Client\ncomponents and the MDX runtime should not import from it. If a function is\nneeded on both sides, it belongs in `lib/`.\n\n### Markup follows semantics, not visuals\n\nA collection of links is a `<ul>`, regardless of whether it visually\nrenders as a list or a grid. CSS handles layout; markup handles semantics.\n\n### Collapse near-duplicates with discriminator props\n\nWhen two components share structure and differ only in classes or markup\ndetails, collapse them. Extract the differences into class-name constants\nkeyed by the discriminator (`type: 'grid' | 'list'`). Don't ship two\ncomponents that are 90% identical.\n\n### Use maps / lookups over arithmetic on known sets\n\nIf the input domain is `'h2' | 'h3' | 'h4'`, a `Map` (or `Record<Literal, T>`)\nkeyed by those literals is clearer than slicing strings and synthesizing\noutput. Exhaustiveness checking comes along for free.\n\n### Avoid render-time closure churn\n\nHooks should return _stable_ callbacks (`useCallback`) that consumers\ninvoke, not curried builders that create a new closure per item per render.\nInline arrow functions at the call site are fine; building closures in a\nloop during render is not.\n\n### Be robust on URL / string parsing\n\n`/^https?:\\/\\//i` is incomplete. Protocol-relative (`//host`), `mailto:`,\n`tel:`, and bare schemes are all external. Prefer `new URL(href, base)` or\na regex that covers `^(?:[a-z][a-z0-9+\\-.]*:|\\/\\/)`.\n\n### Keep diffs minimal\n\nImport reordering, prettier reflows, or unrelated whitespace edits in a\nfeature PR muddy the review. If a file isn't conceptually part of the\nchange, revert it. Auto-formatter ran on a file you didn't touch? Reset\nit.\n\n## Step 5 — Pre-flight before opening the PR\n\nRun through this checklist before pushing:\n\n- [ ] Searched the inventory in Step 1 for existing primitives / pipelines.\n- [ ] Picked the smallest shape that delivers the feature (Step 2).\n- [ ] Renders consistently across pipelines that share content (Step 3).\n- [ ] File and export names match (Step 4 — file naming).\n- [ ] No unnecessary helpers, imports, files, or aliases.\n- [ ] Typography defers to shared primitives.\n- [ ] No `internals/` imports from client / MDX code.\n- [ ] Diff contains only changes relevant to the feature.\n- [ ] `pnpm format`, `pnpm typecheck`, and the relevant lint job pass.\n\nReplies on review threads move faster when they point to a specific commit\n(\"done in abc1234\") than when they explain the reasoning at length.\nExpect review to come in **passes** that go progressively deeper — that is\nthe path to a minimum-surface design, not nitpicking.\n\n## Related\n\n- [`docs-app-direction.md`](./docs-app-direction.md) — broader context on\n  the docs app's tech debt and refactoring direction.\n- [`app-map.md`](./app-map.md) — where each existing seam lives.\n- [`build-pipeline.md`](./build-pipeline.md) — the build steps you should\n  consider extending before adding a new one.\n- [`ci-and-lint.md`](./ci-and-lint.md) — the CI checks you should consider\n  extending before adding a new workflow.\n- [`gotchas.md`](./gotchas.md) — specific traps known to bite.\n", "skills/ask-the-docs/reference/app-map.md": "# `apps/docs` architecture map\n\nWhat lives where, and what depends on what. **Verify against the live tree\nbefore acting** — paths drift. Cross-references the per-topic deep dives in\nthis folder.\n\nVerified at: 3089aa3f67 (2026-11-25).\n\n## High-level architecture\n\n`apps/docs` is a **Next.js App Router** site served at **`/docs`**\n(`basePath` in `next.config.mjs`). It combines hand-written MDX guides,\nmachine-generated reference docs, troubleshooting content, federated content\nfrom external repos, and shared monorepo packages (`ui`, `common`,\n`ui-patterns`, etc.).\n\n```mermaid\nflowchart TB\n  subgraph routes [\"app/ — Next.js routes\"]\n    guides[\"/guides/*\"]\n    reference[\"/reference/*\"]\n    api[\"/api/*\"]\n  end\n\n  subgraph content [\"Content sources\"]\n    mdx[\"content/guides/*.mdx\"]\n    trouble[\"content/troubleshooting/*.mdx\"]\n    spec[\"spec/*.yml, *.json\"]\n    generated[\"features/docs/generated/**\"]\n    refmdx[\"docs/ref/*.mdx\"]\n    fed[\"External repos<br/>(federated)\"]\n  end\n\n  subgraph render [\"Rendering layer\"]\n    features[\"features/docs/\"]\n    components[\"components/\"]\n    layouts[\"layouts/\"]\n  end\n\n  guides --> mdx\n  guides --> trouble\n  guides --> fed\n  reference --> spec\n  reference --> generated\n  reference --> refmdx\n  guides --> features\n  reference --> features\n  features --> components\n  features --> layouts\n```\n\n## Top-level directory layout\n\n| Path                                   | Purpose                                                                                | Notes                                                                                        |\n| -------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |\n| `app/`                                 | Next.js App Router — thin route files that delegate to feature modules                 | Slug-based catch-alls per section, e.g. `guides/auth/[[...slug]]/page.tsx`                   |\n| `apps/docs/content/guides/`            | Source MDX for `/docs/guides/...` pages                                                | One file per page; `_partials/` for shared blocks                                            |\n| `apps/docs/content/_partials/`         | Reusable MDX snippets included via `<$Partial path=\"...\" />`                           | Recursion supported                                                                          |                            |\n| `apps/docs/components/`                | React components used inside MDX                                                       | One folder per component or component family                                                 |\n| `apps/docs/data/`                      | Typed data modules consumed by components                                              | `.data.ts` suffix; lookup helpers live in `.utils.ts`, not here                              |\n| `apps/docs/lib/`                       | Pure library code shared across pipelines                                              | Schemas (zod), helpers (`.utils.ts`), tests                                                  |\n| `apps/docs/features/docs/`             | Page-level skeletons and the MDX renderer (`MdxBase`)                                  | Shared `<Heading>` lives in `MdxBase.shared.tsx`                                             |\n| `apps/docs/features/`                  | Domain logic — docs rendering, auth, search/command menu, telemetry, app providers     | `app.providers.tsx` wires React Query, theme, dev toolbar, command menu                      |\n| `apps/docs/spec/`                      | Source-of-truth specs for reference generation                                         | OpenAPI, SDK YAML, CLI config                                                                |\n| `apps/docs/generator/`                 | Codegen templates for reference docs                                                   |                                                                                              |\n| `apps/docs/resources/`                 | GraphQL endpoint (`/api/graphql`): per-query schema, model, resolver                   | See [`graphql-endpoint.md`](./graphql-endpoint.md)                                           |\n| `apps/docs/internals/`                 | Build-time markdown generation                                                         | **Do not import from runtime/client code**                                                   |\n| `apps/docs/internals/markdown-schema/` | Per-component handlers: JSX → markdown string                                          | File name matches the component name                                                         |\n| `apps/docs/public/markdown/guides/`    | Generated `.md` output; served via `/docs/guides/<path>.md` or `Accept: text/markdown` | Built by `generate-guides-markdown.ts`; see [`llm-agent-surface.md`](./llm-agent-surface.md) |\n| `apps/docs/public/markdown/reference/` | Generated reference `.md` files                                                        | Built by `generate-reference-markdown.ts`                                                    |\n| `apps/docs/proxy.ts`                   | Content negotiation for guides; bot rewrite for reference deep links                   | Uses `packages/common/markdown-negotiation.ts`                                               |\n| `apps/docs/style-guide/`               | Docs content style guide: voice, elements, page structure, word list, templates        | Source of truth for content style; see `apps/docs/style-guide/README.md`                     |\n| `apps/docs/app/api/guides-md/`         | Serves pre-generated guide markdown to agents                                          | Rewritten from `/docs/guides/<path>.md`                                                      |\n| `apps/docs/examples/`                  | Copied from repo root `examples/` at build time                                        | `codegen:examples`                                                                           |\n| `apps/docs/scripts/`                   | Build-time scripts (sitemap, markdown export, embeddings)                              |                                                                                              |\n\nPublished guide sections: `ai`, `api`, `auth`, `cron`, `database`, `deployment`,\n`functions`, `getting-started`, `integrations`, `local-development`, `platform`,\n`queues`, `realtime`, `resources`, `security`, `self-hosting`, `storage`,\n`telemetry`. Each has its own `layout.tsx` for sidebar navigation.\n\n## Content types\n\n| Type                   | Location                                              | Notes                                                                                                                                                                                                                                                                    |\n| ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| **Guides / tutorials** | `content/guides/`                                     | Hand-written MDX; goal-oriented                                                                                                                                                                                                                                          |\n| **Troubleshooting**    | `content/troubleshooting/`                            | Partly synced from GitHub issues                                                                                                                                                                                                                                         |\n| **Reference**          | Generated from `spec/` → `features/docs/generated/**` | Spec-driven (OpenAPI, SDKSpec, ConfigSpec, CLISpec). Reference pages do **not** use the standard MDX path — see [`docs-app-direction.md`](./docs-app-direction.md) for why. Management API OpenAPI path: [`management-api-reference.md`](./management-api-reference.md). |\n| **Federated**          | External repos at build time                          | Pulled via GitHub App. See [`federated-docs.md`](./federated-docs.md)                                                                                                                                                                                                    |\n\n## Routing model\n\nRoutes stay **thin**; rendering lives in **`features/docs/`**.\n\n```tsx\n// app/guides/getting-started/[[...slug]]/page.tsx\nconst slug = ['getting-started', ...(params.slug ?? [])]\nconst data = await getGuidesMarkdown(slug)\nreturn <GuideTemplate {...data!} />\n```\n\n`getGuidesMarkdown()` (in `features/docs/GuidesMdx.utils.tsx`) loads the file,\nvalidates frontmatter, checks navigation enablement, and returns data for\n`GuideTemplate`.\n\n`slug` is just the Next.js param name. `[[...slug]]` is an optional catch-all\n(can match zero or more segments); `[...slug]` is required. The page handler\nprepends the section name and joins segments to find content on disk.\n\nFor reference, `parseReferencePath(slug)` in `features/docs/Reference.utils.ts`\ninterprets segments like `javascript`, `v2`, `auth-signin` to pick SDK,\nversion, and section.\n\n## The two pipelines (and why they share data)\n\nThe same content has to render twice:\n\n1. **MDX runtime** — React components render `<MyComponent id=\"...\" />`,\n   read data via a data registry, output HTML.\n2. **Markdown export** — `internals/markdown-schema/<MyComponent>.ts`\n   handlers convert the same JSX into plain markdown for\n   `public/markdown/guides/`.\n\n**Load-bearing rule:** both pipelines dereference the _same_ data\nregistry (typically `apps/docs/data/<topic>/index.ts` exporting an\nID-keyed map and a `getById` lookup). The component reads it; the\nhandler reads it. The JSX prop is just an `id`. This keeps the two\noutputs in sync without a parallel data shape.\n\n**Reference implementation: `ContentListings`** — the ID-keyed two-pipeline\npattern in production:\n\n| Layer             | Path                                                                   |\n| ----------------- | ---------------------------------------------------------------------- |\n| Data registry     | `apps/docs/data/content-listings/` (`.data.ts` per topic + `index.ts`) |\n| Runtime component | `apps/docs/components/ContentListings/`                                |\n| Markdown handler  | `apps/docs/internals/markdown-schema/ContentListings.ts`               |\n| MDX registration  | `apps/docs/features/docs/MdxBase.shared.tsx`                           |\n\nMDX usage: `<ContentListings id=\"storage-get-started\" />`.\n\nWhen adding a new component that has a markdown representation:\n\n1. Write the React component under `apps/docs/components/`.\n2. Add a handler under `apps/docs/internals/markdown-schema/<SameName>.ts`.\n3. Register the handler in `apps/docs/internals/generate-guides-markdown.ts`\n   (the `SCHEMA` object).\n4. If a component is purely visual and should be **dropped** from markdown,\n   omit the handler — `generate-guides-markdown.ts` unwraps unknown JSX to its\n   children automatically.\n\nFor the full build flow (Turbo task graph), see\n[`build-pipeline.md`](./build-pipeline.md).\n\nFor how agents and LLMs consume exported markdown (negotiation, bulk\ndownloads, `llms.txt`), see [`llm-agent-surface.md`](./llm-agent-surface.md).\n\n## The markdown export in 30 seconds\n\n`generate-guides-markdown.ts` walks `content/guides/**/*.mdx`:\n\n1. Parse MDX → mdast (mdx + gfm extensions).\n2. Inline `<$Partial path=\"...\" />` recursively.\n3. `addBaseUrlPrefix(tree)` — prefixes internal links with `/docs/`.\n4. `applySchema(tree, SCHEMA)` — bottom-up: serializes children first, then\n   replaces each JSX node with the result of its handler (or unwraps it).\n5. Serialize mdast back to markdown.\n6. Prepend front-matter-derived header (`# title`, subtitle, description).\n7. Write to `public/markdown/guides/<same-path>.md`.\n\nEach `SCHEMA` entry receives `{ props, children, node }` and returns the\nmarkdown string to substitute.\n\n## Layout v2\n\nThe `layout-v2:` Tailwind variant styles the new docs layout.\n`styles/globals.css` defines it as `[data-ia-nav='option-1']` on an ancestor.\nThe `option-1` variant of the PostHog flag `docs-ia-mvp-v1` turns it on\n(`features/IaNav/constants.ts`, `features/DocsLayout/useDocsLayoutV2.ts`).\nA `?docs-ia-mvp-v1=option-1` query parameter forces it. The shell lives in\n`layouts/` (`MainSkeleton.tsx`, `RightRail.tsx`, `HeadingSlot.tsx`) and\n`components/Navigation/`. The nav tree lives in `features/IaNav/`. See\n[`feature-flags.md`](./feature-flags.md).\n\n## `<Heading>` and the prose typography contract\n\n- `<Heading>` from `MdxBase.shared.tsx` is the canonical heading component\n  for MDX. It handles tag-from-level mapping and anchor IDs.\n- The MDX wrapper applies prose styles to everything inside `.prose` (default\n  for guide pages). Inside `.not-prose` blocks, typography is opt-in.\n- Pattern for new components with headings: render `<Heading>` _outside_\n  `not-prose`, render the structured layout _inside_ `not-prose`. The heading\n  inherits prose styles; the layout owns its own classes.\n\n## Telemetry conventions\n\n- Event names live in `packages/common/telemetry-constants.ts` (snake*case,\n  `docs*\\*` prefix for docs events).\n- Components call `useSendTelemetryEvent()` from `~/lib/telemetry`.\n- Properties: prefer flat, ID-prefixed keys. Avoid optional spread tricks\n  unless a property is genuinely optional in the schema.\n\n## Linting and verification entry points\n\nSee [`ci-and-lint.md`](./ci-and-lint.md) for the full CI surface. Local\ncommands:\n\n| Tool                                                | Where     | What it catches                                                                                                |\n| --------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------- |\n| `pnpm test:local:unwatch <path>` (from `apps/docs`) | per-test  | Vitest suite for `lib/` and `data/` schemas; needs local Supabase + DB reset first — see `apps/docs/AGENTS.md` |\n| `pnpm format`                                       | repo root | oxfmt — run before opening a PR                                                                                |\n| `pnpm lint --filter=docs`                           | repo root | ESLint over `apps/docs`                                                                                        |\n| `pnpm typecheck`                                    | repo root | TS across packages                                                                                             |\n| `pnpm build --filter=docs`                          | repo root | Includes markdown generation; failures here block release                                                      |\n| Typos check (`.github/workflows/avoid-typos.yml`)   | CI only   | `runner / misspell` job at error severity — no local command; fix flagged words before merge                   |\n\nBefore adding a custom lint job, check whether the existing one can absorb\nthe check (see [`adding-features.md`](./adding-features.md) \"Reuse\npipelines\").\n\n## Providers (`features/app.providers.tsx`)\n\nWraps the app with:\n\n- `QueryClientProvider` (React Query)\n- `FeatureFlagProvider` (see [feature-flags.md](./feature-flags.md)), `ThemeProvider` from `common`\n- `TooltipProvider` from `ui`\n- `DevToolbar` from `dev-tools`\n- `DocsCommandProvider` / `DocsCommandMenu`\n- `SiteLayout` from `layouts/`\n\n\n- `features/docs/Troubleshooting.utils.common.mjs` — `.mjs`, shared between\n  the Next.js build and other scripts that read troubleshooting entries\n  (e.g. search embeddings generation).\n- Topics enum in `TroubleshootingSchema` (the `topics` field) is the source\n  of truth for product tag values.\n\n## Known integrations\n\n- **Studio** (`apps/studio`) links to docs URLs — check link consistency when\n  changing URL shapes.\n- **www** (`apps/www`) sometimes embeds docs sections.\n- **PostHog** receives `docs_*` events for analytics.\n- **Federated upstream repos** — see [`federated-docs.md`](./federated-docs.md)\n  for the full list (pg_graphql, vecs, wrappers, terraform-provider, setup-cli,\n  splinter, agent-skills).\n", "skills/ask-the-docs/reference/build-pipeline.md": "# Docs build pipeline\n\nHow `apps/docs` is built through the Turborepo task graph. There are no pnpm\n`pre`/`post` lifecycle hooks: ordering lives in `dependsOn` in\n`apps/docs/turbo.jsonc`.\nVerify against the current `apps/docs/turbo.jsonc` and\n`apps/docs/package.json` if behavior surprises you.\n\nVerified at: 3089aa3f67 (2026-11-25).\n\n## Build flow\n\n```mermaid\nflowchart TB\n  subgraph turbo[\"Turborepo — apps/docs/turbo.jsonc\"]\n    direction TB\n    WP[\"^build — workspace deps<br/>(common, ui, config, icons, …)\"]\n    GQL[\"codegen:graphql\"]\n    EX[\"codegen:examples<br/>copy ../../examples → apps/docs/examples\"]\n    CR[\"codegen:references<br/>legacy + new (ensure, dart)<br/>→ features/docs/generated/**, content/reference/**\"]\n    MD[\"build:markdown<br/>build:guides-markdown (after build:federated-content)<br/>+ build:reference-markdown\"]\n    GZ[\"build:gz-archive\"]\n    SM[\"build:sitemap\"]\n    RD[\"redirects:generate\"]\n    CR --> MD --> GZ\n    WP --> DOC[\"docs#build — next build\"]\n    GQL --> DOC\n    EX --> DOC\n    CR --> DOC\n    MD --> DOC\n    GZ --> DOC\n    SM --> DOC\n    RD --> DOC\n  end\n```\n\n## Commands\n\nFrom the repo root:\n\n- **Full graph:** `pnpm build` → `turbo run build` (builds every package/app\n  in dependency order).\n- **Docs only:** `pnpm build:docs` → `turbo run build --filter=docs`.\n\n```json\n\"build:docs\": \"turbo run build --filter=docs\"\n```\n\n## What Turbo does\n\nRoot `turbo.jsonc` defines `build` with `dependsOn: [\"^build\"]`, so\n**workspace dependencies** of `docs` (e.g. `common`, `ui`, `config`, …) are\nbuilt before `docs`.\n\n`apps/docs/turbo.jsonc` **extends** that and tightens the docs tasks:\n\n- **`build` also depends on** `codegen:graphql`, `codegen:examples`,\n  `codegen:references`, `build:markdown`, `build:gz-archive`, `build:sitemap`\n  and `redirects:generate`.\n- **`dev`** depends on `codegen:graphql`, `codegen:examples` and\n  `codegen:references`. `typecheck` depends on `codegen:graphql`, `test` on\n  `codegen:examples`, `test:smoke` / `embeddings` on `codegen:references`,\n  `sync` on `codegen:graphql`, and `ingest:search_v2` on\n  `build:guides-markdown` and `codegen:references`.\n- `codegen:references` has no script of its own: it groups\n  `codegen:references:legacy` and `codegen:references:new`, and the latter\n  depends on `codegen:references:new:ensure` and `codegen:references:dart`.\n  `build:markdown` likewise groups `build:guides-markdown` and\n  `build:reference-markdown`.\n- It lists **env vars** and `inputs` / `outputs` that affect caching for the\n  docs app. Tasks that fetch remote content (`build:federated-content`,\n  `codegen:references:new:ensure`) are uncached.\n\nPipeline Turbo orchestrates for docs: **dependency packages → codegen →\nmarkdown / archive / sitemap / redirects → Next build**.\n\n## The `maybe-turbo` wrapper\n\nThe `docs` package has **no pnpm `pre` / `post` hooks**. Scripts that have\nprerequisites are wrapped with the `maybe-turbo` bin (`packages/maybe-turbo`),\nfor example:\n\n```json\n\"build\": \"maybe-turbo next build --webpack\"\n```\n\n`pnpm dev` runs `next dev` (Turbopack). The production build runs\n`next build --webpack`. A loader or bundler change must work in both.\n`next.config.mjs` has a `webpack` block and a `turbopack` block.\n\nOutside Turbo, `pnpm build`, `pnpm dev`, `pnpm codegen:references`,\n`pnpm ingest:search_v2` and friends re-invoke themselves as\n`turbo run <script> --filter=docs`, so the prerequisites still run (now\ncached by Turbo). Inside Turbo the wrapper runs the command directly.\nExisting commands keep working unchanged. A wrapper with no command (such as\n`codegen:references` or `build:markdown`) only groups its dependencies.\n\n`pnpm dev` in `apps/docs`, `pnpm dev --filter=docs` and `pnpm dev:docs` from the\nrepo root run the same task graph. Before the wrapper, the root commands used\n`turbo.jsonc` and package-level commands used `prebuild`/`predev`, so the same\npipeline was defined twice and could drift. Add new steps to `turbo.jsonc`\nonly. See `packages/maybe-turbo/README.md` for why scripts use the wrapper\ninstead of calling `turbo` directly.\n\n## Codegen scripts\n\n- **`codegen:graphql`** — generates GraphQL types from schema.\n- **`codegen:examples`** — copies `examples/` from monorepo root into\n  `apps/docs/examples` for `$CodeSample` directive resolution.\n- **`codegen:references:legacy`** — `features/docs/Reference.generated.script.ts`\n  (includes Management API: merge OpenAPI v1+v2 → `api.latest.*` JSON).\n  Spec download/bundle lives in `apps/docs/spec/Makefile` (Redocly);\n  see [`management-api-reference.md`](./management-api-reference.md).\n- **`codegen:references:new`** — `scripts/build-reference-content.ts` (from\n  TSDoc JSON under `spec/reference/`). Output lands in\n  `content/reference/**`. Its `codegen:references:new:ensure` (download\n  missing TypeDoc dumps) and `codegen:references:dart` prerequisites run as\n  turbo dependencies.\n- **`build:guides-markdown`** — runs `internals/generate-guides-markdown.ts`\n  over `content/guides/**/*.mdx`. Produces `public/markdown/guides/**.md`.\n- **`build:reference-markdown`** — runs `internals/generate-reference-markdown.ts`.\n  Produces `public/markdown/reference/**.md`.\n- **`build:markdown`** — shorthand for guides + reference markdown.\n- **`build:gz-archive`** — runs `internals/generate-gz-archive.ts`.\n  Produces `public/docs.tar.gz` (tarball of all `public/markdown/`).\n\nFor how agents consume these outputs, see\n[`llm-agent-surface.md`](./llm-agent-surface.md).\n\n## Deploy vs CI\n\n- **Production build** for the site is **Vercel**; `apps/docs/vercel.json`\n  sets `buildCommand` to `pnpm build` (the Turbo graph above).\n- **GitHub Actions** mostly run **tests** (`test:docs` → Turbo), **lint**,\n  **sync** jobs, and **smoke** tests — not a separate full production build\n  graph in the way Turbo does locally. See [`ci-and-lint.md`](./ci-and-lint.md).\n\n## Local development\n\nFrom `apps/docs`:\n\n```bash\npnpm dev   # http://localhost:3001/docs\n```\n\n- **`dev`** depends on GraphQL and reference codegen plus example copy in\n  `turbo.jsonc`, so `pnpm dev` runs them first.\n- Community contributors: set `NEXT_PUBLIC_IS_PLATFORM=false` in `.env`.\n- Supabase employees: `pnpm run dev:secrets:pull` for internal env vars\n  (AWS profile + `scripts/getSecrets.js`).\n- In dev mode, the app **only builds routes upon request** rather than\n  pre-rendering — preview and production environments statically generate\n  routes during build for speed.\n\n## Why this shape matters for changes\n\n- Adding a new build step? See [`adding-features.md`](./adding-features.md)\n  \"Reuse pipelines, don't fork them\" and check if an existing turbo task in\n  `apps/docs/turbo.jsonc` already fits (add a `dependsOn` entry rather than a\n  `pre` / `post` hook).\n- New env var? Add it to `apps/docs/turbo.jsonc`'s `env` so Turbo doesn't\n  cache stale.\n- Touching the markdown export? Read [`app-map.md`](./app-map.md) \"The two\n  pipelines\" first — runtime and export share data, not code paths.\n\n## Related\n\n- [`app-map.md`](./app-map.md) — directory layout and runtime / export split.\n- [`ci-and-lint.md`](./ci-and-lint.md) — GitHub Actions workflow surface.\n- [`federated-docs.md`](./federated-docs.md) — external content fetched\n  during build.\n", "skills/ask-the-docs/reference/ci-and-lint.md": "# Docs CI and lint surface\n\nGitHub Actions running on every PR touching `supabase/supabase`, plus\nthe deploy path. Confirm against the current `.github/workflows/` if\nbehavior surprises you.\n\nBefore adding a new lint job or CI check, **scan this list first** — see\n[`adding-features.md`](./adding-features.md) \"Reuse pipelines, don't fork them.\"\n\n## PR flow\n\n```\nPR opened / updated\n    │\n    ├── Docs Tests                 (pnpm test:docs on relevant docs code/spec changes)\n    ├── TypeScript & Lint          (tsc + eslint)\n    ├── Check Code Formatting      (oxfmt format check)\n    ├── reviewdog                  (inline annotations)\n    ├── Validate pull request      (PR metadata)\n    └── Authorize Vercel Deploys → Vercel builds preview deploy → Preview on CDN\n\nMerge to master\n    └── Vercel → next build (after turbo runs markdown generation) → deploy\n```\n\n## On every pull request\n\nWorkflows run in parallel against any PR touching the repo:\n\n### 1. Docs Tests (`docs-tests.yml`)\n\nTriggered on relevant docs code/spec changes, including the generated scoped\nPAT partials and their shared permission catalog. Runs on a Blacksmith 4-vCPU\nUbuntu runner with concurrency controls to cancel stale builds.\n\n- Sparse checkout of `apps/docs`, `examples`, `packages`, `supabase`, and\n  `patches`.\n- Install pnpm (pinned hash).\n- Set up Node.js from `.nvmrc`.\n- `pnpm install --frozen-lockfile`.\n- Regenerate the scoped PAT partials and fail if the committed output drifts.\n- Run `pnpm run test:docs` (with dummy GitHub OAuth env vars to prevent local\n  Supabase startup errors).\n\n### 2. TypeScript & Lint (`typecheck.yml`)\n\nTypeScript type checking and ESLint across the monorepo.\n\n### 3. Check Code Formatting (`prettier.yml`)\n\nFormat checking with oxfmt across the whole repo including `apps/docs`.\n\n### 4. Authorize Vercel Deploys\n\nGates Vercel preview deployment on a GitHub-side check first. Prevents\narbitrary forks from triggering Vercel builds.\n\n### 5. reviewdog\n\nInline code review annotations via reviewdog.\n\n### 6. Validate pull request\n\nPR metadata validation (title format, labels, etc.).\n\n## Deployment (on merge to master)\n\nProduction deployment is handled by **Vercel**. Supabase employees branch the\nrepo directly rather than fork it, so CI checks auto-run and Vercel deploys\ncan be authorized without the external PR security gate.\n\nMarkdown for every guide is generated as a **turbo dependency of `build`** so Vercel can\nbundle it with middleware and functions — see\n[`build-pipeline.md`](./build-pipeline.md) for the task graph.\n\nThe **Authorize Vercel Deploys** workflow is the glue between GitHub Actions\nand Vercel: it runs first to approve the deploy, then Vercel picks it up and\nbuilds/deploys the Next.js site to their CDN.\n\n## Notable design choices\n\n- **Sparse checkout** keeps CI fast by only pulling the relevant workspace\n  packages.\n- **Blacksmith runners** are used instead of standard GitHub-hosted runners\n  for speed.\n- All workflow steps use **pinned action hashes** rather than floating tags\n  for supply chain security.\n\n## Where to add a new check\n\nBefore adding a new GitHub Actions workflow:\n\n1. **Is it a prose or terminology check?** — it belongs in the authoring\n   skills, not in a workflow. The repo ran a blocking MDX linter and retired\n   it.\n2. **Can `Docs Tests` absorb it?** — TypeScript / vitest checks for new\n   functionality fit here.\n3. **Is it cross-cutting?** — typecheck, prettier, and reviewdog already\n   cover the cross-cutting cases.\n4. **Last resort** — a new workflow file. Use a Blacksmith runner, sparse\n   checkout, pinned action hashes, and a concurrency group. Add a clear\n   trigger filter so it doesn't run on unrelated PRs.\n\n## Vale and prose linting (future)\n\nChris Ward's wishlist (source: hiring conversations, not yet in the repo):\n\n- Vale linting MCP server.\n- Vale extension for VS Code.\n- More async automation that doesn't block PR merges.\n\nIf adding prose linting, prefer async (commenting) checks over blocking ones\nto keep merge cadence high.\n\n## Related\n\n- [`app-map.md`](./app-map.md) — what `pnpm test:docs` actually runs.\n- [`build-pipeline.md`](./build-pipeline.md) — turbo tasks that ship\n  markdown to Vercel.\n- [`adding-features.md`](./adding-features.md) — reuse existing pipelines\n  before adding new ones.\n", "skills/ask-the-docs/reference/docs-app-direction.md": "# `apps/docs` direction and vision\n\nWhere the docs app is heading and what new work should align with. For\nthe _current_ state of broken or fragile systems, see\n[`known-issues.md`](./known-issues.md). For feature-design best\npractices, see [`adding-features.md`](./adding-features.md).\n\n## Refactoring vision\n\n- **Docs-only project.** The long-term goal is for the documentation\n  project to handle _only_ documentation. Other functionalities (specific\n  APIs, etc.) should migrate to sub-projects.\n- **Ongoing surface reduction.** A substantial portion of legacy\n  critical code has already been refactored, and remaining work\n  continues to reduce surface area rather than add to it.\n- **One-to-one markdown fidelity.** Improvements to\n  `generate-guides-markdown` aim for exact correspondence between the\n  rendered guide and the LLM-oriented markdown export. New components\n  that render in MDX should serialize to markdown with the same\n  semantics.\n\n## Working norms\n\n- **Work inside `apps/docs/`, not the repo root.** Simpler terminal\n  commands, clearer debugging scope. Most docs commands assume you've\n  `cd`'d into the app.\n- **AI use is encouraged** for explaining complex or legacy sections of\n  the codebase. Considered effective for mechanical, non-creative tasks.\n- **Historical context.** For decisions older than the current\n  refactoring wave, check with longer-tenured maintainers — most\n  current code has clearer provenance.\n\n## What this means for new work\n\nWhen proposing changes that touch `apps/docs`:\n\n1. **Reuse existing seams before adding new ones.** Markdown export, MDX\n   pipeline, lint, codegen, and federated fetch are all places where\n   new surface area gets challenged. See\n   [`adding-features.md`](./adding-features.md) \"Inventory before you\n   write.\"\n2. **Keep markdown fidelity in mind.** Anything that changes how a\n   guide renders should also change how it serializes to markdown — or\n   have a clear reason it doesn't.\n3. **Don't build against the broken parts.** See\n   [`known-issues.md`](./known-issues.md). Search, Sentry\n   instrumentation, and federated link handling are all in flux. New\n   features should not depend on their current shape.\n4. **Don't extend tech debt.** Component scatter, parallel pipelines,\n   and bespoke render paths are existing problems — don't add to them.\n5. **Refactor only what the feature requires.** Bundling unrelated\n   cleanup into a feature PR muddies review and gets cut anyway. Open a\n   separate refactor PR if the cleanup matters.\n\n## Related\n\n- [`adding-features.md`](./adding-features.md) — feature-design best\n  practices.\n- [`known-issues.md`](./known-issues.md) — what's currently broken or\n  fragile.\n- [`app-map.md`](./app-map.md) — where the existing seams are now.\n- [`federated-docs.md`](./federated-docs.md) — mechanics of one of the\n  known liabilities.\n", "skills/ask-the-docs/reference/feature-flags.md": "# Feature flags in `apps/docs`\n\nDocs has two flag systems. Static flags resolve at build time. PostHog flags resolve in the browser.\n\n## Static flags (`enabled-features`)\n\n- Source: `packages/common/enabled-features/enabled-features.json`. The schema is `enabled-features.schema.json` in the same folder.\n- Read a flag with `isFeatureEnabled` from `common/enabled-features`. One key returns a boolean. An array of keys returns an object with camelCased names (`'logs:templates'` becomes `logsTemplates`).\n- To add a flag, follow `packages/common/enabled-features/README.md`. Do not copy those steps here.\n- Studio-only runtime overrides (`ENABLED_FEATURES_*` env vars, `profile.disabled_features`) do not apply to docs. Docs reads the JSON at build time.\n- `ENABLED_FEATURES_OVERRIDE_DISABLE_ALL=true` makes every `isFeatureEnabled` call return `false`. The `embeddings:nimbus` and `embeddings:nimbus:refresh` scripts in `apps/docs/package.json` set it to build the filtered search index.\n\nWhere docs uses static flags:\n\n| Place                                                              | Effect                                                                        |\n| ------------------------------------------------------------------ | ----------------------------------------------------------------------------- |\n| `components/Navigation/NavigationMenu/NavigationMenu.constants.ts` | Nav items use an `enabled` value from `isFeatureEnabled([...])`.              |\n| `features/directives/Show.ts` (`$Show` in MDX)                     | `<$Show if=\"flag\">` keeps or removes content. `if=\"!flag\"` negates.           |\n| `lib/content-listings.utils.ts`                                    | A content listing item with a `feature` field drops out when the flag is off. |\n| `internals/generate-reference-markdown.ts`                         | Skips a reference whose `feature` flag is off.                                |\n\n## PostHog flags\n\n- `features/app.providers.tsx` wraps the app in `FeatureFlagProvider` from `packages/common/feature-flags.tsx`. It passes `enabled={IS_PLATFORM}`, so flags load only when the app runs on the platform.\n- The provider loads PostHog flags from the platform API path `/telemetry/feature-flags`.\n- Read them with `useFeatureFlags()` from `common`. Use the `posthog` object (flag key to value) and the `hasLoaded` boolean. Before `hasLoaded` is `true`, `posthog` is empty.\n- Local and staging only: the dev toolbar writes the `x-ph-flag-overrides` cookie, and the provider merges it into `posthog`. See `../../dev-toolbar-review/SKILL.md`.\n- Reload the page to apply a toolbar override. The provider ignores the cookie when no PostHog flags load, so the override does nothing in a local build.\n\n### Without Supabase access\n\n- A local build is not on the platform, so no PostHog flags load. Variant hooks return `control` (or the cached value from an earlier visit).\n- The URL override still works. `?<flag>=<variant>` shows that variant locally with no PostHog access.\n- The URL override applies only to the page that has it in its URL. Navigation links drop the query parameter, and the hook does not cache the override. After you follow a link, the page returns to `control` or the cached variant. Add the parameter to each page that you want to preview.\n- Only Supabase staff can create, change, or ramp PostHog flags. Contributors without access suggest an experiment in the PR or a GitHub issue. See `pm-the-docs` for both paths.\n\n## Variant hook pattern\n\nEach experiment reads its flag through a variant hook. To find the current hooks, search `apps/docs` for `captureExperimentExposure`. A variant hook follows these rules:\n\n1. Before the flags load, use the value from the last visit. The hook stores it in `localStorage`. The cached value can be any variant, not only `control`.\n2. Keep the cached value after `hasLoaded` is `true` if PostHog returns no flags (an empty response or a failed request). Only a non-empty response replaces the cache.\n3. If the cached or loaded flag value is not a known variant, use `control` unless a valid URL override applies.\n4. Let the `?<flag>=<variant>` query parameter override the variant. Only known variants count.\n5. Treat a `false` flag value as \"outside the rollout\", not as an assignment to `control`.\n6. Call `posthogClient.captureExperimentExposure(flag, { variant }, hasAccepted)` only when the loaded flag assigns the visitor and no URL override exists. Pass the consent value from `useConsentState`. A cached value never records an exposure.\n\nWrite tests for each variant hook, next to the hook.\n\nTo test a nav variant, override the nav constants for that variant and select them in a hook. Every nav consumer must read the nav items from that hook.\n\n## Gotchas\n\n- `$Show` reads static flags only. It cannot read PostHog flags. For a PostHog-driven change, branch in a React component with a variant hook.\n- The server renders `control`, so a visitor in another variant can see a flicker. To limit it, add an inline script to `app/layout.tsx`. The script reads the URL override or the cached value before paint and marks `<html>`. The changed component hides itself until hydration when that mark is set. Add a fallback that restores visibility if hydration does not complete.\n- A first-time visitor has no cached value, so the flicker can still happen on the first visit.\n- Exposure is not recorded for a forced variant (URL override) or for a cached value.\n- The cache is a `localStorage` value. A stale value can show the wrong variant until the flags load.\n\n## Related\n\n- `../../telemetry-standards/SKILL.md`, section \"Feature Flag Measurement\". It describes Studio patterns (`usePHFlag`). Use it for measurement ideas, not as a docs hook template.\n- `../../dev-toolbar-review/SKILL.md` for the override cookies and environment guards.\n- PMs: see `pm-the-docs`. Docs engineering owns creating and ramping PostHog flags. Contributors without Supabase access follow the OSS path in `pm-the-docs`.\n- Example (2026): the IA nav experiment, flag `docs-ia-mvp-v1`, in `features/IaNav/`. It can be removed after the experiment ends.\n", "skills/ask-the-docs/reference/federated-docs.md": "# Federated docs\n\n`apps/docs` can pull **markdown (and other files) from external GitHub repos**\nat **build or request time**, then render them inside the normal docs shell.\nContent lives in ecosystem repos (client libs, extensions, tooling) without\nduplicating into `apps/docs/content`.\n\nDocumented upstream in root **`DEVELOPERS.md`** → \"Federated docs.\"\n\n> **The maintainers treat this as a known liability.** See\n> [`docs-app-direction.md`](./docs-app-direction.md) for the full context\n> (lack of editorial oversight, brittle builds, quality drift). Treat\n> federated content as a liability when reviewing or debugging.\n\n## Why federate\n\n- **No duplication** — e.g. `supabase/vecs` docs stay in the vecs repo.\n- **Automatic sync** — fetched during the docs build (or on cached\n  revalidation), not hand-copied.\n- **Native feel** — same `GuideTemplate`, nav, typography, and search surface\n  as first-party guides.\n- **Flexible placement** — can embed external docs at nearly any path under\n  `/guides/`.\n\nTrade-off: **integration is manual and brittle**. Each federated section\nneeds its own route file, `pageMap`, link transform, and often custom remark\nplugins.\n\n## Build-time flow\n\n```mermaid\nflowchart TB\n  subgraph upstream [\"External repos\"]\n    PG[\"supabase/pg_graphql\"]\n    VECS[\"supabase/vecs\"]\n    WRAP[\"supabase/wrappers\"]\n    TF[\"supabase/terraform-provider-supabase\"]\n    CI[\"supabase/setup-cli\"]\n    SPL[\"supabase/splinter\"]\n    SKILLS[\"supabase/agent-skills\"]\n  end\n\n  subgraph fetch [\"Fetch layer — lib/octokit.ts\"]\n    APP[\"GitHub App auth<br/>DOCS_GITHUB_APP_*\"]\n    API[\"getGitHubFileContents()\"]\n    CACHE[\"fetchRevalidatePerDay<br/>(Next.js cache, retry up to 5x)\"]\n    APP --> API --> CACHE\n  end\n\n  subgraph route [\"Per-section route — app/guides/.../page.tsx\"]\n    MAP[\"pageMap<br/>(slug → remoteFile + meta)\"]\n    GET[\"getContent()\"]\n    MAP --> GET\n  end\n\n  subgraph transform [\"MDX pipeline\"]\n    RM[\"remark plugins<br/>Admonition, Tabs, removeTitle\"]\n    RH[\"rehype plugins<br/>linkTransform + rehypeSlug\"]\n    RM --> RH\n  end\n\n  subgraph render [\"Render\"]\n    GT[\"GuideTemplate / GuideMdxContent\"]\n    OUT[\"/docs/guides/...\"]\n    GT --> OUT\n  end\n\n  upstream --> API\n  GET --> RM\n  RH --> GT\n```\n\n### Step-by-step\n\n1. **Route file** defines `org`, `repo`, `branch` (or tag), `docsDir`, and a\n   **`pageMap`** — each entry maps a local slug to a remote markdown file\n   plus page metadata.\n2. **`getGitHubFileContents()`** fetches file content via a **GitHub App**\n   (`DOCS_GITHUB_APP_ID`, `DOCS_GITHUB_APP_INSTALLATION_ID`,\n   `DOCS_GITHUB_APP_PRIVATE_KEY`). Uses **once-per-day revalidation** by\n   default (`fetchRevalidatePerDay`).\n3. Raw markdown is passed through **remark/rehype plugins** to bridge dialect\n   gaps.\n4. **`linkTransform` + custom `urlTransform`** rewrite relative links from\n   the source repo into `/docs/guides/...` paths (or fall back to the upstream\n   docs site / GitHub).\n5. Output is rendered with **`GuideTemplate`** so federated pages look like\n   native guides. **Edit on GitHub** links point at the source repo file.\n\n> Note: `DEVELOPERS.md` still mentions `getStaticProps()` — the current App\n> Router implementation uses async server components + `generateStaticParams`\n> instead, but the idea is the same: fetch remote markdown at build time.\n\n## Federated sources (inventory)\n\n| Local path                                  | Source repo                            | Ref / branch                   | Pattern                                           |\n| ------------------------------------------- | -------------------------------------- | ------------------------------ | ------------------------------------------------- |\n| `/guides/graphql/*`                         | `supabase/pg_graphql`                  | `master`                       | Fully federated; `pageMap` per page               |\n| `/guides/ai/python/*`                       | `supabase/vecs`                        | `main`                         | Fully federated                                   |\n| `/guides/deployment/ci/*`                   | `supabase/setup-cli`                   | `gh-pages`                     | Fully federated                                   |\n| `/guides/deployment/terraform/*`            | `supabase/terraform-provider-supabase` | branch in `terraformConstants` | Federated prose pages                             |\n| `/guides/deployment/terraform/reference`    | same                                   | same                           | Federated **JSON schema** (not MDX)               |\n| `/guides/database/extensions/wrappers/*`    | `supabase/wrappers`                    | **release tag** `docs_v*.*.*`  | **Hybrid** — local MDX + federated catalog        |\n| `/guides/monitoring-and-debugging/advisors` | `supabase/splinter`                    | `main`                         | **Dynamic listing** — all `docs/*.md` files       |\n| AI Skills index                             | `supabase/agent-skills`                | `main`                         | Lists `skills/*/SKILL.md` at runtime              |\n| `$CodeSample` directive                     | various                                | commit SHA only                | Snippets via `getGitHubFileContentsImmutableOnly` |\n\n### Related patterns (not quite \"federated docs\")\n\n| Pattern              | Source                    | Mechanism                                                                                              |\n| -------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |\n| **AI prompts**       | `examples/prompts/*.md`   | Copied into `apps/docs/examples` at build (`codegen:examples`); nav injected in getting-started layout |\n| **Integrations nav** | Supabase `partners` table | `integrations/layout.tsx` fetches approved partners (external URLs)                                    |\n| **Reference docs**   | `apps/docs/spec/`         | Generated locally, not fetched from GitHub — see [`build-pipeline.md`](./build-pipeline.md)            |\n\n## How to spot a federated page in the repo\n\n- Look for a **dynamic route** (`[[...slug]]/page.tsx`, `[slug]/page.tsx`)\n  instead of content-only routing.\n- Search for **`// We fetch these docs at build time from an external repo`**\n  or **`getGitHubFileContents`**.\n- Check for a local **`pageMap`** array mapping slugs to `remoteFile` names.\n- GraphQL is listed in `PUBLISHED_SECTIONS` comments as _\"technically\n  published, but completely federated\"_ — no MDX under `content/guides/graphql/`.\n\nCanonical starter example:\n`apps/docs/app/guides/ai/python/[slug]/page.tsx` (vecs).\n\n## Link and markdown transforms\n\nExternal repos often use **MkDocs Material** or similar dialects. Supabase\ndocs do not understand those natively.\n\n### Remark plugins (`lib/mdx/plugins/`)\n\n| Plugin              | Purpose                                         |\n| ------------------- | ----------------------------------------------- |\n| `remarkAdmonition`  | `!!! note` / `!!! warning` → `<Admonition>`     |\n| `remarkTabs`        | pymdownx tab syntax → Supabase tabs             |\n| `remarkRemoveTitle` | Strip duplicate H1 when title comes from `meta` |\n\nNew upstream syntax may need a **new remark plugin** — called out explicitly\nin `DEVELOPERS.md`.\n\n### Link transform (`rehypeLinkTransform.ts`)\n\nEach federated route defines its own **`urlTransform`** function:\n\n- **Relative `.md` links** → mapped via `pageMap` to `/docs/guides/...` (or\n  section-relative slug).\n- **Unmapped relative links** → fall back to upstream site (e.g.\n  `https://supabase.github.io/vecs/...`) or raw GitHub blob URL (terraform).\n- **Absolute URLs** → passed through unchanged.\n\nWrappers additionally rewrites **`../assets/`** image paths to\n`raw.githubusercontent.com` URLs tied to the docs release tag.\n\n## Known failure modes\n\nFederated docs are a frequent source of **content quality issues** and\n**broken links**.\n\n### Broken or wrong links\n\n- **`pageMap` is manual** — upstream rename/remove → broken link until\n  someone updates the route file in `supabase/supabase`.\n- **`urlTransform` is per-section** — logic differs between graphql, vecs,\n  terraform, wrappers, etc.\n- **Unmapped pages fall back externally** — users leave the docs site or land\n  on a GitHub pages URL that may not match the embedded path structure.\n- **Absolute links in upstream** pass through untouched — may point at old\n  domains or anchors that moved.\n- **Cross-links between federated and native guides** are not automatic;\n  upstream authors don't know Supabase URL shapes.\n\n### Content quality\n\n- **No editorial gate in `apps/docs/content`** — upstream tone, structure,\n  and freshness vary.\n- **Dialect mismatches** — unsupported mkdocs extensions render as raw text\n  or fail MDX compile until a plugin is added.\n- **Duplicate titles** — mitigated by `removeTitle` / `removeRedundantH1`,\n  but layout can still look off.\n- **Stale content** — daily GitHub cache means upstream fixes may not appear\n  until revalidation; wrappers pin to **release tags** which can lag further.\n\n### Operational / dev failures\n\n- **GitHub App credentials required** — without `DOCS_GITHUB_APP_*`, fetches\n  fail. `$CodeSample` with external repos shows a **local dev warning** and\n  does not render real content.\n- **GitHub API timeouts** — `database-advisors` catches fetch errors and\n  shows a degraded view with a link to GitHub; build may still succeed with\n  partial content.\n- **Wrappers tag resolution** — `getLatestDocsTag()` queries `docs_v*.*.*`\n  tags; if tagging breaks, federated wrapper pages throw at build time.\n- **Dev mode gaps** — some federated routes return **empty\n  `generateStaticParams` in dev** (`IS_DEV`), so pages may 404 locally unless\n  you hit them via production build or adjust params.\n\n### Navigation drift\n\n- Sidebar entries for federated sections are often **hard-coded** in\n  `NavigationMenu.constants.ts` plus optional **`additionalNavItems`**\n  injection (prompts, integrations).\n- New upstream pages do not appear in nav until a maintainer adds them to\n  `pageMap` **and** navigation config.\n\n## When to federate vs copy into `content/`\n\nFederate when:\n\n- The canonical docs live in another repo and change frequently.\n- Maintainers of that repo own the content lifecycle.\n\nPrefer `content/guides/` when:\n\n- Editorial control, consistent voice, and link stability matter.\n- Content is tightly coupled to Supabase product UI and cross-links.\n\n## Related\n\n- [`app-map.md`](./app-map.md) — runtime + markdown export pipelines.\n- [`build-pipeline.md`](./build-pipeline.md) — where federated fetches sit\n  in the overall build.\n- [`docs-app-direction.md`](./docs-app-direction.md) — context on the\n  federated-docs liability and long-term direction.\n", "skills/ask-the-docs/reference/gotchas.md": "# `apps/docs` gotchas\n\nSpecific traps to watch for. One-liner per item.\n\n## Markdown pipeline\n\n- **JSX with no schema handler is unwrapped, not dropped.** Children pass\n  through as plain markdown. If a component should disappear entirely from\n  `.md` output, its handler must return `''`.\n- **Handlers run bottom-up.** Children are already-serialized markdown\n  strings by the time the parent handler sees them. Don't try to inspect\n  child JSX from a parent handler — use `node.children` only for structure\n  decisions.\n- **`mdxFlowExpression` / `mdxTextExpression` / `mdxjsEsm` are skipped.**\n  Anything wrapped in `{...}` won't appear in markdown output.\n- **`<AiPrompt id=\"…\" />` carries only an ID.** Prompt text lives in\n  `data/ai-prompts.data.ts`; don't inline prompt strings in MDX. Markdown\n  export handles the `PromptPanel` parts via\n  `internals/markdown-schema/PromptPanel.ts` (drops `PromptCopy`).\n- **`<$Partial>` recursion is silent.** A missing or unreadable partial is\n  dropped without error. Check `partials/` paths when content seems missing\n  from generated `.md`.\n- **`$Partial` `variables` are runtime-only unless wired in markdown export.**\n  `partialsRemark` substitutes `{{ .key }}` placeholders; `inlinePartials`\n  in `generate-guides-markdown.ts` must do the same or nested partials like\n  `path=\"{{ .prompt }}\"` fail silently (file not found).\n- **`GlassPanel` / `IconPanel` markdown handlers must include children.**\n  A handler that returns only `props.title` drops nested content. See\n  `internals/markdown-schema/Panel.ts`.\n\n## Markdown handler authoring\n\n- Handler files in `internals/markdown-schema/` must be named after the\n  component (`ContentListings.ts`, not `Listings.ts`). The registry key in\n  `generate-guides-markdown.ts` is the JSX element name.\n- Use the existing `withDocsBasePath` / `addBaseUrlPrefix` from\n  `internal-links.ts` for URL prefixing — don't roll your own.\n- If a handler needs data, the **JSX prop carries an `id`** and the handler\n  looks the data up from the same registry the runtime component uses. Don't\n  serialize data into JSX props.\n- Push a blank line right after each exported block (heading, description,\n  list). Keeps handler logic linear and avoids redundant trailing-empty-line\n  branches.\n\n## React / MDX components\n\n- `not-prose` is the canonical opt-out from the surrounding `.prose`\n  typography. Wrap structural layout in `not-prose`; keep headings outside so\n  they inherit prose styles.\n- `<Heading>` from `MdxBase.shared.tsx` is the canonical heading. Don't roll\n  your own `<h2>` / `<h3>` markup in MDX components — typography drifts.\n- `<Link>` from `next/link` works with `target=\"_blank\"` for external\n  destinations. Don't construct `<a>` directly.\n- A `useSendTelemetryEvent()` call inside a render path returns a function;\n  don't invoke it directly inside the JSX, build a callback first.\n- `$Show` reads static `enabled-features` flags only. It cannot read PostHog\n  flags. See [feature-flags.md](./feature-flags.md).\n\n## Data modules\n\n- Shared zod schemas for MDX components should use HTML heading levels\n  (`'h2'|'h3'|'h4'`), not markdown marker strings (`'##'`). Markdown markers\n  belong only in `internals/markdown-schema/` handlers (via a `Record`/`Map`\n  lookup).\n- `getXById(id)` lookups belong in `*.utils.ts`, not in the data file or the\n  schema file. Schema files hold schemas; data files hold data; utils hold\n  functions.\n- Each `.data.ts` exports named groups; the topic `index.ts` aggregates them\n  into a `Record<id, group>` map. The aggregation file is the single source\n  of truth for \"all valid IDs.\"\n\n## URL handling\n\n- External-link detection is **not** just `/^https?:\\/\\//`. Protocol-relative\n  (`//host`), `mailto:`, `tel:`, custom schemes — all external. Prefer\n  `new URL(href, base)` or a broader regex.\n- `withDocsBasePath('/guides/foo')` → `/docs/guides/foo`. Already-prefixed\n  URLs are passed through. Use it consistently in markdown output to avoid\n  broken links.\n\n\n## Build / CI\n\n- `pnpm build --filter=docs` runs markdown generation. A failure in\n  `generate-guides-markdown.ts` blocks the build — read its console output\n  rather than the cryptic CI error.\n- `pnpm format` from the repo root catches most oxfmt drift. Run it\n  before opening a PR; CI is unforgiving.\n- Auto-import sorting can silently shuffle imports across files you didn't\n  touch. Reset those files (`git checkout master -- <path>`) before pushing.\n\n## Federated docs\n\nSee [`federated-docs.md`](./federated-docs.md) for the full surface — the\nshort version:\n\n- **No GitHub App credentials in dev** = `$CodeSample` shows a warning, not\n  real content. Don't assume the page is broken.\n- **`pageMap` is manual.** Upstream renames break links until a maintainer\n  updates the route file.\n- **Wrappers pin to release tags** (`docs_v*.*.*`). If tagging breaks\n  upstream, build fails.\n- **Search and federated content interact poorly** — search infrastructure\n  is currently decoupled from the markdown generation. See\n  [`docs-app-direction.md`](./docs-app-direction.md).\n\n## Reference pages\n\n- SDK and CLI reference pages **don't go through the standard MDX path** —\n  they're too long for the AST parser in preview environments. Generated\n  from `spec/` instead, output to `features/docs/generated/**`.\n- Reference page length is a known UX/LLM problem. Long-term plan: split\n  into smaller modular pages. Management API is already one endpoint per\n  page (DOCS-1268); see [`management-api-reference.md`](./management-api-reference.md).\n- Management API Redocly bundle **omits `--dereferenced`** because of a\n  circular `$ref`. Don't \"fix\" that by adding `--dereferenced` without\n  checking codegen's cycle-safe `resolveRefs`.\n- Don't propose Scalar/Redoc/Elements as the Management API page UI\n  without covering markdown export, search, and `x-*` extension fields.\n\n## PR hygiene\n\n- No incidental import reorders or whitespace edits in a feature PR. Reset\n  files that are conceptually unchanged.\n- When resetting unrelated files (`git checkout master -- <path>`), verify the\n  result matches current `master` — rebases can resurrect stale file versions.\n- File names must match the primary export. Rename rather than aliasing on\n  import.\n- Single-use helpers stay in the consuming file. Don't add new files in\n  unrelated folders for one-shot utilities.\n- Two components with the same JSX shape and different classes → collapse\n  with a discriminator prop. Don't ship near-duplicates.\n", "skills/ask-the-docs/reference/graphql-endpoint.md": "# Docs GraphQL Architecture\n\n**Verify against live code** before depending on any path here — check\n`apps/docs/resources/` and `rootSchema.ts` for the current query list.\n\n## Overview\n\nThe `apps/docs/resources` folder contains the GraphQL endpoint architecture for the docs GraphQL endpoint at `/api/graphql`. It follows a modular pattern where each top-level query is organized into its own folder with consistent file structure.\n\n## Architecture Pattern\n\nEach top-level query lives in its own folder. `error/` is the fullest\nexample; `*Types.ts` and `*Sync.ts` are optional, and `globalSearch/`\nuses a `*Interface.ts` for its polymorphic result type instead. `guide/`,\n`reference/`, and `troubleshooting/` hold only model + schema files: they\nare result types surfaced through `searchDocs`, registered under `types`\nin `rootSchema.ts`, not top-level queries.\n\n```\nresources/\n├── queryObject/\n│   ├── queryObjectModel.ts      # Data models and business logic\n│   ├── queryObjectSchema.ts     # GraphQL type definitions\n│   ├── queryObjectResolver.ts   # Query resolver and arguments\n│   ├── queryObjectTypes.ts      # TypeScript interfaces (optional)\n│   └── queryObjectSync.ts       # Functions for syncing repo content to the database (optional)\n├── utils/\n│   ├── connections.ts         # GraphQL connection/pagination utilities\n│   └── fields.ts              # GraphQL field selection utilities\n├── rootSchema.ts              # Main GraphQL schema with all queries\n└── rootSync.ts                # Root sync script for syncing to database\n```\n\n## Folders and top-level queries\n\n| Folder             | Exposes                                                                              |\n| ------------------ | ------------------------------------------------------------------------------------ |\n| `globalSearch/`    | **searchDocs** — vector search across all docs content                               |\n| `error/`           | **error** (single code lookup) and **errors** (paginated collection)                 |\n| `guide/`           | `Guide` result type (search result), no top-level query                              |\n| `reference/`       | `ReferenceCLICommand`, `ReferenceManagementApi`, `ReferenceSDKFunction` result types |\n| `troubleshooting/` | `Troubleshooting` result type                                                        |\n| `rootSchema.ts`    | **schema** — introspection, plus the root that spreads the query objects above       |\n\n## Key Files\n\n### `rootSchema.ts`\n\n- Main GraphQL schema definition\n- Imports all resolvers and combines them into the root query\n- Defines the `RootQueryType` with all top-level fields\n\n### `utils/connections.ts`\n\n- Provides `createCollectionType()` for paginated collections\n- `GraphQLCollectionBuilder` for building collection responses\n- Standard pagination arguments and edge/node patterns\n\n### `utils/fields.ts`\n\n- `graphQLFields()` utility to analyze requested fields in resolvers\n- Used for optimizing data fetching based on what fields are actually requested\n\n## Creating a New Top-Level Query\n\nTo add a new GraphQL query, follow these steps:\n\n### 1. Create Query Folder Structure\n\n```bash\nmkdir resources/newQuery\ntouch resources/newQuery/newQueryModel.ts\ntouch resources/newQuery/newQuerySchema.ts\ntouch resources/newQuery/newQueryResolver.ts\n```\n\n### 2. Define GraphQL Schema (`newQuerySchema.ts`)\n\n```typescript\nimport { GraphQLObjectType, GraphQLString } from 'graphql'\n\nexport const GRAPHQL_FIELD_NEW_QUERY = 'newQuery' as const\n\nexport const GraphQLObjectTypeNewQuery = new GraphQLObjectType({\n  name: 'NewQuery',\n  description: 'Description of what this query returns',\n  fields: {\n    id: {\n      type: GraphQLString,\n      description: 'Unique identifier',\n    },\n    // Add other fields...\n  },\n})\n```\n\n### 3. Create Data Model (`newQueryModel.ts`)\n\n> [!NOTE]\n> The data model should be agnostic to GraphQL. It may import argument types\n> from `~/__generated__/graphql`, but otherwise all functions and classes\n> should be unaware of whether they are called for GraphQL resolution.\n\n> [!TIP]\n> The types in `~/__generated__/graphql` for a new endpoint will not exist\n> until the code generation in step 6 has run.\n\n```typescript\nimport { type RootQueryTypeNewQueryArgs } from '~/__generated__/graphql'\nimport { convertPostgrestToApiError, type ApiErrorGeneric } from '~/app/api/utils'\nimport { Result } from '~/features/helpers.fn'\nimport { supabase } from '~/lib/supabase'\n\nexport class NewQueryModel {\n  constructor(\n    public readonly data: {\n      id: string\n      // other properties...\n    }\n  ) {}\n\n  static async loadData(\n    args: RootQueryTypeNewQueryArgs,\n    requestedFields: Array<string>\n  ): Promise<Result<NewQueryModel[], ApiErrorGeneric>> {\n    // Implement data fetching logic\n    const result = new Result(\n      await supabase().from('your_table').select('*')\n      // Add filters based on args\n    )\n      .map((data) => data.map((item) => new NewQueryModel(item)))\n      .mapError(convertPostgrestToApiError)\n    return result\n  }\n}\n```\n\n### 4. Write the resolver (`newQueryResolver.ts`)\n\nMirror `error/errorResolver.ts`: wrap the model call in\n`Result.tryCatchFlat(..., convertUnknownToApiError, args)`, log and\n`Sentry.captureException` non-user errors, and return a `GraphQLError`\nwhose message is `'Internal Server Error'` when `error.isPrivate()`. For\npaginated results use `paginationArgs`, `createCollectionType()`, and\n`GraphQLCollectionBuilder.create()` from `utils/connections.ts`. Export a\nroot-field object keyed by the field constant:\n\n```typescript\nexport const newQueryRoot = {\n  [GRAPHQL_FIELD_NEW_QUERY]: {\n    description: 'What this query returns',\n    args: { id: { type: new GraphQLNonNull(GraphQLString) } },\n    type: GraphQLObjectTypeNewQuery,\n    resolve: resolveNewQuery,\n  },\n}\n```\n\n### 5. Register it in `rootSchema.ts`\n\nSpread the root-field object into `RootQueryType.fields` next to\n`...errorRoot`. Object types that are only reachable through an\ninterface (search results) go in the `types` array instead.\n\n### 6. Run codegen\n\n```bash\ncd apps/docs && pnpm run codegen:graphql\n```\n\nThis prints the schema to `__generated__/schema.graphql`\n(`scripts/graphqlSchema.ts`) and runs `graphql-codegen` (`codegen.ts`) to\nproduce `~/__generated__/graphql` — the `RootQueryType*Args` and resolver\ntypes the model and resolver import. `dev` and `build` run this\nautomatically as turbo dependencies.\n\n## Related\n\n- [`app-map.md`](./app-map.md) — where `resources/` sits in the app layout.\n- [`llm-agent-surface.md`](./llm-agent-surface.md) — `searchDocs` as an\n  agent entry point.\n- [`search-embeddings.md`](./search-embeddings.md) — the offline pipeline\n  that populates what `searchDocs` queries.\n- [`build-pipeline.md`](./build-pipeline.md) — where `codegen:graphql` runs\n  as a turbo dependency of `dev` / `build`.\n", "skills/ask-the-docs/reference/known-issues.md": "# `apps/docs` known issues\n\nWhat's currently broken, fragile, or intentionally being avoided. Read\nthis before depending on a piece of infrastructure for new work — if it's\nlisted here, expect it to change or fail in surprising ways.\n\nLiving document — update when a new fragility shows up in a PR or\nincident.\n\n## Federated documentation pipeline\n\n**Severity:** load-bearing fragility. Affects daily builds.\n\nThe docs site fetches markdown from external repos at build/request time\n(pg_graphql, vecs, wrappers, terraform-provider, setup-cli, splinter,\nagent-skills). Treat as a liability:\n\n- **Lack of oversight.** Quality control, linting, and formatting can't\n  be enforced because the source code isn't owned.\n- **Quality drift.** Inconsistent formatting, missing semicolons,\n  structural differences between federated and in-house content.\n- **Build brittleness.** Upstream fetches fail intermittently — retry\n  logic (up to 5x) is in place to mitigate. Builds can still degrade or\n  partially succeed.\n- **Manual `pageMap`.** Upstream rename/remove → broken links until a\n  maintainer updates the route file in `supabase/supabase`.\n- **Wrappers pins to release tags** (`docs_v*.*.*`). If tagging breaks\n  upstream, federated wrapper pages throw at build time.\n- **Dev mode gaps.** Some federated routes return empty\n  `generateStaticParams` in dev — pages may 404 locally unless hit via\n  production build.\n\nSee [`federated-docs.md`](./federated-docs.md) for the full mechanics and\nfailure modes. Implication: **don't add new federated sources** without\nstrong justification; **don't extend federated patterns** to new content\ntypes.\n\n## Troubleshooting articles come from a private repo\n\n**Severity:** ongoing sync issues.\n\nTroubleshooting articles moved from `apps/docs` to `/kb`. The build fetches\nthem into `apps/kb/src/content/troubleshooting/` from a private repo, so\nthey don't take direct contributions in `supabase/supabase`, and the site\ncan drift from the source repo. See `apps/kb/README.md`.\n\n## Reference pages can't go through standard MDX\n\n**Severity:** architectural constraint.\n\nSDK & CLI reference pages (e.g. JavaScript SDK, CLI) use a different\nrendering path than guides. Attempts to migrate them to MDX **failed\nbecause their length exceeded memory limits for the AST parser in\npreview environments.** They are generated from `spec/` instead, output\nto `features/docs/generated/**`.\n\nImplication: don't propose \"unify everything under MDX\" for reference\npages without addressing the memory ceiling first.\n\n## Reference page length\n\n**Severity:** UX and LLM usability issue.\n\nCurrent reference pages are far too long, making them difficult for\nhuman users to navigate and inefficient for LLMs to process. Long-term\ngoal: break them into specialized, modular pages for better readability\nand performance.\n\nImplication: new reference content should default to smaller, modular\npages.\n\n## Search infrastructure is decoupled and considered broken\n\n**Severity:** functional, but not trustworthy for new features.\n\nSearch relies on separate scripts and embeddings rather than the\nconsolidated markdown files (`build:guides-markdown` output). It is\ndecoupled from the main markdown-generation pipeline.\n\nImplication: **don't build new features against the current search\ninfrastructure** assuming it's stable. Expect it to be reworked as part\nof the refactoring direction.\n\n## Error tracking and Sentry signal quality\n\n**Severity:** noise-to-signal issue.\n\nSentry errors for slugs / 404s are often caused by:\n\n- Bots scanning paths.\n- Legacy URLs that no longer exist.\n- Broken inbound links from external sites.\n\nError tracking and instrumentation are relatively new and\nunderdeveloped. Implication: **don't trust noisy Sentry signals as proof\nof a real bug** without corroboration (reproduce locally, check the\nreferrer, etc.).\n\n## Component dispersion\n\n**Severity:** tech debt — accumulating cost, not a runtime failure.\n\nReact components for the docs app are inconsistently scattered across\nmultiple folders (`components/`, `features/docs/`, `features/ui/`,\n`layouts/`, etc.). No canonical place for \"this is a docs component.\"\n\nImplication:\n\n- Don't try to refactor the scatter as a side-quest in a feature PR.\n- Place new components by following the closest existing analogue, not\n  by inventing a new location.\n- Prioritize understanding the immediate task over mastering the whole\n  codebase.\n\n## \"One-to-one\" markdown fidelity is aspirational, not enforced\n\n**Severity:** ongoing improvement target.\n\nThe stated direction is one-to-one fidelity between rendered guides and\nthe markdown export produced by `generate-guides-markdown`. In practice,\ngaps exist:\n\n- Any MDX component without a `markdown-schema` handler is unwrapped to\n  its children, which may not match the rendered output.\n- `$Partial` recursion is silent — missing partials are dropped.\n- Some components (interactive, JSX-expression-heavy) inherently can't\n  serialize to markdown faithfully.\n\nImplication: when adding a component that should appear in markdown\noutput, **always add a handler** in `internals/markdown-schema/` and\nregister it in `generate-guides-markdown.ts`. See\n[`app-map.md`](./app-map.md) \"The two pipelines.\"\n\n## Related\n\n- [`docs-app-direction.md`](./docs-app-direction.md) — where the\n  refactoring is headed; what these issues are being driven toward.\n- [`federated-docs.md`](./federated-docs.md) — full mechanics of the\n  federation pipeline.\n- [`gotchas.md`](./gotchas.md) — smaller per-change traps; this file\n  is for load-bearing systemic issues.\n", "skills/ask-the-docs/reference/llm-agent-parity.md": "# LLM / agent content parity and onboarding\n\nCompanion to [`llm-agent-surface.md`](./llm-agent-surface.md) (routing and\ndiscovery). This file covers HTML↔markdown fidelity, search caveats, agent\nonboarding guides, and known stale wiring.\n\n**Verify against live code** before depending on any path here.\n\n## Two-pipeline parity for embedded content\n\nContent that renders on the HTML page is **not** automatically present\nin the `.md` export. Both pipelines must implement the same semantics.\n\nExample: framework quickstart **AI prompt blocks** (see\nsupabase/supabase#47543). Each quickstart embeds one by ID:\n\n```mdx\n<AiPrompt id=\"flask\" />\n```\n\nThe prompt text lives in `data/ai-prompts.data.ts` (`aiPrompts`, keyed by\n`id`); the MDX carries only the ID, following the registry pattern in\n[`app-map.md`](./app-map.md). An unknown ID throws at render time.\n\n| Pipeline     | Path                                                                                                                                    |\n| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- |\n| **HTML**     | `features/ui/AiPrompt.tsx` looks up the prompt and renders `PromptPanel` (copy + expand)                                                |\n| **Markdown** | `internals/markdown-schema/PromptPanel.ts` — handlers for the `PromptPanel` compound parts, registered in `generate-guides-markdown.ts` |\n\nThe markdown handlers keep `PromptTitle` (bold) and `PromptContent`, and\ndrop `PromptCopy` (clipboard-only duplicate). `AiPrompt` itself has no\nmarkdown handler: the HTML wrapper composes the compound children on the\nclient, so the `.md` export intentionally omits the copy panel.\n\n`$Partial` variable substitution (`lib/partials.utils.ts`, wired in both\n`partialsRemark` and `inlinePartials`) is still required for nested\npartials; it is not involved in the AI-prompt path.\n\nWhen adding content aimed at both humans and agents, always verify:\n\n```bash\ncd apps/docs && pnpm build:guides-markdown\n# then inspect public/markdown/guides/<same-path>.md for **AI Prompt**\n```\n\n## Programmatic search\n\n`/docs/api/graphql` exposes `searchDocs`, backed by embeddings generated\noffline via `scripts/search/generate-embeddings.ts`. Agents can request\nfull `content` in results.\n\n**Caveat:** search infrastructure is decoupled from the markdown export\npipeline and is considered fragile. See\n[`known-issues.md`](./known-issues.md) \"Search infrastructure is\ndecoupled and considered broken\" before building features on top of it.\n\n## Agent onboarding content\n\nFirst-party guides under `content/guides/ai-tools/`:\n\n| Page             | Purpose                           |\n| ---------------- | --------------------------------- |\n| `mcp.mdx`        | Supabase MCP server setup         |\n| `plugins.mdx`    | One-click MCP + skills bundle     |\n| `byo-mcp.mdx`    | Build your own MCP server         |\n| `ai-skills.mdx`  | Index of installable agent skills |\n| `ai-prompts.mdx` | Curated IDE prompts               |\n\nThe skills index is **federated** from `supabase/agent-skills` at\nruntime (`AiSkills.utils.ts`). See [`federated-docs.md`](./federated-docs.md).\n\n## In-flux / stale wiring\n\n- `llms-full.txt` fetches reference markdown from\n  `${NEXT_PUBLIC_DOCS_URL}/markdown/reference/<slug>.md` at runtime.\n\n## Related\n\n- [`llm-agent-surface.md`](./llm-agent-surface.md) — routing, negotiation,\n  entry points, bulk vs per-page retrieval.\n- [`app-map.md`](./app-map.md) — two-pipeline model, directory layout.\n- [`federated-docs.md`](./federated-docs.md) — agent-skills federation.\n- [`known-issues.md`](./known-issues.md) — search fragility, reference\n  page length.\n", "skills/ask-the-docs/reference/llm-agent-surface.md": "# LLM and agent consumption surface\n\nHow `apps/docs` exposes machine-readable content and how that relates to\n`apps/www`. For markdown export fidelity and agent onboarding pages, see\n[`llm-agent-parity.md`](./llm-agent-parity.md). For the markdown export\npipeline itself, see [`app-map.md`](./app-map.md) \"The two pipelines.\"\n\nVerified at: 3089aa3f67 (2026-11-25).\n\n**Verify against live code** — several pieces here span two apps and\nchange independently.\n\n## Scope boundary\n\n| App             | Role                                                                                                               |\n| --------------- | ------------------------------------------------------------------------------------------------------------------ |\n| **`apps/docs`** | Produces markdown exports, serves per-guide `.md`, reference static files, GraphQL search, agent onboarding guides |\n| **`apps/www`**  | Serves discovery indexes (`/llms.txt`, `/llms-full.txt`) and product-page `.md` negotiation                        |\n\n`llms.txt` is **not** a route in `apps/docs`. It is assembled at runtime\nby `apps/www/app/llms.txt/route.ts`, reading guide directory names from\n`apps/docs/content/guides/` and linking to docs + reference exports.\nThere is no static `llms.txt` file in the repo — the www route handler\nbuilds it on each request.\n\n### Key source files\n\n| What                  | Monorepo path                                    | Public URL (prod)                                 |\n| --------------------- | ------------------------------------------------ | ------------------------------------------------- |\n| `llms.txt` route      | `apps/www/app/llms.txt/route.ts`                 | `https://supabase.com/llms.txt`                   |\n| `llms-full.txt` route | `apps/www/app/llms-full.txt/route.ts`            | `https://supabase.com/llms-full.txt`              |\n| Guide proxy           | `apps/docs/proxy.ts`                             | Negotiates markdown, rewrites to guides-md        |\n| WWW proxy             | `apps/www/proxy.ts`                              | Product-page markdown negotiation                 |\n| Negotiation logic     | `packages/common/markdown-negotiation.ts`        | Shared by both proxy files                        |\n| Guides markdown API   | `apps/docs/app/api/guides-md/[...slug]/route.ts` | Reads `public/markdown/guides/` at runtime        |\n| Markdown manifest     | `apps/docs/public/markdown/manifest.json`        | Slugs eligible for `.md` negotiation              |\n\n## Build outputs → serving paths\n\n```mermaid\nflowchart TB\n  subgraph docsApp [\"apps/docs build\"]\n    GM[\"build:guides-markdown\"]\n    RM[\"build:reference-markdown\"]\n    GZ[\"build:gz-archive\"]\n    GM --> outGuides[\"public/markdown/guides/\"]\n    RM --> outRef[\"public/markdown/reference/\"]\n    GZ --> tarball[\"public/docs.tar.gz\"]\n  end\n\n  subgraph docsServe [\"apps/docs runtime\"]\n    mw[\"proxy.ts\"]\n    guidesMd[\"api/guides-md\"]\n    crawlers[\"api/crawlers\"]\n    gql[\"api/graphql searchDocs\"]\n    mw --> guidesMd\n  end\n\n  subgraph wwwApp [\"apps/www\"]\n    llmsTxt[\"/llms.txt\"]\n    llmsFull[\"/llms-full.txt\"]\n  end\n\n  outGuides --> guidesMd\n  outGuides --> llmsFull\n  outRef --> llmsFull\n  outGuides --> llmsTxt\n  gql --> guidesMd\n```\n\n## Entry points\n\n| URL                                      | Owner       | Source                                                                                        |\n| ---------------------------------------- | ----------- | --------------------------------------------------------------------------------------------- |\n| `/llms.txt`                              | `apps/www`  | `app/llms.txt/route.ts` — index of guide sections + reference links                           |\n| `/llms-full.txt`                         | `apps/www`  | `app/llms-full.txt/route.ts` — concatenated guides + reference + product overviews            |\n| `/docs/guides/<path>.md`                 | `apps/docs` | Proxy → `app/api/guides-md/[...slug]/route.ts` reads `public/markdown/guides/`                |\n| `/docs/markdown/reference/<lib>.md`      | `apps/docs` | Static file from `public/markdown/reference/` (build output)                                  |\n| `/docs/docs.tar.gz`                      | `apps/docs` | `internals/generate-gz-archive.ts` tarballs all of `public/markdown/`                         |\n| `/docs/api/graphql` (`searchDocs`)       | `apps/docs` | Vector search over embedded doc sections — see [`llm-agent-parity.md`](./llm-agent-parity.md) |\n| `/docs/reference/<sdk>/<section>` (bots) | `apps/docs` | `isbot()` → `app/api/crawlers/route.ts` (simplified HTML, not markdown)                       |\n\nHomepage alternate link points agents at the full dump:\n`https://supabase.com/llms-full.txt` (`apps/docs/app/page.tsx`).\n\n## Audience routing (humans vs agents vs crawlers)\n\nEvery guide exists in two forms from the same MDX source:\n\n| Form         | Produced by                                                          | Served to                            |\n| ------------ | -------------------------------------------------------------------- | ------------------------------------ |\n| **HTML**     | Live MDX render (`partialsRemark`, React components)                 | Humans in a browser                  |\n| **Markdown** | Prebuild (`generate-guides-markdown.ts` → `public/markdown/guides/`) | Live-fetch agents and bulk downloads |\n\n`apps/docs/proxy.ts` is the bouncer for guide requests. It calls\n`negotiateMarkdown()` from `packages/common/markdown-negotiation.ts` and\nchecks `public/markdown/manifest.json` before serving markdown.\n\n```mermaid\nflowchart TD\n  req[Guide request] --> mdSuffix{URL ends in .md?}\n  mdSuffix -->|yes| markdown[Serve markdown]\n  mdSuffix -->|no| agentUA{Live-fetch agent UA?}\n  agentUA -->|yes| markdown\n  agentUA -->|no| accept{Accept prefers markdown?}\n  accept -->|yes| markdown\n  accept -->|no| html[Serve HTML page]\n  markdown --> rewrite[\"Rewrite to /api/guides-md/...\"]\n  rewrite --> file[\"Read public/markdown/guides/...\"]\n```\n\n### Who gets what\n\n| Audience                                 | Typical request                                                                  | Format   | Notes                                                                                |\n| ---------------------------------------- | -------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------ |\n| **Human (browser)**                      | `/docs/guides/.../nextjs`                                                        | HTML     | Default — no special headers                                                         |\n| **Live-fetch agent**                     | Same URL with `Claude-User`, `ChatGPT-User`, `PerplexityBot`, or `Claude-Web` UA | Markdown | Auto-negotiated even without `.md` suffix                                            |\n| **Live-fetch agent**                     | `/docs/guides/.../nextjs.md` or `Accept: text/markdown`                          | Markdown | Explicit request                                                                     |\n| **SEO bot** (Googlebot)                  | Guide URL                                                                        | HTML     | Same page humans see; `isbot()` markdown rewrite applies only to **reference** pages |\n| **Training crawler** (GPTBot, ClaudeBot) | Guide URL                                                                        | HTML     | Allowed by `robots.txt` but **not** given alternate markdown — avoids cloaking       |\n| **Bulk ingest**                          | `/llms-full.txt`, `/docs/docs.tar.gz`                                            | Markdown | Reads prebuilt `public/markdown/` files                                              |\n\nHumans see interactive UI (copy buttons, styled panels). Agents and bulk\ntools read the pre-generated `.md` transcript — not the live HTML DOM.\n\n### Agent discovery\n\nAgents that don't know a specific URL can start from:\n\n- `/llms.txt` — section index with links to `.md` paths\n- `/llms-full.txt` — concatenated guides + reference + product overviews\n- `rel=\"alternate\" type=\"text/markdown\"` on each guide page\n  (`GuidesMdx.utils.tsx` → `${BASE_PATH}${pathname}.md`)\n- Docs homepage alternate → `https://supabase.com/llms-full.txt`\n\n## Content negotiation\n\nShared logic lives in `packages/common/markdown-negotiation.ts`, used by\nboth `apps/docs/proxy.ts` and `apps/www/proxy.ts`.\n\nMarkdown is served when:\n\n- The URL ends in `.md`\n- `Accept: text/markdown` wins over HTML (q-value comparison)\n- The user-agent matches **live-fetch agents**: `Claude-User`,\n  `Claude-Web`, `ChatGPT-User`, `PerplexityBot`\n\nTraining crawlers (`GPTBot`, `ClaudeBot`, etc.) are **not** given\nalternate markdown — they are governed by `robots.txt` to avoid\ncloaking penalties.\n\nOn guides, negotiated requests rewrite to `/api/guides-md/<slug>`.\nEach guide page advertises its markdown alternate in metadata via\n`GuidesMdx.utils.tsx` (`text/markdown` → `${BASE_PATH}${pathname}.md`).\n\n404 responses from `guides-md` are also markdown and include\n`searchDocs` suggestions — useful when an agent fetches a stale URL.\n\n## Bulk vs per-page retrieval\n\n| Strategy                            | Best for                                          |\n| ----------------------------------- | ------------------------------------------------- |\n| `/llms.txt`                         | Discovering available sections and reference libs |\n| `/llms-full.txt`                    | One-shot full ingest                              |\n| `/docs/docs.tar.gz`                 | Offline/batch ingest of all generated markdown    |\n| `/docs/guides/<path>.md`            | Single guide page                                 |\n| `/docs/markdown/reference/<lib>.md` | Single reference lib export                       |\n\nReference pages do **not** use the same `Accept: text/markdown`\nnegotiation as guides. Reference markdown comes from the static export\nand `llms-full.txt`, not from proxy negotiation.\n\n## Related\n\n- [`llm-agent-parity.md`](./llm-agent-parity.md) — two-pipeline fidelity,\n  search caveat, agent onboarding pages, in-flux wiring.\n- [`app-map.md`](./app-map.md) — two-pipeline model, directory layout.\n- [`build-pipeline.md`](./build-pipeline.md) — turbo tasks that\n  produce markdown exports and the tarball.\n- [`docs-app-direction.md`](./docs-app-direction.md) — one-to-one\n  markdown fidelity goal.\n- [`known-issues.md`](./known-issues.md) — reference page length,\n  search fragility.\n", "skills/ask-the-docs/reference/management-api-reference.md": "# Management API reference generation\n\nHow `/docs/reference/api/*` is built from the live Management API OpenAPI\nspec. Verify against `apps/docs/spec/Makefile` and\n`features/docs/Reference.generated.script.ts` before acting — paths drift.\n\n## Pipeline\n\n```mermaid\nflowchart LR\n  live[\"api.supabase.com<br/>/api/v1-json + v2-json\"]\n  raw[\"spec/api_v{1,2}_openapi.json\"]\n  redocly[\"Redocly bundle<br/>(no --dereferenced)\"]\n  bundled[\"spec/transforms/<br/>api_v*_openapi_deparsed.json\"]\n  sections[\"common-api-sections.json\"]\n  codegen[\"codegen:references:legacy\"]\n  gen[\"features/docs/generated/<br/>api.latest.*.json\"]\n  page[\"ApiReferencePage →<br/>ApiEndpointSection\"]\n  md[\"public/markdown/reference/api.md\"]\n\n  live --> raw --> redocly --> bundled\n  bundled --> sections\n  bundled --> codegen\n  sections --> codegen\n  codegen --> gen --> page\n  gen --> md\n```\n\n1. **Download** — `make download.api.v1` in `apps/docs/spec/` curls the\n   live OpenAPI into `api_v1_openapi.json` / `api_v2_openapi.json`.\n2. **Bundle** — `make dereference.api.v1` runs Redocly CLI\n   (`@redocly/cli`) `bundle` into `transforms/*_deparsed.json`.\n   Management API deliberately omits `--dereferenced` (circular `$ref` in\n   `APIErrorObject.issues`). `$refs` are resolved later in codegen with a\n   cycle guard.\n3. **Nav sections** — `sections/generateMgmtApiSections.cts` walks\n   operations/tags into `common-api-sections.json`.\n4. **Codegen** — `codegen:references:legacy`\n   (`Reference.generated.script.ts`) merges v1+v2, resolves refs, writes\n   `api.latest.endpointsById.json`, `sections.json`, `flat.json`,\n   `bySlug.json` under `features/docs/generated/`.\n5. **Runtime** — `/reference/api/[operation]` via `ApiReferencePage` →\n   `SectionSwitch` → `ApiEndpointSection` (custom React, not MDX). One\n   endpoint per page (DOCS-1268). Hand-written intro MDX lives under\n   `docs/ref/api/`.\n6. **Agents** — `generate-reference-markdown.ts` exports the same data to\n   `public/markdown/reference/api.md`.\n\nLegacy EJS (`generator/api.ts` + `ApiTemplate.ts`) is not the live path.\n\n## Redocly today (bundle / lint)\n\n| Job    | Where                                                                      | Notes                                                               |\n| ------ | -------------------------------------------------------------------------- | ------------------------------------------------------------------- |\n| Bundle | `make dereference.api.v1` (and sibling targets for auth/storage/analytics) | Invoked via `npx --package=@redocly/cli redocly bundle`             |\n| Lint   | `make validate.analytics.v0` only                                          | `redocly lint --extends=minimal`. Management API has no lint target |\n\nRedocly is the OpenAPI **toolchain** (bundle/lint), not the page renderer.\n\n## Rendering: keep the custom path\n\nPages render via custom React (`ApiEndpointSection`), not Scalar / Redoc /\nStoplight Elements. Reasons (see also [`adding-features.md`](./adding-features.md)\nand [`known-issues.md`](./known-issues.md)):\n\n- **Two pipelines** — HTML + markdown export + GraphQL search share one\n  `IApiEndPoint` / generated-JSON shape. A third-party viewer forks that.\n- **Custom extensions** — `x-oauth-scope`, `x-allowed-plans`,\n  `x-fga-permissions` need first-class rendering.\n- **Modular pages** — DOCS-1268 already split the monolithic API page;\n  embedding a full-spec viewer would reverse that.\n- **Surface** — new dep + theming + parity work fights docs-app direction\n  (reduce surface, don't add parallel renderers).\n\nPrefer improving `ApiEndpointSection` / schema helpers, or deepening\nRedocly lint on download/transform. Do not propose swapping the renderer\nfor an OpenAPI UI kit without addressing markdown/search/`x-*` parity.\n\nClosest CLI substitutes if Redocly were unavailable: `@apidevtools/swagger-parser`\nor `swagger-cli` for bundle; Spectral for lint. Switching buys little while\nthe custom cycle-safe resolve remains required.\n\n## Key files\n\n| Path                                                    | Role                                         |\n| ------------------------------------------------------- | -------------------------------------------- |\n| `apps/docs/spec/Makefile`                               | download / Redocly bundle / section generate |\n| `apps/docs/spec/sections/generateMgmtApiSections.cts`   | OpenAPI → `common-api-sections.json`         |\n| `apps/docs/features/docs/Reference.generated.script.ts` | merge, resolve refs, write `api.latest.*`    |\n| `apps/docs/features/docs/Reference.api.utils.ts`        | `IApiEndPoint` + schema display helpers      |\n| `apps/docs/features/docs/Reference.apiPage.tsx`         | route → one operation page                   |\n| `apps/docs/features/docs/Reference.sections.tsx`        | `ApiEndpointSection` UI                      |\n| `apps/docs/internals/generate-reference-markdown.ts`    | agent markdown export                        |\n\n## Scoped personal access token permission tables\n\nThe \"Personal Access Tokens\" guide's permission and MCP tables are generated\nfrom the Management API specs, MCP permission map, and the same shared catalog\nStudio uses. Regenerate `content/_partials/access-control/scoped_pat_*.mdx` with\n`make -C apps/docs/spec generate.partials.access-control`. Docs Tests runs this\non relevant pull requests and fails if the partials drift; the weekly Management\nAPI update also runs it after refreshing the live inputs.\n\n## Related\n\n- [`build-pipeline.md`](./build-pipeline.md) — where `codegen:references`\n  sits in the turbo graph.\n- [`app-map.md`](./app-map.md) — reference vs guides routing.\n- [`known-issues.md`](./known-issues.md) — reference pages avoid standard\n  MDX; length / modularization direction.\n- [`llm-agent-surface.md`](./llm-agent-surface.md) — markdown export\n  consumption.\n", "skills/ask-the-docs/reference/search-embeddings.md": "# Documentation Embeddings Generation System\n\n**Verify against live code** before depending on any path here. Search\ninfrastructure is on the [`known-issues.md`](./known-issues.md) list\n(decoupled from the markdown export pipeline and considered fragile) —\ncheck there before building on it.\n\n## Overview\n\nThe documentation embeddings generation system processes various documentation sources and uploads their metadata to a database for semantic search functionality. The system is located in `apps/docs/scripts/search/` and works by:\n\n1. **Discovering content sources** from multiple types of documentation\n2. **Processing content** into structured sections with checksums\n3. **Generating embeddings** using OpenAI's text-embedding-ada-002 model\n4. **Storing in database** with vector embeddings for semantic search\n\n## Architecture\n\n### Main Entry Point\n\n- `apps/docs/scripts/search/generate-embeddings.ts` - Main script that orchestrates the entire process\n- Supports `--refresh` flag to force regeneration of all content\n\n### Content Sources (`sources/` directory)\n\n#### Base Classes\n\n- `BaseLoader` - Abstract class for loading content from different sources\n- `BaseSource` - Abstract class for processing and formatting content\n\n#### Source Types\n\n1. **Markdown Sources** (`apps/docs/scripts/search/sources/markdown.ts`)\n   - Processes `.mdx` files from guides and documentation\n   - Extracts frontmatter metadata and content sections\n\n2. **Reference Documentation** (`apps/docs/scripts/search/sources/reference-doc.ts`)\n   - **OpenAPI References** - Management API documentation from OpenAPI specs\n   - **Client Library References** - JavaScript, Dart, Python, C#, Swift, Kotlin SDKs\n   - **CLI References** - Command-line interface documentation\n   - Processes YAML/JSON specs and matches with common sections\n\n3. **GitHub Discussions** (`apps/docs/scripts/search/sources/github-discussion.ts`)\n   - Fetches troubleshooting discussions from GitHub using GraphQL API\n   - Uses GitHub App authentication for access\n\n4. **Partner Integrations** (`apps/docs/scripts/search/sources/partner-integrations.ts`)\n   - Fetches approved partner integration documentation from Supabase database\n   - Technology integrations only (excludes agencies)\n\n### Processing Flow\n\n1. **Content Discovery**: Each source loader discovers and loads content files/data\n2. **Content Processing**: Each source processes content into:\n   - Checksum for change detection\n   - Metadata (title, subtitle, etc.)\n   - Sections with headings and content\n3. **Change Detection**: Compares checksums against existing database records\n4. **Embedding Generation**: Uses OpenAI to generate embeddings for new/changed content\n5. **Database Storage**: Stores in `page` and `page_section` tables with embeddings\n6. **Cleanup**: Removes outdated pages using version tracking\n\n### Database Schema\n\n- **`page`** table: Stores page metadata, content, checksum, version\n- **`page_section`** table: Stores individual sections with embeddings, token counts\n\n## Related\n\n- [`known-issues.md`](./known-issues.md) — search infrastructure fragility.\n- [`llm-agent-parity.md`](./llm-agent-parity.md) — `searchDocs` caveats for\n  agents.\n- [`graphql-endpoint.md`](./graphql-endpoint.md) — the `searchDocs` query\n  that reads these embeddings.\n- [`build-pipeline.md`](./build-pipeline.md) — embeddings are generated\n  offline (`pnpm run embeddings`, run by `.github/workflows/search.yml`),\n  not as part of the site build.\n", "skills/clickhouse-logs-queries/SKILL.md": "---\nname: clickhouse-logs-queries\ndescription: >-\n  Write, review, and migrate Supabase logs queries against the ClickHouse-backed\n  `logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task\n  involves Logs Explorer SQL, the `log_attributes` map, querying a log `source`\n  (edge_logs, postgres_logs, auth_logs, etc.), translating an old BigQuery\n  `cross join unnest(metadata)` logs query to ClickHouse, or wiring analytics log\n  SQL in `apps/studio/data/logs` and `apps/studio/components/interfaces/Settings/Logs`.\n  Reach for it even when the user just says \"logs query\", \"Logs Explorer\", or\n  pastes a BigQuery logs query to convert, not only when they name ClickHouse.\n---\n\n# Querying Supabase logs (ClickHouse)\n\nSupabase logs live in a single ClickHouse `logs` table, served by the\n`logs.all.otel` analytics endpoint. Every log line from every part of the stack\nis one row in this table, tagged by a `source` column. This replaces the older\nBigQuery model, where each service had its own table and fields were reached\nthrough `cross join unnest(metadata)`.\n\nTwo kinds of work use this skill, and they share the same SQL model:\n\n1. **Writing or reviewing a logs query** (in the Logs Explorer or anywhere a raw\n   ClickHouse logs query is needed). Start here in this file.\n2. **Wiring a logs query in the Studio codebase** (branded analytics SQL, the\n   endpoint picker, the OTEL query builders). Read\n   [references/codebase-integration.md](references/codebase-integration.md).\n\nIf you are converting an existing BigQuery logs query, read\n[references/bigquery-migration.md](references/bigquery-migration.md) for the full\ntranslation table.\n\n## The logs table\n\nEach row has a small set of real columns. Everything specific to a service lives\nin `log_attributes`.\n\n| Column           | Type                  | Notes                                                 |\n| ---------------- | --------------------- | ----------------------------------------------------- |\n| `id`             | `String`              | Unique log identifier.                                |\n| `timestamp`      | `DateTime64` (UTC)    | When the log was produced. Order/compare it directly. |\n| `event_message`  | `String`              | The raw log line.                                     |\n| `severity_text`  | `String`              | Log level, when the source sets one.                  |\n| `source`         | `String`              | The service the log came from. Always filter on this. |\n| `log_attributes` | `Map(String, String)` | Structured per-source fields, keyed by a dotted path. |\n\n`timestamp` is formatted like `2026-06-22T09:34:06.215000` (ISO 8601, microsecond\nprecision, no trailing `Z`). In the Logs Explorer the selected time range is\napplied for you, so you rarely need to write a `timestamp` filter by hand.\n\nA minimal, well-formed query. Lead with a comment naming the query, filter by\n`source`, and always `limit`:\n\n```sql\n-- recent edge requests\nselect timestamp, event_message\nfrom logs\nwhere source = 'edge_logs'\norder by timestamp desc\nlimit 100;\n```\n\n## Sources\n\n`source` selects the service. The common ones:\n\n- `edge_logs` — API gateway requests and responses\n- `postgres_logs` — database statements and errors (also where pg_cron logs live)\n- `auth_logs` — authentication and authorization activity\n- `function_edge_logs` — edge function requests and responses\n- `function_logs` — `console` output from inside edge functions\n- `storage_logs` — object upload and retrieval activity\n- `realtime_logs` — Realtime client connections\n- `postgrest_logs`, `supavisor_logs`, `pgbouncer_logs` — mostly `id`, `timestamp`, `event_message`\n\nThe Logs Explorer **Field Reference** drawer lists every source and the fields it\nactually sets. When in doubt about a key, discover it from real data rather than\nguessing (see below).\n\n## Reading fields from log_attributes\n\n`log_attributes` maps a string key to a string value. Read a field with bracket\naccess. There are no unnesting joins:\n\n```sql\nselect\n  log_attributes['request.method'] as method,\n  log_attributes['request.path'] as path,\n  log_attributes['response.status_code'] as status\nfrom logs\nwhere source = 'edge_logs'\n```\n\nThe key keeps the dotted path that BigQuery expressed through nested structs, with\nthe `metadata` root dropped: BigQuery `metadata.request.method` becomes\n`log_attributes['request.method']`. Keep the full prefix — `request.cf.country`\nis `log_attributes['request.cf.country']`, not `log_attributes['cf.country']`.\n\nCommon keys by source:\n\n- `edge_logs`: `request.method`, `request.path`, `request.search`, `response.status_code`, `identifier`\n- `postgres_logs`: `parsed.error_severity`, `parsed.detail`, `parsed.hint`, `parsed.query`, `identifier`\n- `auth_logs`: `level`, `status`, `path`, `msg`, `error`\n- `function_edge_logs`: `response.status_code`, `request.method`, `request.pathname`, `function_id`, `execution_id`, `execution_time_ms`\n- `function_logs`: `event_type`, `function_id`, `execution_id`, `level`\n\n### Numeric fields are strings\n\nMap values are always strings. To compare or aggregate a numeric field, wrap it in\n`toInt32OrZero`, which returns `0` for missing or non-numeric values so it never\nerrors on partial data:\n\n```sql\nselect count() as server_errors\nfrom logs\nwhere source = 'edge_logs'\n  and toInt32OrZero(log_attributes['response.status_code']) between 500 and 599\n```\n\n### Discover the keys a source sets\n\nRead `mapKeys` from recent rows rather than guessing key names:\n\n```sql\nselect arrayJoin(mapKeys(log_attributes)) as key, count() as n\nfrom logs\nwhere source = 'postgres_logs'\ngroup by key\norder by n desc\nlimit 100;\n```\n\n`arrayJoin(mapKeys(...))` flattens the map keys into one row per key so you can\nrank them by frequency. (The Studio codebase does exactly this for the Field\nReference drawer and to feed real keys to the AI rewrite.)\n\n## ClickHouse vs BigQuery functions\n\nThese are the substitutions that trip people up most:\n\n| Need               | BigQuery                      | ClickHouse                                   |\n| ------------------ | ----------------------------- | -------------------------------------------- |\n| Count rows         | `count(*)`                    | `count()`                                    |\n| Regex match        | `regexp_contains(x, 'p')`     | `match(x, 'p')`                              |\n| Substring match    | `x like '%p%'`                | `x ilike '%p%'` (case-insensitive) or `like` |\n| Numeric coercion   | `cast(x as int64)`            | `toInt32OrZero(x)`                           |\n| Read the timestamp | `cast(timestamp as datetime)` | `timestamp` (use the column directly)        |\n| Map keys           | n/a (used unnest)             | `mapKeys(log_attributes)`                    |\n\nThe `logs.all.otel` analytics endpoint (and the Logs Explorer on top of it)\nrejects `count(*)` and `select *` — use `count()` and list the columns you need.\n(Raw ClickHouse supports both; this is a constraint of the logs query surface.)\n\n## Best practices\n\nThese keep queries correct and cheap. Log tables are large; an unbounded scan\nreads far more data than you need.\n\n- **Start every query with an identifying comment** (e.g. `-- errors since last deploy`). It labels the query in logs and review, and makes each of several queries in a file easy to tell apart.\n- **Always include a `LIMIT`.** Even for aggregates while you iterate.\n- **Always query `from logs where source = '...'`.** There is no per-service table (no `edge_logs`, `postgres_logs`, etc. table) — there is one `logs` table, and `source` scopes it to a service. Filtering by `source` is required, not just an optimization.\n- **Keep the time range tight.** A smaller window returns results faster.\n- **Filter on the real columns** (`source`, `timestamp`) before reaching into\n  `log_attributes`.\n- **Order by `timestamp desc`** to see the most recent logs first.\n- **Use `count()`**, not `count(*)` or `select *`.\n\n## Worked examples\n\nRequests by status code:\n\n```sql\nselect\n  toInt32OrZero(log_attributes['response.status_code']) as status,\n  count() as count\nfrom logs\nwhere source = 'edge_logs'\ngroup by status\norder by count desc\nlimit 50\n```\n\nAuth errors:\n\n```sql\nselect timestamp, event_message, log_attributes['msg'] as message\nfrom logs\nwhere source = 'auth_logs'\n  and log_attributes['level'] in ('error', 'fatal')\norder by timestamp desc\nlimit 100\n```\n\nSearch the raw message:\n\n```sql\nselect timestamp, event_message\nfrom logs\nwhere source = 'postgres_logs'\n  and event_message ilike '%deadlock%'\norder by timestamp desc\nlimit 100\n```\n\nPostgres errors grouped by severity (the canonical unnest-to-map conversion):\n\n```sql\nselect log_attributes['parsed.error_severity'] as severity, count() as count\nfrom logs\nwhere source = 'postgres_logs'\n  and log_attributes['parsed.error_severity'] in ('ERROR', 'FATAL', 'PANIC')\ngroup by severity\norder by count desc\nlimit 100\n```\n\n## When the user pastes a BigQuery query\n\nConvert it rather than running it as-is. The mechanical steps (drop the\nper-service table for `from logs where source = ...`, remove every\n`cross join unnest(...)`, rewrite unnest-alias columns as `log_attributes['...']`\nlookups, swap the functions above) are spelled out with a full before/after in\n[references/bigquery-migration.md](references/bigquery-migration.md). The Logs\nExplorer also has a built-in **Rewrite to ClickHouse** action that does this with\nAI; point users to it for one-off conversions in the dashboard.\n", "skills/clickhouse-logs-queries/references/bigquery-migration.md": "# Migrating a BigQuery logs query to ClickHouse\n\nThe old logs engine gave each service its own table and exposed structured fields\nthrough repeated `cross join unnest(...)` over a nested `metadata` column. The\nClickHouse engine has one `logs` table and a flat `log_attributes` map. Conversion\nis mechanical once you internalize the mapping.\n\n## The five steps\n\n1. **Replace the table with `logs` plus a `source` filter.** The old table name is\n   the `source` value: `from postgres_logs as t` becomes\n   `from logs where source = 'postgres_logs'`. Never select from a per-service\n   table name (`postgres_logs`, `edge_logs`, ...) on the ClickHouse engine.\n   - Exception: pg_cron logs live under `source = 'postgres_logs'`.\n\n2. **Remove every unnest join.** Delete `cross join unnest(metadata) as m`,\n   `cross join unnest(m.parsed) as p`, `left join unnest(...) on true`, and so on.\n   They have no equivalent — the data is already flat in the map.\n\n3. **Rewrite every unnest-alias column as a map lookup.** A field taken off\n   `unnest(metadata)` becomes `log_attributes['field']`. A field off a nested\n   struct like `unnest(m.parsed)` becomes `log_attributes['parsed.field']`: keep\n   the struct name as a dotted prefix, drop the `metadata` root and every alias.\n\n4. **Wrap numeric fields in `toInt32OrZero(...)`** before comparing or aggregating\n   them — map values are strings.\n\n5. **Swap BigQuery functions for ClickHouse ones** (see the table below).\n\nPreserve the original select list, filters, group by, order by, and limit intent\nthroughout.\n\n## Function substitutions\n\n| Need             | BigQuery                      | ClickHouse                  |\n| ---------------- | ----------------------------- | --------------------------- |\n| Count rows       | `count(*)`                    | `count()`                   |\n| Regex match      | `regexp_contains(x, 'p')`     | `match(x, 'p')`             |\n| Substring match  | `x like '%p%'`                | `x ilike '%p%'` or `like`   |\n| Numeric coercion | `cast(x as int64)`            | `toInt32OrZero(x)`          |\n| Timestamp value  | `cast(timestamp as datetime)` | `timestamp`                 |\n| All columns      | `select *`                    | list the columns explicitly |\n\n## Full before/after\n\nBigQuery:\n\n```sql\nselect count(t.timestamp) as count, p.error_severity\nfrom\n  postgres_logs as t\n  cross join unnest(metadata) as m\n  cross join unnest(m.parsed) as p\nwhere p.error_severity in ('ERROR', 'FATAL', 'PANIC')\ngroup by p.error_severity\norder by count desc\nlimit 100;\n```\n\nClickHouse:\n\n```sql\nselect count() as count, log_attributes['parsed.error_severity'] as error_severity\nfrom logs\nwhere source = 'postgres_logs'\n  and log_attributes['parsed.error_severity'] in ('ERROR', 'FATAL', 'PANIC')\ngroup by log_attributes['parsed.error_severity']\norder by count desc\nlimit 100\n```\n\nNotice: `count(t.timestamp)` became `count()`, the two unnest joins are gone,\n`p.error_severity` became `log_attributes['parsed.error_severity']`, and the\n`from`/`where` targets the single table.\n\n## Getting the keys right\n\nThe most common conversion mistake is dropping a dotted prefix — writing\n`log_attributes['x_real_ip']` when the real key is\n`log_attributes['request.headers.x_real_ip']`, or `log_attributes['cf.country']`\ninstead of `log_attributes['request.cf.country']`. Do not invent or shorten keys.\nWhen unsure, discover the real keys from data:\n\n```sql\nselect arrayJoin(mapKeys(log_attributes)) as key, count() as n\nfrom logs\nwhere source = 'edge_logs'\ngroup by key\norder by n desc\nlimit 200;\n```\n\nThen map each old nested path to the matching key exactly as it appears.\n", "skills/clickhouse-logs-queries/references/codebase-integration.md": "# Wiring a logs query in the Studio codebase\n\nThis covers writing analytics log SQL inside `apps/studio` so it is safe, routed\nto the right endpoint, and consistent with the existing OTEL builders. Read this\nwhen you are editing TypeScript that builds or runs a logs query, not when you are\njust writing a query in the Logs Explorer UI.\n\n## Branded SQL: never concatenate user input\n\nAll analytics log SQL must be a `SafeLogSqlFragment`, built with the helpers in\n`apps/studio/data/logs/safe-analytics-sql.ts`. Two things enforce this: the\n`sql` parameter of `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`)\nis typed `SafeLogSqlFragment`, and an eslint `no-restricted-syntax` rule in\n`apps/studio/eslint.config.cjs` blocks direct `post()`/`get()` calls to the\n`logs.all` / `logs.all.otel` endpoints from any file other than\n`execute-analytics-sql.ts`. The branding is what keeps interpolated values from\nbecoming injection. The key\nexports:\n\n- `safeSql\\`...\\``— a tagged template that only accepts`SafeLogSqlFragment`interpolations. Plain strings (and Postgres-branded`SafeSqlFragment`) are\n  rejected at compile time, so you cannot accidentally drop a raw value in.\n- `analyticsLiteral(value)` — turns a string/number/boolean into a safely escaped\n  literal fragment (single quotes and backslashes are escaped). Use it for every\n  dynamic value, especially the `source`.\n- `joinSqlFragments(fragments, separator)` — joins already-safe fragments with a\n  fixed structural separator (`' and '`, `', '`, etc.).\n- `keyword(value, allowed)` — resolves a value against a compile-time allow-list of\n  fragments (e.g. an `AND`/`OR` operator). Returns the allow-listed fragment, never\n  the raw input.\n- `quotedIdent(value)` — backtick-quotes a dotted identifier path after validating\n  each segment.\n\nCompose with `safeSql` plus these helpers. The only way to run SQL that was not\nbuilt from them is the user-authored path: `untrustedLogSql(text)` marks editor\ntext as `UntrustedLogSqlFragment` (displayable, storable, never executable), and\n`acceptUntrustedLogsSql(fragment)` promotes it to `SafeLogSqlFragment`. That\npromotion is a security boundary — call it only from a run gesture (Run\nbutton click, Cmd+Enter) or an approval-gated tool call (the AI notebook\ntools). Never from render, `useEffect`, or any automatic path. The notebook\npersist path also promotes cells because the writable notebook type requires\n`SafeLogSqlFragment`; that is storage typing, not execution approval, and is\nnot precedent for promoting anywhere else.\n\n```ts\nimport { analyticsLiteral, safeSql } from '@/data/logs/safe-analytics-sql'\n\nconst source = 'edge_logs'\nconst sql = safeSql`\n  select timestamp, event_message\n  from logs\n  where source = ${analyticsLiteral(source)}\n  order by timestamp desc\n  limit 100\n`\n```\n\n## Pick the endpoint and builder by flag\n\nThe ClickHouse path is gated by the `otelLegacyLogs` ConfigCat flag\n(`useFlag('otelLegacyLogs')` from `common` — ConfigCat, not PostHog). Keep the BigQuery path working when\nthe flag is off. Two helpers in `apps/studio/data/logs/logs-endpoint.ts` express\nthe split:\n\n- `logsAllEndpointUrl(useOtel)` — returns the `logs.all.otel` endpoint when\n  `useOtel`, otherwise the legacy `logs.all` endpoint.\n- `pickLogsQueryBuilder(useOtel, otel, bq)` — picks between an OTEL builder and a\n  BigQuery builder while preserving the type.\n\n```ts\nconst useOtel = useFlag('otelLegacyLogs')\nconst builder = pickLogsQueryBuilder(useOtel, genDefaultQueryOtel, genDefaultQuery)\nconst endpoint = logsAllEndpointUrl(useOtel)\n// include { otel: useOtel } in the React Query key so the two paths cache separately\n```\n\nRun the fragment through `executeAnalyticsSql` (`apps/studio/data/logs/execute-analytics-sql.ts`)\nagainst that endpoint:\n\n```ts\nimport { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'\nimport { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'\n\n// ✅ GOOD: every interpolation is sanitized.\nconst sql = safeSql`\n  SELECT timestamp, event_message\n  FROM ${quotedIdent(table)}\n  WHERE id = ${analyticsLiteral(id)}\n`\n\nawait executeAnalyticsSql({\n  projectRef,\n  endpoint,\n  sql,\n  iso_timestamp_start,\n  iso_timestamp_end,\n})\n```\n\n```ts\n// 🛑 BAD: raw string interpolation. This fails to type-check at the\n// executeAnalyticsSql boundary because the result is `string`, not\n// `SafeLogSqlFragment`.\nconst sql = `SELECT * FROM ${table} WHERE id = '${id}'`\nawait executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })\n```\n\n## Follow the existing OTEL builders\n\nWhen you need a new query shape, mirror the generators in\n`apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.ts` rather than\ninventing a parallel style. They already encode the conventions:\n\n- `genDefaultQueryOtel`, `genCountQueryOtel`, `genChartQueryOtel`,\n  `genSingleLogQueryOtel` — the row/count/chart/single-log builders. They select\n  the real columns plus source-specific `log_attributes[...]` lookups aliased to\n  the leaf names the renderers expect.\n- `mapOtelPreviewRow`, `mapOtelSingleLogToLegacy`, `otelTimestampToMicros` — the\n  JS normalization layer. `timestamp` must end up a microsecond number for the\n  pagination cursor and the renderers, so reuse `otelTimestampToMicros` rather\n  than parsing the ISO string yourself.\n\nThe map-key discovery hook (`apps/studio/data/logs/otel-log-keys-query.ts`,\n`fetchOtelLogKeys` / `useOtelLogKeysQuery`) is the canonical example of a small,\ncorrectly-branded OTEL query — read it before writing a new one.\n\n## Checklist\n\n- [ ] Every dynamic value goes through `analyticsLiteral` (or another sanitizer),\n      never string concatenation.\n- [ ] The query filters by `source` and includes a `LIMIT`.\n- [ ] Numeric `log_attributes` values are wrapped in `toInt32OrZero`.\n- [ ] The endpoint and builder are chosen with `logsAllEndpointUrl` /\n      `pickLogsQueryBuilder` off `useFlag('otelLegacyLogs')`.\n- [ ] The React Query key distinguishes the OTEL and BigQuery paths.\n- [ ] `timestamp` is normalized to micros for any row consumed by the table/cursor.\n- [ ] There is a unit test asserting the generated SQL string (see\n      `Logs.utils.otel.test.ts` and `safe-analytics-sql.test.ts` for the pattern).\n", "skills/code-review/SKILL.md": "---\nname: code-review\ndescription: Review repository changes for correctness, type boundaries, structural quality, and meaningful test coverage. Use for read-only code or PR assessments and development-task readiness checks.\n---\n\n# Code Review\n\n## Select the mode and target\n\n**Read-only assessment:** use for explicit reviews and audits. Resolve the requested PR, branch, commit, or file scope; otherwise inspect current changes against the actual base branch. If neither changes nor a clear target exist, ask for the target. Do not edit, format, mutate source for testing, push, open a PR, or publish review comments. Run only checks compatible with the requested scope.\n\n**Readiness:** use when verifying implementation. Follow applicable instructions and the user's requested scope. Delegate fixes, formatting, and temporary source mutations to the implementation worker when available. Review every later fix and repeat affected checks before claiming readiness.\n\nRead the applicable [AGENTS.md](../../../AGENTS.md) instructions and domain skills. Inspect the complete diff, stated intent, surrounding code, relevant callers, tests, and available check results. A summary or author report is not a substitute for reading the change.\n\n## Correctness and boundaries\n\nTrace changed inputs through their observable effects. Check async sequencing and rejection paths, nullable values, indexing and pagination, state updates, removed guards, permissions, and callers affected by changed exports or contracts. Identify concrete failing scenarios rather than speculative defensive requirements that contradict established API guarantees.\n\nAt external boundaries such as HTTP, parsed JSON, route parameters, storage, and callbacks, verify how values become trusted domain data. Keep useful inferred types and validate untrusted inputs where the contract requires it. Flag broad types propagated inward, assertion chains, non-null assertions, or unsafe casts when they hide an unproven invariant. `unknown` and runtime narrowing are appropriate at genuine boundaries; do not ban them mechanically or add a schema library without need.\n\nAudit every added or changed type assertion in the diff. At JSON/API/storage boundaries, validate with a focused schema and preserve its inferred type; do not accept moving a cast into a helper as a fix.\n\nExplain any surviving type assertion's invariant in the review evidence. Do not weaken types, suppress errors, or route values through `any` to make checks pass. Static typechecking and passing runtime tests provide different evidence.\n\n## Structure and readability\n\nPrefer the smallest change that clarifies the behavior. Check whether a refactor reduces states and branches or merely moves complexity behind wrappers. Keep feature logic with its owning module and reuse canonical utilities.\n\nFlag scattered special cases, duplicate domain contracts, pass-through abstractions, and generic mechanisms that obscure simple data flow. Extract helpers or name complex conditions when doing so reduces the reader's reasoning burden. Similar-looking code alone does not justify an abstraction; prioritize high-impact structural problems over cosmetic nits.\n\nKeep transformations and business rules independently understandable without extracting every expression from a component. Follow domain-specific composition conventions where they apply.\n\nPrefer self-explanatory names and structure. Avoid comments that restate the code or narrate change history; history belongs in commits and PRs. Preserve domain-required annotations and semantic tooling directives.\n\n## Meaningful coverage\n\nFor Studio, follow [studio-testing](../studio-testing/SKILL.md) for test selection and location, [studio-mock-api-tests](../studio-mock-api-tests/SKILL.md) for network-backed component tests, and [studio-e2e-tests](../studio-e2e-tests/SKILL.md) for E2E execution. Use [vitest](../vitest/SKILL.md) for runner details. For docs, follow [review-the-docs](../review-the-docs/SKILL.md) and use [test-the-docs](../test-the-docs/SKILL.md) when runnable snippets need verification.\n\nEach new test should protect a meaningful behavior or plausible regression. Prefer observable outcomes and representative failures over private state, DOM structure, class names, or whole-tree snapshots. Reuse real definitions and existing fixtures when suitable, while keeping expected outcomes independent of the implementation's calculation.\n\nInspect changed tests and nearby coverage for duplicates, assertions that cannot fail, unawaited async checks, and mocks that replace the integration being verified. Preserve distinct boundary, error, historical-data, and safety cases. Rewrite brittle coverage around the meaningful contract before removing its only assertion. Do not add tests solely for static configuration, type guarantees, framework internals, or coverage percentages.\n\n## Verification evidence\n\nChoose formatting, lint, typecheck, build, and test commands from the affected package's actual scripts and CI configuration. Check changed files with the repository's Prettier configuration. Do not assume an unscoped root `tsc` validates every package. Record commands, scope, and outcomes; distinguish checks run personally from CI results and author claims.\n\nIn readiness mode for executable behavior:\n\n1. Run relevant existing tests with retries disabled. Diagnose failures as behavioral, dependency, environment, or infrastructure issues; blocked runs are not passes.\n2. Repeat affected tests and shuffle with recorded seeds where timing, shared state, order dependence, or observed instability makes flakiness a concern. Fix the cause instead of masking failures with retries or skips.\n3. For new or changed behavioral tests and regression-critical coverage, prove the important assertion detects broken behavior. Prefer reproducing the original bug before the fix when available. Otherwise use a focused, realistic temporary mutation of the affected behavior, such as omitting a required side effect. A compile error, timeout, or infrastructure failure does not demonstrate a behavioral assertion.\n4. Before mutating, save exact source bytes and guarantee restoration even on failure, preserving unrelated edits. Coordinate ownership to prevent concurrent writes. Restore source, confirm the intended diff remains, and rerun the affected clean tests. Repair meaningful coverage that survives the probe, then repeat it.\n\nThis is a focused check of important behavioral coverage, not a repository-wide mutation campaign. For docs or configuration without executable behavior, explain why execution or mutation is inapplicable; do not invent tests to satisfy a gate. In read-only mode, inspect available evidence and report gaps without source mutations.\n\nVerify required CI against the latest head when CI is part of the requested deliverable. Missing, pending, cancelled, failed, skipped, and neutral results are not passes; establish and disclose genuine path-based inapplicability. Never claim an unavailable required check passed.\n\n## Report\n\nLead with actionable findings ordered by impact. Each finding needs a file and line, a concrete trigger or scenario, its consequence, and supporting evidence. Separate demonstrated defects from uncertainty and blocked verification. Say when no actionable findings remain; avoid restating the diff.\n\nFor an audit or requested score, give correctness confidence out of 100 grounded in inspected evidence and its limits. Explain which improvements would raise confidence. A score never authorizes merging or substitutes for required checks.\n\nFor readiness, summarize what was fixed, remaining findings and decisions, commands and outcomes, behavioral proof where applicable, and blockers. Claim readiness only when the applicable review and checks cover the current changes. Report limitations honestly when independent review or execution was unavailable. Do not post findings externally unless requested.\n", "skills/copywriting/SKILL.md": "---\nname: copywriting\ndescription: Write or audit UI copy (buttons, labels, empty states, error messages, tooltips, form text) anywhere in the monorepo. Load it before shipping or reviewing any user-facing text — including when copy is incidental to the task, like a new feature that adds buttons, toasts, dialogs, or validation messages.\n---\n\n# Copywriting\n\nSource of truth: `apps/design-system/content/docs/copywriting.mdx`. Read it before writing or auditing any UI copy — it covers voice and tone, buttons, error messages, empty states, and confirmation dialogs with good/bad examples.\n", "skills/dev-toolbar-review/SKILL.md": "---\nname: dev-toolbar-review\ndescription: Safety rules for the dev toolbar, PostHog client, and feature flags. Use\n  when writing or reviewing any change to packages/dev-tools/, packages/common/posthog-client.ts,\n  or packages/common/feature-flags.tsx. Covers environment guards, flag override cookies,\n  telemetry event subscription, and SSE stream safety.\n---\n\n# Dev Toolbar Review Guide\n\nReview checklist for PRs touching the dev toolbar (`packages/dev-tools/`) and its\nintegration points in `packages/common/`. The toolbar surfaces telemetry events and\nallows feature flag overrides in local and staging environments only.\n\n## When This Applies\n\nPRs modifying any of these paths need growth eng review:\n\n- `packages/dev-tools/**` (owned by `@supabase/growth-eng` in CODEOWNERS)\n- `packages/common/posthog-client.ts` (flag override reads, event subscription)\n- `packages/common/feature-flags.tsx` (flag override merge logic)\n- App-level mounting: `DevToolbarProvider`/`DevToolbar`/`DevToolbarTrigger` in `apps/studio/`, `apps/www/`, `apps/docs/`\n\nNote: `posthog-client.ts` and `feature-flags.tsx` are NOT in CODEOWNERS for growth-eng,\nso PRs touching only those files won't auto-request review. Watch for these in the PR feed.\n\n## Review Checklist\n\n### 1. Environment Guards\n\n**Files:** `packages/dev-tools/index.ts`, `DevToolbar.tsx`, `DevToolbarTrigger.tsx`, `DevToolbarContext.tsx`\n\nThe toolbar uses two layers of protection:\n\n- **Build-time tree-shaking** in `index.ts`: the bundler inlines `process.env.NEXT_PUBLIC_ENVIRONMENT`, so `isToolbarEnabled = env === 'local' || env === 'staging'` makes the export ternaries static. Outside those two environments every export is a stub (`DevToolbar` and `DevToolbarTrigger` render `null`, `DevToolbarProvider` passes children through, `useDevToolbar` returns a no-op context) and the implementation modules are eliminated from the bundle. The same literal `process.env` check is duplicated in `DevToolbarContext.tsx`, `DevToolbar.tsx`, `DevToolbarTrigger.tsx`, and `feature-flags.tsx` because the bundler must see it directly — keep them in sync.\n- **Runtime guards** inside the implementation: `IS_LOCAL_DEV = env === 'local'` gates the local-only pieces — the SSE event stream in `DevToolbarContext.tsx` and local-only UI in `DevToolbar.tsx` — so staging gets the toolbar without them.\n\n**Check for:**\n\n- Guards being removed or broadened. The toolbar is enabled only for `local` and `staging`; preview and production builds must keep getting the stubs.\n- Tree-shaking ternaries in `index.ts` staying intact — these are the primary production safety mechanism.\n- New components or exports that bypass the existing guard pattern.\n\n### 2. Flag Override Cookies\n\n**Files:** `packages/dev-tools/DevToolbar.tsx`, `packages/common/posthog-client.ts`, `packages/common/feature-flags.tsx`\n\nThe toolbar writes two cookies that override feature flags locally:\n\n- `x-ph-flag-overrides` — PostHog flag overrides\n- `x-cc-flag-overrides` — ConfigCat flag overrides\n\nThese are read by:\n\n- `posthog-client.ts:getFeatureFlag()` — checks the PostHog override cookie before querying the SDK\n- `feature-flags.tsx` — merges both override cookies into the flag store during initialization\n\n**Check for:**\n\n- Cookie name changes (must stay in sync across writer and all readers)\n- Changes to the merge/precedence logic in `feature-flags.tsx` (currently: `vercel-flag-overrides` first, then `x-cc-flag-overrides` takes precedence in local dev)\n- Override cookies being read outside the `IS_LOCAL_DEV` / `isLocalDev` guard — overrides must never affect production flag evaluation\n- Changes to `parseOverrideValue` or `valuesAreEqual` in `packages/dev-tools/utils.ts` that could cause type coercion bugs\n\n### 3. Telemetry Event Subscription\n\n**Files:** `packages/common/posthog-client.ts`, `packages/dev-tools/DevToolbarContext.tsx`\n\nThe toolbar subscribes to client-side PostHog events via `posthogClient.subscribeToEvents()`.\nThe PostHog client calls `emitToDevListeners()` after `capturePageView`, `capturePageLeave`,\nand `identify`. Note: `captureExperimentExposure` calls `posthog.capture()` directly\nwithout emitting to dev listeners — experiment exposure events are invisible in the toolbar.\n\n**Check for:**\n\n- Changes to `emitToDevListeners` or `subscribeToEvents` that could introduce side effects on the actual capture path (e.g., throwing errors, blocking, mutating event data)\n- The listener set (`devListeners`) being iterated synchronously in a way that could delay event dispatch\n- New PostHog client methods that capture events but don't call `emitToDevListeners` (gap in toolbar visibility)\n\n### 4. SSE Server Telemetry Stream\n\n**Files:** `packages/dev-tools/DevToolbarContext.tsx`\n\nThe toolbar connects to `${apiUrl}/telemetry/stream` via Server-Sent Events to display\nserver-side telemetry. Uses exponential backoff on connection errors.\n\n**Check for:**\n\n- Changes to the SSE endpoint URL or `session_id` cookie handling\n- Reconnection logic changes that could cause excessive retries or connection leaks\n- Note: the stream endpoint lives in the platform repo — cross-repo changes need coordinated review\n\n### 5. App-Level Mounting\n\n**Provider + toolbar panel** (`DevToolbarProvider`, `DevToolbar`):\n\n- `apps/studio/pages/_app.tsx`\n- `apps/www/pages/_app.tsx`, `apps/www/app/providers.tsx`\n- `apps/docs/features/app.providers.tsx`\n\n**Trigger button** (`DevToolbarTrigger`) — rendered separately in nav/header components:\n\n- `apps/studio/components/layouts/Navigation/LayoutHeader/LayoutHeader.tsx`\n- `apps/www/components/Nav/index.tsx`\n- `apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsx`\n\n**Check for:**\n\n- Provider being added or removed from an app\n- `apiUrl` prop changes (must point to the correct platform API)\n- Rendering order changes that could affect the toolbar's access to PostHog context\n\n## What Doesn't Need Growth Review\n\nChanges that are purely UI/UX within the toolbar panel itself — styling, layout, copy\nchanges, drag behavior, popover positioning — don't need growth eng review unless they\nalso touch the integration points above.\n", "skills/edit-the-docs/SKILL.md": "---\nname: edit-the-docs\ndescription: >-\n  Restructure, reorder, and improve existing Supabase docs pages under\n  apps/docs: clarity, connective text, section grouping, and brevity.\n  Use when asked to edit, reorganize, restructure, tighten prose, add glue\n  between sections, or split a page edit into stacked PRs. Not for net-new\n  feature drafts, which belong to write-the-docs, and not for PR triage or\n  verification, which belong to review-the-docs.\n---\n\n# Edit the docs\n\nImproves **existing** Supabase docs pages: structure, order, connective text, and clarity.\n\n**Not this skill:** [`write-the-docs`](../write-the-docs/SKILL.md) drafts net-new content or product-grounded rewrites from intent and code. [`review-the-docs`](../review-the-docs/SKILL.md) covers build and PR triage.\n\n**Output is one pull request, with one change type per commit.** A reviewer reads the style diff apart from the structure diff without holding several PRs in their head. Split into a stack of PRs only when the requester asks for one, or approves the split you offer because the diff turned out large. Phase 0 covers when to raise it, and [reference/stacked-prs.md](reference/stacked-prs.md) covers the mechanics.\n\n## Core rules\n\n1. **Read before you rewrite.** Open the target page and nearby pages of the same type. Name the reader's goal and the page type before moving sections.\n2. **Don't invent product truth. Verify it, in its own PR.** Style and structure work preserves behavior claims, UI labels, and positioning as written. Correcting a claim is PR 3 work, and adding one belongs to the additions branches above it. Those PRs follow [`write-the-docs`](../write-the-docs/SKILL.md) grounding rules: read the code, separate shipped behavior from product intent, and flag what you inferred.\n3. **Follow the [style guide](../../../apps/docs/style-guide/README.md)** for voice, terminology, structure, and components.\n4. **Prefer brevity.** Use broad strokes when mechanical detail doesn't help the reader's task. Cut redundancy. Don't over-explain.\n5. **Reuse sibling skills.** Get IA and architecture from [`ask-the-docs`](../ask-the-docs/SKILL.md). Get validation and self-review from [`review-the-docs`](../review-the-docs/SKILL.md). Apply the style guide's [timeless documentation](../../../apps/docs/style-guide/03-page-structure.md#write-timeless-documentation) rather than duplicating it here.\n6. **One change type per diff.** A diff that mixes reworded prose with moved sections is unreviewable, because the reader can't tell a move from a rewrite. Separate them by commit in a single PR, or by branch in a stack.\n\n## Phase 0: Size and split\n\n1. Identify the document type per [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md#document-types). The types are explainer, tutorial, guide, reference, and troubleshooting. Then pick its template per [Choose a template](../../../apps/docs/style-guide/03-page-structure.md#choose-a-template).\n2. State the reader's goal and prerequisites in one or two lines.\n3. Compare the page to its template and list every section that doesn't fit it: a second task, a second audience, background, or lookup content. **When a section is clearly a second task or audience, or the requester asked for template alignment, recommend a topic split-out and a content migration for it.** Name the page it should move to, an existing page or a new one under its own template, and say that the original anchor stays as a pointer. Otherwise note the misfit and carry on, so a small edit stays small. Don't squeeze misfit content into the template, and don't delete it. If no template fits the page at all, say so and ask.\n4. Note structural problems: mixed information types interrupting a procedure, missing intro navigation on a long page, weak transitions, redundancy, or over-explained mechanics.\n5. Sort the diagnosis into the buckets below. **Drop any bucket that comes back empty, and say so.** Style, structure, and technical revision take one commit or branch each. Additions take as many as the content needs, so the edit has no fixed size. A style edit plus a structural edit is the common shape, because most pages that need restructuring are already correct. Two buckets is a complete result, not a truncated one.\n6. Know where the edit ends. **The edit is only the buckets that have content.** Any bucket you drop is beyond the edit, and a later request for that change type is a new request. That includes one you raise yourself. Name it, keep the work in progress clean, and ask whether it belongs in this edit, in a separate ticket, or nowhere. Absorbing it into a bucket that's already open is what turns an edit into a rewrite.\n7. Size the edit. **When it comes out large, offer a stack. Don't choose one.** One PR with each bucket as its own commit is the output unless the requester approves a split. Raise the question when both hold:\n   - The edit rewrites prose and moves sections, or it corrects a technical claim.\n   - It runs over roughly 150 changed lines.\n\n   Say how large the diff is and propose the branches. Name the trade in the ask: a stack gives a reviewer clean per-change-type diffs, and it also means no PR page shows the whole edit, so reading it end to end costs them an extra command. Their reviewers pay that cost, so it's their call. **No answer means one PR.**\n\n8. Summarize the diagnosis and the proposed split to the requester, and **wait for confirmation before creating any branch.** Name which buckets are empty and why. When nobody is available to confirm, record the diagnosis in the PR body and ship one PR.\n\n**When the diff outgrows the estimate mid-edit, stop and offer the split then.** A size call made at diagnosis can be wrong by the time the style pass lands. Say how large it got and ask. Splitting unasked is the failure here, and so is carrying on quietly because you already have an answer.\n\n**The sections below are named for the stacked case.** In a single PR they're commits, in the same order and under the same rules.\n\n## PR 1: Style\n\nInline changes only. Nothing in this PR moves a line from one place to another.\n\n**Rewrite:**\n\n- Use second person, present tense, short paragraphs, and ordered steps for sequential actions.\n- Put procedures in procedure format. Per-step formatting is in [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md#procedures); how many steps to present at once and when to split into phases is in [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md#chunking).\n- Apply [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md) for admonitions, emphasis, links, and lists, and [`01-voice-and-tone.md`](../../../apps/docs/style-guide/01-voice-and-tone.md) for person, tense, and sentence-level grammar.\n- Keep code samples executable in their stated context, and mark intentionally omitted code. Prefer partials under `apps/docs/content/_partials/` over copied blocks.\n- **Check the alt text on every image, and open the image to do it.** Alt text on an existing page usually names the topic rather than describing the picture, and a topic name is what the nearby heading already says. Describe what a reader who can't see it would need: the labeled parts, the relationships between them, and any values the diagram carries. This is a rewrite of existing text, so it belongs in this PR.\n\n**Cut:**\n\n- Restated points and mechanical over-explanation.\n- Time-anchored language and unshipped features: [timeless documentation](../../../apps/docs/style-guide/03-page-structure.md#write-timeless-documentation). Internal planning context in shipped MDX: [keep internal context out](../../../apps/docs/style-guide/03-page-structure.md#keep-internal-context-out). Repeated points: [brevity](../../../apps/docs/style-guide/01-voice-and-tone.md#brevity). Single-item lists and restated admonitions: [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md).\n- Terminology that doesn't match [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md). Run both passes from [Use with an AI agent](../../../apps/docs/style-guide/WORD_LIST.md#use-with-an-ai-agent): [Phrase groups](../../../apps/docs/style-guide/WORD_LIST.md#phrase-groups) gives you every literal term list in one read, then `grep '^### ' WORD_LIST.md` and open only the entries matching words on the page. Cover terms already on the page, not only the ones you introduce. An existing page is where nonconforming terminology accumulates.\n\n## PR 2: Structure\n\nApply [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md) — section grouping, navigation, and glue. This section is the procedure for doing that on an existing page; the rules live in the guide.\n\n**Work in this order, and settle the outline before you move a line.** A restructure invalidates every branch above it in the stack, so each revision costs a full restack, and a restack is where content gets dropped in conflict resolution. Reworking the shape twice costs far more than getting it right once.\n\n### 1. Lock the headings other code links to\n\nGrep the whole repo for `#<slug>` against every heading on the page, not just `apps/docs/content`. Studio renders Docs buttons that deep-link into guide anchors, and `apps/www` links into them too. Those are the matches that break a button in the product rather than a link between two pages.\n\nWrite the matched heading texts down. For the rest of this PR they are immutable. **Moving a section preserves its slug, and so does changing its level. Only renaming breaks it.** That is what makes an aggressive regroup safe.\n\n### 2. Classify every substantial section\n\nClassify each one against the information types in [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md#information-types), then collapse them into the three buckets you'll group by: **procedural** (Procedure), **contextual** (Concept and Process), and **reference** (Structure and Fact). A principle or a fact usually rides along in the section it qualifies rather than getting one of its own.\n\nThe guide has the two rules that decide the hard cases: classify by what the reader is doing rather than what the section is about, and split a section that serves two types instead of filing it under the larger half.\n\nWrite the bucket for every section down before moving anything. A page where every section lands in one bucket is a page that wasn't really classified.\n\n### 3. Write the target outline before touching the file\n\nProduce the whole heading tree, with levels, and check it against the locked list from step 1. Put it in front of the requester along with the Phase 0 diagnosis. The outline is the artifact that gets revised, not the page.\n\nOrder the groups per [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md#grouping-sections), which has the order that works and a worked outline. A short concept opener can precede the procedure group; keep that group uninterrupted, and put the remaining background after it.\n\nWhen a section held two types and you split it in step 2, the half that keeps the original heading text stays in its original group, so the locked anchor from step 1 survives. The new half takes a new heading and moves to the group its type belongs to.\n\n### 4. Move, then add the glue the new shape needs\n\nMove and regroup, and preserve meaning. Don't silently rewrite facts while restructuring. A pure set of moves is what makes this PR reviewable, so call out in the PR body any deletion that isn't a move.\n\nThen:\n\n- Add a short introduction linking each major group and saying when to use it. Skip it when a short page is already easy to scan.\n- Add a group introduction, a transition where the information type changes, and an outcome after a procedure. Don't link every adjacent section.\n- Put sections covering the same topic under a shared heading.\n\n### 5. When the page itself should split\n\nWhen a topic outgrows the page, or a section doesn't fit the page's template (Phase 0, step 3), give it its own page rather than its own group, and migrate the content there. Navigation that overflows the sidebar is one signal. A section carrying its own subsections several levels deep, sharing nothing with the rest of the page but a single word, is another.\n\nUpdate every navigation entry, repoint every inbound anchor, and cross-reference the new page. Confirm the nav-registration mechanism through [`ask-the-docs`](../ask-the-docs/SKILL.md) rather than assuming it.\n\n### 6. Before you submit\n\nRe-run the step 1 grep. Every locked heading text is still present, at whatever level it ended up.\n\n**A move that only reads correctly once new content exists isn't a PR 2 move.** It belongs to the branch that adds the content. Leave the section where it is, and say in the PR body which move you deferred and what it is waiting on. Otherwise PR 2 stops standing on its own, and a stack merged partway leaves the page reading worse than before.\n\nIf nothing needs to move, PR 2 doesn't exist. A page can be well organized and still need a style pass. Drop the branch and say the structure held up.\n\n## PR 3: Technical revision\n\nValidate the truth of the content and correct what's wrong.\n\n**Change a claim only when leaving it would produce a wrong outcome.** A reader following the page would hit an error, get a different result than the page promises, or decide on a fact that isn't true. That's the test.\n\n**Leave it alone otherwise.** Don't open PR 3 for imprecise but harmless phrasing, a claim you'd have worded differently, an accurate detail that isn't the newest way to do it, or a stale-looking value you can't verify against code. The last one is a note to the author, not an edit.\n\n**An external rule isn't a wrong outcome by itself.** A best-practices rule that a reader would never hit as a failure doesn't clear the gate, however high the rule's stated impact. Weigh what the reader experiences against the page, not how the rule is ranked.\n\n**PR 3 corrects what's on the page. A missing safeguard is an absence, and absences are additions.** When the fix is to add something the page never had, it belongs above this branch, not in it. This is the line that keeps a verification pass from quietly becoming a rewrite.\n\nWhen a claim does fail the test, verify before you change it, per Phase 1 of [`write-the-docs`](../write-the-docs/SKILL.md):\n\n- Read the implementation. Prefer the diff of a linked `supabase/supabase` PR over a general codebase read.\n- Where code and product intent disagree, code wins for behavior claims. Flag the mismatch.\n- Flag anything you inferred in the PR description, not in the MDX.\n\n**Run the snippets when the page has them.** Offer [`test-the-docs`](../test-the-docs/SKILL.md) before you start, and don't run it unasked. A snippet that fails in the sandbox is the most direct evidence a claim fails the wrong-outcome test, because the reader hits the same error. Attach the verification report to the PR body. If the author declines, record the artifacts as deferred and carry on with the code read. If the sandbox fails for an environmental reason, that's a deferral rather than a result — retry it before the branch merges.\n\n**Run every fence in document order, not only one path.** The reader pastes top to bottom, so that order is the claim. Snippets that each work alone can still fail as a sequence, by re-creating an object an earlier one made or by depending on one no fence ever creates. Nothing in a code read surfaces that, and it's the failure a reader hits first.\n\nTesting covers procedural content only. Claims that nothing executes, such as limits, defaults, and positioning, still need the code read above.\n\n**A branch above can change the answer.** The test is applied to the page as it stands, so a claim that passes inspection here can become wrong once an additions branch contradicts it. That correction belongs to the branch that creates the conflict, not back down here. Say so when you leave the claim, so the later change reads as intended rather than as a missed finding.\n\n**If every finding fails the test, PR 3 is empty.** Say what you checked and what you're deliberately leaving, then drop the branch. An empty PR 3 means verified and fine, not skipped. A technical concern raised later in the stack is then a new request, per the boundary rule in Phase 0.\n\n## PR 4+: Additions, on request only\n\n**Additions sit on top of the stack, so they stay out of the edit.** New content is a different job from editing what's already there. Keeping it on its own branches is what stops an edit from turning into a rewrite halfway through.\n\n**Additions take as many branches as the content needs.** Split them by diff size so each branch stays reviewable, and name each branch for what it adds rather than for its position in the stack. One branch is right when the additions are one topic and a small diff.\n\n**Don't scope these branches from the diagnosis.** Additions are empty by default. Don't propose them because the page looks thin.\n\n**A tracked request is the request.** An assigned ticket or issue that asks for new content has already made the ask, so treat it as scoped and get on with it. The rule forbids inventing additions yourself. It doesn't ask you to wait for someone to repeat a request that's already written down.\n\n**Route mid-edit requests up here instead.** When the author asks for new content while you're on an earlier branch, or when you spot a gap yourself, say it's additions material and keep the current branch clean. Then ask whether they want it in this stack, in a separate ticket, or not at all. Naming it is how you keep the conversation from reopening PR 1.\n\nOnce it's scoped:\n\n- Crawl reader feedback for candidate gaps. Linear is an internal Supabase tool, preferred when available and not required for open-source contributors.\n- Before you add content, check the [content-type gate](../write-the-docs/reference/content-type-gate.md#what-goes-in-docs-and-what-goes-in-kb). Put situation-specific content and fixes for specific problems in `/kb`, and link to them from the page.\n- Ground additions the same way as PR 3. Read the code before making a behavior claim, and flag what you inferred.\n- **Run every new runnable snippet through [`test-the-docs`](../test-the-docs/SKILL.md) before it ships.** New content is where an untested snippet is likeliest to be wrong, because nothing has ever executed it.\n- Strip internal business context before the draft ships: PRD intent, roadmap speculation, and ticket discussion. It belongs in the PR description, not in the MDX.\n\n## Validate each PR\n\nRun this per change type, before you submit the commit or branch that carries it, not once at the end:\n\n- [ ] The diff contains only this change type\n- [ ] Section groups follow information type, and procedures aren't interrupted by long context\n- [ ] Intro navigation is present only when the page needs it, and links resolve\n- [ ] Connective text is selective, not link spam\n- [ ] Voice matches [`01-voice-and-tone.md`](../../../apps/docs/style-guide/01-voice-and-tone.md) and terminology matches [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md)\n- [ ] Every image has alt text that describes the image, checked against the image itself\n- [ ] No invented behavior or positioning\n- [ ] Shared pitfalls checklist considered\n\n**Anchors.** PR 2 step 1 builds the locked-heading list and step 6 re-checks it. Any branch that renames or rewords a heading clears the same gate.\n\n**Frontmatter `title`.** It follows the same sentence-case rule as a heading. Renaming it moves a navigation label and a search entry, not just a line of prose, so it clears this same gate and lands in PR 2 rather than PR 1.\n\n**Format and build.** Follow [`write-the-docs/reference/drafting-mechanics.md`](../write-the-docs/reference/drafting-mechanics.md). Then run the [`review-the-docs`](../review-the-docs/SKILL.md) local self-review, plus `pnpm build:guides-markdown` when a guide, explainer, or tutorial changed.\n\n`build:guides-markdown` writes `apps/docs/public/markdown/manifest.json`, which the repo tracks and commits as `[]`. Discard that file before committing. It's a build artifact, not part of the edit.\n\n## Additional resources\n\n**Stacking:**\n\n- Mechanics and `gh stack` commands: [reference/stacked-prs.md](reference/stacked-prs.md)\n- Bottom-up stack review: [`review-the-docs`](../review-the-docs/SKILL.md)\n\n**Style and structure:**\n\n- Style guide entry point: [`style-guide/README.md`](../../../apps/docs/style-guide/README.md)\n- Section grouping, navigation, glue, and chunking: [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md)\n- Procedure format and other components: [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md)\n- Terminology: [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md)\n\n**Sibling skills:**\n\n- Drafting mechanics: [`drafting-mechanics.md`](../write-the-docs/reference/drafting-mechanics.md)\n- Runnable verification: [`test-the-docs`](../test-the-docs/SKILL.md)\n- Architecture and IA: [`ask-the-docs`](../ask-the-docs/SKILL.md)\n- Net-new drafts: [`write-the-docs`](../write-the-docs/SKILL.md)\n", "skills/edit-the-docs/reference/stacked-prs.md": "# Stacked PRs for a page edit\n\nMechanics for shipping the [`edit-the-docs`](../SKILL.md) buckets as a stack. **A stack is the exception, and the requester approves it.** Phase 0 covers when to offer one. This file covers how to build and submit it once they agree.\n\n## Branch names\n\nOne branch per change type, bottom to top:\n\n| PR  | Branch                       |\n| --- | ---------------------------- |\n| 1   | `docs/<page>-style`          |\n| 2   | `docs/<page>-structure`      |\n| 3   | `docs/<page>-technical`      |\n| 4+  | `docs/<page>-<what-it-adds>` |\n\nThe first three names are fixed, because there's one of each. **Additions get one branch per topic, named for the content it adds:** `docs/tables-rls` and `docs/tables-datatypes`, not `docs/tables-additions-1` and `-2`. Use `docs/<page>-additions` when a single branch carries all of them.\n\n**Create only the branches whose buckets have content.** Two branches is the common shape once an edit clears the gate. `gh stack init` takes however many you pass it.\n\n**Use a category prefix and a short second segment.** Don't prefix a branch with an author name, even when a tracker suggests that format.\n\n**Get every name right before you submit.** Renaming a branch that already has an open PR closes the PR rather than retargeting it, and a closed PR whose head ref is gone can't be reopened. Recovering costs the PR number and its CI history.\n\n## Build the stack with gh stack\n\nNever chain `gh pr create --base <previous-branch>`. That produces correct base branches but no GitHub stack. There's no stack number and no stack UI, so reviewers see several unrelated-looking PRs instead of one series.\n\n1. `gh stack init <bottom> <middle> <top>` adopts existing branches, bottom to top. This is local only and makes no remote change.\n2. `gh stack view` confirms the structure and shows the mapped PR for each branch.\n3. `gh stack submit --auto` pushes and registers the stack on GitHub. Use `--auto` in a non-interactive session, where the editor can't open. New PRs are created as drafts unless you pass `--open`.\n\n**Check the titles after submitting.** `submit` can title a PR from its branch name rather than its commit subject. Fix any that came out wrong with `gh pr edit <pr> --title`.\n\n**Safe to re-run on PRs that already exist.** `submit` reports each one \"up to date\" and reuses it, so PR numbers, descriptions, and creation timestamps survive.\n\n**Draft state doesn't reliably survive.** `--open` marks existing PRs ready for review, not just new ones, and a resubmit has been observed taking drafts out of draft without it. Check the draft state of every PR after submitting, and set it back with `gh pr ready --undo` if it moved.\n\n**Other commands.** `gh stack link <pr> <pr> <pr>` registers the GitHub stack without local tracking. `gh stack unstack` removes a stack. The extension is `github/gh-stack`.\n\n## Reading the stack as a whole\n\nNo PR page shows the whole edit, so a reviewer who wants it in one view needs the command:\n\n```bash\ngit diff master...<top-branch> -- <path>\n```\n\n`gh stack view` lists the branches in order, so it gives you the top one. Put the command in the bottom PR's body. Without it the reviewer reconstructs the edit branch by branch, and that cost is why Phase 0 defaults to a single PR.\n\n## Restacking after a change low in the stack\n\n`gh stack rebase` replays every branch above the one you changed. Where a lower branch moved content that an upper branch also edited, git raises a conflict whose two sides are \"the new structure\" and \"the old content being re-added\". Resolving toward the new structure is usually right, and it silently drops the upper branch's edit along with the stale copy.\n\n**Assume that happened. Audit rather than read the diff.** Before pushing, grep each branch for a marker of every change it is supposed to carry:\n\n```bash\ngit show <branch>:<path> | grep -c '<marker>'\n```\n\nOne marker per change, checked against the count you expect. A restructure large enough to conflict is large enough that reading the diff will not catch a missing paragraph.\n\nRestore anything missing as a new commit on the branch that owns it, then rebase again. Don't fold it into a neighboring branch to avoid a second rebase; that breaks the one-change-type-per-PR rule the stack exists for.\n\n## Merge order\n\nMerge bottom-up: `master`, then PR 1, then PR 2, then PR 3, then each additions branch in stack order. This is the model [`review-the-docs`](../../review-the-docs/SKILL.md) uses to review a stack, so the authoring and review sides share one vocabulary.\n\n## PR bodies\n\nEach body states which change type the PR carries and what it leaves to the PRs above it. That tells a reviewer the diff is narrow on purpose. Reworded prose isn't missing from the structure PR, it already landed below.\n\nCarry forward anything you flagged while working: inferred claims from PR 3, gaps you named but didn't fill, and stale values you couldn't verify. Those belong in the description, not in the MDX.\n\nFor general PR-body mechanics, see [`create-pull-request`](https://github.com/supabase/docs-agent-skills/blob/main/.claude/skills/create-pull-request/SKILL.md).\n", "skills/pm-the-docs/SKILL.md": "---\nname: pm-the-docs\ndescription: >-\n  Docs-PM decision support for the \"Write the docs\" authoring process —\n  makes audience, stage, and cross-cutting scope calls during the Frame\n  and Shape stages (including cross-repo product lookup via universe when\n  accessible, else the public OSS path), and helps decide when a docs\n  question needs to self-serve vs. escalate to a docs PM. Use when framing\n  a new docs page or launch, deciding what product stage or audience a\n  feature targets, judging whether a docs question needs PM sign-off, or\n  confirming which product repos a launch spans.\n---\n\n# PM the docs\n\nBacks the Frame and Shape stages of the \"Write the docs\" checklist (mirrored in [reference/write-the-docs-checklist.md](reference/write-the-docs-checklist.md)) — the audience, product-stage, and cross-cutting scope calls a docs PM would normally make before drafting starts.\n\n## When to invoke\n\n- Starting a new docs page or launch and need to state the product stage, audience, and \"why\" before drafting (Frame).\n- Deciding content type, IA placement, or prerequisites for a page (Shape).\n- Judging whether a launch spans multiple product repos (CLI, Auth, migrations, platform, …) — see [reference/universe-lookup.md](reference/universe-lookup.md).\n- Unsure whether a docs question is self-serve or needs a docs PM's sign-off.\n- Deciding whether a docs change should ship behind a feature flag or A/B test.\n\n**Not for** drafting content itself (see [`write-the-docs`](../write-the-docs/SKILL.md)), restructuring existing pages (see [`edit-the-docs`](../edit-the-docs/SKILL.md)), running snippets (see [`test-the-docs`](../test-the-docs/SKILL.md)), or docs-app architecture/IA placement mechanics (see [`ask-the-docs`](../ask-the-docs/SKILL.md)).\n\n## Reference files\n\n| File                                                                           | What's inside                                                              |\n| ------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |\n| [reference/write-the-docs-checklist.md](reference/write-the-docs-checklist.md) | Six-stage authoring checklist mirror                                       |\n| [reference/universe-lookup.md](reference/universe-lookup.md)                   | Cross-repo product lookup: capability gate, universe accelerator, OSS path |\n\n## Answering a scope/stage/audience question\n\n1. Read the relevant stage in [reference/write-the-docs-checklist.md](reference/write-the-docs-checklist.md) — its checkboxes state exactly what needs deciding.\n2. Read whatever context exists for the feature: the linked issue/project, the PRD, the shipped code or PR. When code and PRD disagree, the code wins for behavior claims.\n3. When scope may span services (CLI, Auth, migrations, Dashboard, platform, …), follow [reference/universe-lookup.md](reference/universe-lookup.md) **capability gate** before settling Frame/Shape; use universe only if accessible, otherwise the OSS path. Record which repos you searched.\n4. Answer the checklist's questions directly: product stage, audience and job-to-be-done, the one-line \"why,\" content type, IA placement, prerequisites.\n5. Distinguish **confirmed fact** (stated in the ticket/PRD/code) from **inference** (your best read) — flag inference explicitly rather than presenting it as settled.\n6. If a decision is genuinely open at the org level (not a docs authoring call), say so and name who should decide instead of inventing an answer to look complete.\n\n## Self-serve vs. escalate\n\nSelf-serve when the checklist is clear, standards exist, and you already know the stage and audience.\n\nEscalate to your docs team's PM when scope or stage is unclear, you need a review path, the bar is ambiguous, or the launch touches cross-cutting surfaces (quickstarts, API keys, tutorials, onboarding, platform concepts) — see the full \"Ask the Docs PM\" section in the checklist mirror.\n\nA static `enabled-features` flag (show or hide content at build time) needs no PostHog flag and no A/B test. Add it in your PR by following the [enabled-features README](../../../packages/common/enabled-features/README.md). The flag file is shared with Studio and www, so keep changes to docs keys.\n\nExperiment requests (a PostHog flag with A/B testing) depend on Supabase access. Run the [capability gate](reference/universe-lookup.md#capability-gate) first. Use the same `gh api repos/supabase/universe` probe.\n\n- **Supabase org access:** Send the request to Docs Engineering through a DOCS issue in Linear. Docs Engineering creates and wires the PostHog flag, and you work with them to start A/B user testing. Read [Feature flag a docs change](https://app.notion.com/p/4105004b775f81bf810ddd5682284d23) (internal, staff only) for the process.\n- **No access (OSS):** Do not tell the user to file a Linear issue or open the Notion page. Suggest the experiment in the PR description or a GitHub issue, and say why the change may need an A/B test. A Supabase team member decides and files the request. To preview a variant of a live experiment locally, add `?<flag>=<variant>` to the URL. Record `feature flags: staff-only (OSS)` in the Frame/Shape summary. This is a valid outcome, not a blocker.\n\nFor the code view, see [`ask-the-docs` `reference/feature-flags.md`](../ask-the-docs/reference/feature-flags.md).\n\n## Related skills\n\n- [`ask-the-docs`](../ask-the-docs/SKILL.md) — docs-app architecture and IA placement mechanics, such as nav registration. Cross-repo **product** lookup lives here in `universe-lookup.md`, not in `ask-the-docs`.\n- [`write-the-docs`](../write-the-docs/SKILL.md) — drafting once Frame/Shape are settled\n- [`test-the-docs`](../test-the-docs/SKILL.md) — run snippets against a Docker-isolated local stack; verification report\n- [`edit-the-docs`](../edit-the-docs/SKILL.md) — restructure and improve existing pages\n- [`review-the-docs`](../review-the-docs/SKILL.md) — self-review and PR review stages\n", "skills/pm-the-docs/reference/universe-lookup.md": "# Cross-repo product lookup\n\nCross-repo product search for Frame/Shape when a feature may span services. Use during `/pm-the-docs`, not `/ask-the-docs` (`ask-the-docs` stays on `apps/docs` architecture).\n\n**Cross-repo confirmation is required for everyone.** [`supabase/universe`](https://github.com/supabase/universe) is an optional accelerator when you have Supabase org access to that private meta-repo (and ideally a local clone). Contributors without that access use the OSS path below — that is a successful outcome, not a failure.\n\n## Capability gate\n\nRun this gate before any universe clone or submodule command.\n\n```mermaid\nflowchart TD\n  start[Cross-repo grounding needed]\n  clone{\"Local universe root exists?\"}\n  ghApi{\"gh api repos/supabase/universe succeeds?\"}\n  useUniverse[Use universe clone + rg in repos/]\n  ossPath[OSS path: public gh search + linked product repos]\n  start --> clone\n  clone -->|yes| useUniverse\n  clone -->|no| ghApi\n  ghApi -->|yes Supabase org access| useUniverse\n  ghApi -->|no 404/403| ossPath\n```\n\n### 1. Local clone?\n\nResolve the universe root in order (do not hardcode machine-specific absolute paths in committed files):\n\n1. `$SUPABASE_UNIVERSE_ROOT` (if set)\n2. `$HOME/GitHub/supabase/universe`\n\n```bash\nUNIVERSE_ROOT=\"${SUPABASE_UNIVERSE_ROOT:-$HOME/GitHub/supabase/universe}\"\n[[ -d \"$UNIVERSE_ROOT/.git\" || -f \"$UNIVERSE_ROOT/.git\" ]] && echo \"local universe ok\"\n```\n\nIf that checkout exists → **accelerator path** (skip the `gh api` probe).\n\n### 2. Else probe org access (read-only, no clone)\n\n```bash\ngh api repos/supabase/universe -q .full_name\n```\n\n| Result | Next step |\n| ------ | --------- |\n| Success (`supabase/universe`) | Accelerator path: you **may** clone with `--recurse-submodules` (or ask the user to), then search |\n| 404, 403, or other failure | **OSS path only** — do **not** run `git clone` or `git submodule update` against universe |\n\n## OSS path (always valid)\n\nWhen the gate says universe is unavailable:\n\n- Search public code: `gh search code --owner supabase '<query>'` (plus other public owners named in the ticket)\n- Read any product repo already checked out or linked from Linear / the PR\n- Prefer `supabase/supabase` in-tree sources when that is enough\n- In the Frame/Shape summary, record `universe: unavailable (OSS)` and list the public sources used\n\nNever treat missing universe access as a blocker or an incomplete Frame/Shape.\n\n## Accelerator: universe (when accessible)\n\nPrefer an existing local clone. Only init or update submodules after the gate succeeds:\n\n```bash\ncd \"$UNIVERSE_ROOT\"\ngit submodule update --init --recursive\n```\n\nPrivate submodules (`platform`, `branching`) may need a PAT. If those fail, note the gap and continue with public submodules plus the OSS search path.\n\n### Where to look\n\nStart from the universe README \"Finding your way around\" table, then `rg` inside the relevant submodule:\n\n| Looking for… | Start in |\n| ------------ | -------- |\n| Schema, extensions, RLS | `repos/postgres/`, `repos/postgrest/`, `repos/pg-toolbelt/` |\n| Auth flows | `repos/auth/`, `auth-js` under `repos/supabase-js/` |\n| Realtime / Storage / Edge Functions | `repos/realtime/`, `repos/storage/`, `repos/edge-runtime/` |\n| Dashboard / Studio | `repos/supabase/apps/studio` |\n| Management API / hosted infra | `repos/platform/` (private) |\n| CLI, local dev, `config.toml` | `repos/cli/` |\n| Docs & self-hosting Compose | `repos/supabase/` (`apps/docs`, `docker/`) |\n\nWhen scope is unknown, search initialized `repos/**` with a tight pattern rather than reading entire trees.\n\n## How to use in Frame / Shape\n\n1. Name the product surfaces the launch might touch (CLI, Auth, migrations, Dashboard, …).\n2. Run the **capability gate**.\n3. Resolve surfaces to repos (universe submodules **or** public search / linked checkouts).\n4. Confirm with a short search whether behavior lives in one repo or several.\n5. Record in the Frame/Shape summary: gate result (`universe: available` or `universe: unavailable (OSS)`), repos consulted, cross-cutting vs single-repo, and any gaps.\n\nAlways distinguish confirmed fact from inference.\n", "skills/pm-the-docs/reference/write-the-docs-checklist.md": "# Write the docs\n\nA practical six-stage checklist and quality standard for planning, drafting, and reviewing product documentation.\n\n**P** = Product  \n**E** = Engineering  \n**Docs** = Docs team\n\n## Authoring\n\nSix short stages. Keep it lightweight; the point is to make good docs the default, not to add ceremony.\n\n_Self-serve first ([agent skills](../../../../apps/docs/CONTRIBUTING.md#ai-agent-skills-for-docs-authoring)), ask your docs team's PM as needed._\n\n## What good looks like\n\n- The **why** is explicit: a reader learns what problem this solves and when to reach for it, not only the steps.\n- The content **type is deliberate** and consistent within the page.\n- **Audience and prerequisites** are stated up front.\n- **Examples are runnable and have been tested** (commands, code, expected result)\n- **Correct stage** like GA is stated; limitations are named honestly.\n- The page **lives in the right place** in the IA and links to and from related pages.\n- Terminology and formatting match the [style guide](../../../../apps/docs/style-guide/README.md).\n\n### 1. Frame\n\n_Skills:_ `/ask-the-docs` for how the docs surface works today; `/pm-the-docs` for audience, stage, and cross-cutting scope (cross-repo span via universe when accessible — see [universe-lookup.md](universe-lookup.md)).\n\n- [ ] P: State the product stage (private/public alpha, beta, GA)\n- [ ] P: Name the audience and the job they are trying to do\n- [ ] P: Write one line on _why_ the feature exists (the problem it solves), not only what it does\n\n### 2. Shape\n\n_Skills:_ `/pm-the-docs` for content type and placement decisions; `/ask-the-docs` for docs-app architecture and where content lives.\n\n- [ ] P: Pick the content type(s): tutorial (learning), how-to (a task), reference (lookup), explanation (the why). Do not mix types on one page (refer to [Diátaxis](https://diataxis.fr/))\n- [ ] P: Decide where the page lives in the existing IA and what links in and out (avoid orphan pages)\n- [ ] P: Decide if part of the content belongs in `/kb` instead of `/docs`: comparisons, migration guides, or anything where the answer depends on the user's stack. Product facts stay in `/docs`, and `/kb` links to them ([content-type gate](../../write-the-docs/reference/content-type-gate.md#what-goes-in-docs-and-what-goes-in-kb))\n- [ ] P: List prerequisites and assumed knowledge up front\n\n### 3. Draft\n\n_Skill:_ `/write-the-docs` to draft net-new content grounded in Linear and the code.\n\n- [ ] P: Lead with the why and the outcome, then the how/what (product story first)\n- [ ] P: Include at least one runnable, copy-pasteable example that you have actually run (or will run in Self-review via `/test-the-docs`)\n- [ ] P/E: Cross-repo behavior confirmed via universe when accessible, else public `gh search` / named product repos when the feature is not confined to `supabase/supabase` (lookup via `/pm-the-docs`, not `/ask-the-docs`)\n- [ ] E: Contribute technical depth and verify accuracy (APIs, limits, edge cases)\n- [ ] P: Call out the current stage inline and any known limitations\n\n### 4. Self-review against the bar\n\n_Skills:_ `/review-the-docs` for [local self-review](../../review-the-docs/SKILL.md#local-self-review-no-open-pr) before opening the PR; `/test-the-docs` to run snippets and produce a verification report.\n\n- [ ] P/E: Check the draft against \"What good looks like\" above before opening the PR\n- [ ] P/E: `/test-the-docs` run; verification report ready for the PR body\n- [ ] P/E: Follow Authoring Experience standards and tooling when available\n\n### 5. PR review\n\n_Skill:_ `/review-the-docs` to triage, classify, verify the build, and report.\n\n- [ ] P/E: Open the PR and request review per the rules of engagement\n- [ ] Docs: Review against the published bar\n\n### 6. Keep it honest\n\n- [ ] P: Keep the product launch checklist's \"start on day 1\" docs gate honest through ship (update as stage or behavior changes)\n\n## Ask the Docs PM\n\n**Self-serve when:** the checklist above is clear, standards exist, and you know the product stage and audience.\n\n**Ask when:** scope or stage is unclear, you need a review path, the bar is ambiguous, or the launch docs touch cross-cutting surfaces (quick starts, API keys, tutorials, onboarding, platform concepts).\n\n**What to expect:** the docs PM is the point of contact for questions, skills enablement, and review against the bar.\n\n**Where to ping:** your team's PR-review channel and current docs PM — check your contributor guide for who that is today.\n\n## Resources\n\nSkills for this checklist: [AI agent skills for docs authoring](../../../../apps/docs/CONTRIBUTING.md#ai-agent-skills-for-docs-authoring) (`/pm-the-docs`, `/ask-the-docs`, `/write-the-docs`, `/test-the-docs`, `/review-the-docs`).\n", "skills/react-hook-form/SKILL.md": "---\nname: react-hook-form\ndescription: Correct React Hook Form usage anywhere in the monorepo — data flow, subscriptions,\n  reset, dirty state, number inputs, and controlled-input rules. Load this BEFORE\n  writing or modifying ANY form code, adding a field to an existing form, touching\n  watch/useWatch/formState/getValues/setValue/reset, wiring a form into a dialog or\n  sheet, or building a submit/cancel footer — even when the change looks trivial.\n  The codebase contains widespread RHF anti-patterns; without this skill you will\n  copy them. For form layout and which components to use, also load\n  studio-ui-patterns.\n---\n\n# React Hook Form\n\nHow to write forms that stay correct as they grow. The existing codebase is **not**\na safe reference: `form.watch()` off prop-drilled form objects, subscription-only\nwatches, unguarded `valueAsNumber`, and `?? undefined` controlled values are all\ncommon in older code and all wrong. Follow this skill, not the neighboring file.\n\n**Policy — fix what you touch.** New code must follow these rules. When you modify\nexisting form code, upgrade the specific fields/hooks/components you're editing to\nmatch (e.g. a component you touch that calls `form.watch` gets converted to\n`useWatch`). Leave untouched code alone, but tell the user about anti-patterns you\nnoticed and didn't fix. Never add new violations: `react-hook-form/no-use-watch`\nis ratcheted in Studio CI — any increase in the warning count fails the build.\n\n## Mental model: subscriptions decide who re-renders\n\nRHF is uncontrolled at heart. Values live in refs; nothing re-renders unless a\nsubscription says so. Every read API is a subscription decision:\n\n| API                           | Subscribes | Re-renders                 | Use for                                        |\n| ----------------------------- | ---------- | -------------------------- | ---------------------------------------------- |\n| `useWatch({ control, name })` | yes        | only the calling component | reactive value reads, anywhere                 |\n| `useFormState({ control })`   | yes        | only the calling component | `isDirty`/`errors`/etc. outside the form owner |\n| `formState` (destructured)    | yes        | the `useForm` owner        | form state **in the owner component only**     |\n| `form.watch(name)`            | yes        | the **entire form tree**   | avoid — lint-flagged, see below                |\n| `getValues()`                 | no         | never                      | event handlers and `onSubmit` only             |\n| `subscribe()`                 | callback   | none                       | side effects outside render                    |\n\nTwo facts explain most of the bugs we've shipped:\n\n1. **`form.watch()` and `form.formState` hoist their subscription to the `useForm`\n   owner**, no matter which component calls them. A child that reads\n   `form.watch('x')` off a prop works today only because the whole tree re-renders\n   on every change — it silently goes stale the moment anyone adds `React.memo`\n   between owner and child, and until then it re-renders every sibling on every\n   keystroke. A no-arg `form.watch()` sets `watchAll` and re-renders the tree on\n   every field change for the life of the form.\n2. **`formState` is a Proxy** — reading a property is what arms the subscription.\n   Destructure it (`const { isDirty } = form.formState`), never pass the object\n   around or read it conditionally (`a && formState.isValid` may never subscribe).\n   Enforced by `react-hook-form/destructuring-formstate` (error).\n\n### Reading values, by location\n\n- **In the component that owns `useForm`:** destructure `formState`; prefer\n  `useWatch` over `form.watch` even here (the `no-use-watch` rule flags every\n  `watch`, and `useWatch` scopes the re-render if the JSX is later extracted).\n- **In any child component or custom hook:** accept `control` (not the whole\n  `form`) and use `useWatch({ control, name })` / `useFormState({ control })`.\n  Inside `<Form {...form}>` (which _is_ `FormProvider`), `useFormContext()` +\n  `useWatch({ name })` also works and avoids prop-drilling entirely.\n- **Consume the return value.** Never call a watch for its subscription side\n  effect and then read via `getValues()` — the watch list and the read list will\n  drift apart (it has already happened; fields silently lost reactivity). The\n  value you render must _be_ the value you subscribed to.\n- **One read path per value per render.** Mixing `useWatch('x')` on one line and\n  `getValues('x')` a few lines later lets the two disagree within a single render.\n- **Name what you watch.** `useWatch({ control })` with no `name` re-renders on\n  every keystroke in every field. Subscribe to the specific names you use.\n- `watch(callback)` is deprecated — use `subscribe()` for render-free listeners,\n  and always return its cleanup from `useEffect`.\n\n```tsx\n// ❌ common in the codebase — all three subscriptions hoist to the form owner\nfunction Fields({ form }: { form: UseFormReturn<FormValues> }) {\n  form.watch(['storageType', 'totalSize'])        // return value discarded\n  const { errors } = form.formState               // prop-form formState\n  const size = form.getValues('totalSize')        // non-reactive read in render\n  ...\n}\n\n// ✅ child subscribes for itself and consumes what it watches\nfunction Fields({ control }: { control: Control<FormValues> }) {\n  const [storageType, totalSize] = useWatch({ control, name: ['storageType', 'totalSize'] })\n  const { errors } = useFormState({ control })\n  ...\n}\n```\n\n## The canonical form\n\nzod schema → `z.infer` type → `useForm` with `zodResolver` and **complete**\n`defaultValues` → `<Form {...form}>` → `FormField` render-prop per field →\n`FormItemLayout` → `FormControl` → primitive from `ui`. Layout/container choices\n(Card vs Sheet, `layout=` variants) are covered by the `studio-ui-patterns` skill\nand the demos in `apps/design-system/registry/default/example/`\n(`form-patterns-pagelayout.tsx`, `form-patterns-sidepanel.tsx`) — check them\nbefore inventing structure.\n\n```tsx\n// Module level — static references, not recreated on every render\nconst FORM_ID = 'pool-config-form'\n\nconst FormSchema = z.object({\n  name: z.string().min(1, 'Name is required'),\n  maxConnections: z\n    .union([z.literal(''), z.coerce.number().gte(1, 'Must be at least 1')])\n    .refine((v) => v !== '', 'Max connections is required'),\n})\ntype FormValues = z.infer<typeof FormSchema>\n\nconst defaultValues: FormValues = { name: '', maxConnections: '' }\n\n// Inside the component\nconst form = useForm<FormValues>({\n  resolver: zodResolver(FormSchema),\n  defaultValues,\n})\n\n<Form {...form}>\n  <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>\n    <FormField\n      control={form.control}\n      name=\"name\"\n      render={({ field }) => (\n        <FormItemLayout layout=\"horizontal\" label=\"Name\">\n          <FormControl>\n            <Input {...field} />\n          </FormControl>\n        </FormItemLayout>\n      )}\n    />\n  </form>\n</Form>\n```\n\nDefine the schema, `type`, static `defaultValues`, and the form's id at module\nlevel, outside the component. Rebuilding them per render is wasted work and\nunstable references — RHF reads `defaultValues` only on the first render, but\nanything else comparing against these objects sees a fresh identity each time.\nWhen they genuinely depend on runtime data, build the schema with `useMemo` and\nfeed server-driven defaults through the `values` option (next section) instead\nof hoisting.\n\nSubmit buttons living outside the `<form>` (sheet/dialog footers) use the same\nmodule-level `FORM_ID` via `form={FORM_ID}` on the button. A module-level id is\nonly safe for singleton forms — if the component can mount more than once at a\ntime, duplicate ids make external buttons submit the first matching form, so\nmint a per-instance id with `useId()` and share it between the `<form>` and its\nbuttons.\n\n## defaultValues, server data, and reset\n\n- **Provide a complete `defaultValues` object — every field, no `undefined`.**\n  `isDirty`, `dirtyFields`, and Cancel-reset all compare against it; a missing or\n  `undefined` default breaks all three, and `undefined` also makes React treat the\n  input as uncontrolled (see below).\n- **Form populated from an API? Use the `values` option, not a hand-rolled\n  effect.** `values` reacts to the query resolving and resets the form for you;\n  computing `defaultValues` from a query that may not have loaded freezes whatever\n  happened to be in cache at mount. Add\n  `resetOptions: { keepDirtyValues: true }` when a background refetch must not\n  clobber the user's in-progress edits. `keepDirtyValues` preserves whatever is\n  in `formState.dirtyFields`; typed edits and `setValue(…, { shouldDirty: true })`\n  populate it regardless of subscriptions, but `useFieldArray` operations\n  (append/remove/move) only mark fields dirty while `dirtyFields` or `isDirty`\n  is subscribed — so a form that combines `keepDirtyValues` with a field array\n  must read one of them in the owner, or the next refetch will discard array\n  edits. (Good examples:\n  `components/interfaces/Settings/Database/ConnectionLogging.tsx`,\n  `components/interfaces/Storage/FilesBuckets/EditBucketModal.tsx`.)\n- **After a successful mutation, re-baseline the form** in `onSuccess` so the\n  saved state becomes the new baseline (`isDirty` returns to false, Cancel now\n  reverts to the saved values). Prefer what the server actually persisted: if the\n  form uses `values` and the mutation invalidates the query, the refetch handles\n  this for you; if the mutation returns the updated resource, `reset(response)`.\n  `reset(submittedValues)` is the fallback for APIs that store exactly what was\n  sent — if the server normalizes or fills values, it baselines the form to data\n  that was never saved. A bare `reset()` reverts to the _previous_ defaults —\n  wrong after a save.\n- Cancel buttons call `form.reset()`. This only visually restores fields whose\n  values round-trip through defined, controlled values — which is why the null\n  rules below matter.\n\n## Controlled inputs: never let `value` flip to `undefined`\n\nReact decides controlled vs uncontrolled per render from whether `value` is\ndefined. A field whose value can be `undefined` (or becomes `undefined` on reset)\nflips modes: console warnings, and — worse — `reset()` stops clearing the visible\ntext because React abandoned the DOM value. `value={field.value ?? undefined}` is\na bug, not a fix.\n\n- Text fields: default to `''`, never `null`/`undefined`.\n- **Normalize `null` from the API at the form boundary** (`growthPercent ?? ''`\n  when building defaults) and convert back on submit (`'' → null`). Do not paper\n  over a `null` default with a `placeholder` that looks like a value: the user\n  sees \"50\", the form holds `null`, and every downstream comparison\n  (`defaultValues.growthPercent !== watched` → `null !== 50`) reports a permanent\n  phantom change while Cancel silently fails to reset the field.\n- Selects/radios: default to `''` or a real option value; checkboxes/switches to\n  `false`.\n\n## Number inputs\n\nThe blessed pattern keeps `''` as the \"empty\" sentinel so the input stays\ncontrolled, and lets zod coerce on validation (see `maxConnections` above):\n`z.union([z.literal(''), z.coerce.number()...]).refine((v) => v !== '', '…')`\nwith a plain `<Input {...field} type=\"number\" />`.\n\nIf you instead wire `onChange` through `e.target.valueAsNumber` (or\n`valueAsNumber: true`), an empty or partially-typed input produces `NaN`, which\nlands in form state and propagates into every calculation, price preview, and\n`value` attribute downstream. Guard it with the **same empty sentinel the\nfield's schema declares** — with the `''`-union schema above:\n`field.onChange(Number.isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber)`.\nNever let `NaN` into form state.\n\nA nullable API field (`null` = \"unset\", e.g. a platform default applies)\ndoesn't change the in-form sentinel — keep `''` inside the form and convert at\nthe boundaries:\n\n```tsx\n// inbound: null → '' when building defaults/values\nvalues: { growthPercent: data.growth_percent ?? '' },\n// schema: '' stays the in-form sentinel, zod coerces real input\ngrowthPercent: z.union([z.literal(''), z.coerce.number().gte(10).lte(100)]),\n// outbound: '' → null in onSubmit\nmutate({ growth_percent: values.growthPercent === '' ? null : values.growthPercent })\n```\n\nIf `null` does end up in form state (some existing forms hold it), keep it out\nof both the input and the coercion: render via `value={field.value ?? ''}`, and\ndon't pass the value through `z.coerce.number()` — `Number(null)` is `0`, so a\nnullable field fed into the coercing union silently validates empty as `0`.\nEither way it's one sentinel per field, used consistently across defaults,\nschema, `onChange`, rendering, and the submit mapping.\n\n## Dirty state and change detection\n\n- Gate Save on `isDirty`; show Cancel only when dirty. In the owner, destructure\n  from `form.formState`; anywhere else, `useFormState({ control })`.\n- When the form lives in a Sheet or Dialog, also wire dirty dismissal:\n  `useConfirmOnClose` + `DiscardChangesConfirmationDialog`. Route Cancel,\n  Escape, and backdrop through the guard; call the raw `onClose` on successful\n  submit so you do not prompt after save. Details:\n  `apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form\n  dismissal) and the studio-ui-patterns skill Sheets section.\n- To show _which_ fields changed (review/summary dialogs), read `dirtyFields`\n  from the same subscription instead of hand-comparing\n  `defaultValues.x !== watchedX`. RHF already does that comparison correctly;\n  hand-rolled versions break on the null-vs-placeholder mismatch and must be\n  kept in sync with the watch list by hand.\n- `setValue` outside user input needs explicit flags:\n  `setValue('x', v, { shouldDirty: true, shouldValidate: true })` — otherwise the\n  change is invisible to `isDirty` and validation.\n\n## Disabling and gating\n\nIf a field must not be edited (plan tier, permissions, cooldown), disable the\nfield itself — a notice next to an editable input gates nothing. Wire the same\ncondition into both the notice and the control. Permission checks come from\n`useAsyncCheckPermissions`; disabled buttons that need an explanation use\n`ButtonTooltip`.\n\nCaution: `register`/`useController` `disabled: true` removes the field's value\nfrom submission data. For \"visible but locked\" fields whose value must survive\nsubmit, use the input's own `disabled`/`readOnly` prop (as `FormField` +\nprimitive props do) rather than RHF-level disabling, or the form-level\n`disabled` option to freeze everything during async work.\n\n## Submit and mutations\n\n`onSubmit` receives validated, typed data — trust it; don't re-read via\n`getValues()`. Mutations follow Studio conventions: `onSuccess` → `toast.success`\n\n- `reset(values)` (or query invalidation when using `values:`), `onError` →\n  `toast.error`; pass the mutation's `isPending` to the button's `loading` prop.\n  Default validation `mode: 'onSubmit'` is right for most forms — pick another mode\n  deliberately, not by copying.\n\n## Lint rules in force (Studio)\n\n| Rule                                        | Level            | Meaning                                          |\n| ------------------------------------------- | ---------------- | ------------------------------------------------ |\n| `react-hook-form/destructuring-formstate`   | error            | destructure `formState`, never hold the object   |\n| `react-hook-form/no-access-control`         | error            | don't reach into `control` internals             |\n| `react-hook-form/no-nested-object-setvalue` | error            | `setValue('a.b', v)`, not `setValue('a', {b:v})` |\n| `react-hook-form/no-use-watch`              | warn (ratcheted) | use `useWatch`, not `watch`                      |\n", "skills/review-the-docs/SKILL.md": "---\nname: review-the-docs\ndescription: >-\n  Review Supabase docs changes locally in your `supabase/supabase` checkout —\n  either an open PR (triage, classify, verify) or your own branch before\n  opening a PR (local self-review). Covers markdown pipeline, MDX content,\n  tutorials, examples, Studio links, and docs tooling. Use when asked to\n  review docs PRs, self-review a draft branch, check who has approved,\n  verify build output, or evaluate supabase/supabase documentation changes.\n---\n\n# Review docs PRs\n\nLocal review workflow for `supabase/supabase` docs changes. Classify first, then follow the matching checklist.\n\nTwo modes:\n\n- **Open PR review** (default) — triage via `gh`, checkout, verify, report. Start at [Phase 1](#phase-1--triage-read-only).\n- **Local self-review** — no open PR yet; verify the current branch before opening one. Start at [Local self-review](#local-self-review-no-open-pr).\n\nFor **implementing** docs fixes (Linear tickets, worktrees, platform E2E), use [`work-linear-issue`](https://github.com/supabase/docs-agent-skills/blob/main/.claude/skills/work-linear-issue/SKILL.md) instead.\n\n## Core rules\n\n1. **Classify before reviewing** — path patterns determine which checklist applies.\n2. **Review stacked PRs bottom-up** — each PR may base on the previous branch.\n3. **Run verification locally** — do not approve from diff alone.\n4. **Compare against `master`** when the PR claims to fix missing or broken output.\n5. **One report per batch** — sequential review, consolidated output at the end.\n6. **Separate blockers from nits** — type/style notes are suggestions unless output breaks.\n\n## Repository layout\n\n| Path                                    | Purpose                                                          |\n| --------------------------------------- | ---------------------------------------------------------------- |\n| your local `supabase/supabase` checkout | Main clone for review checkouts                                  |\n| `apps/docs/content/guides/`             | Source MDX                                                       |\n| `apps/docs/internals/`                  | Markdown pipeline (`generate-guides-markdown.ts`, etc.)          |\n| `apps/docs/internals/markdown-schema/`  | Component handlers → plain markdown strings                      |\n| `apps/docs/public/markdown/guides/`     | Generated output (produced by build)                             |\n| `apps/docs/components/`                 | React MDX components                                             |\n| `examples/`                             | Tutorial/quickstart apps referenced via `$CodeSample`            |\n| `apps/studio/`                          | Dashboard UI; may link to hosted docs                            |\n| `.agents/skills/`                       | In-repo agent skills (canonical; `.claude/skills` symlinks here) |\n\n## Local self-review (no open PR)\n\nUse this on your own branch **before** opening a PR (checklist Stage 4). No `gh pr` required.\n\n```bash\ncd <your supabase/supabase checkout>\n# Ensure you're on the feature branch, not master\ngit branch --show-current\ngit diff --name-only master...HEAD\n```\n\n1. **Classify** from `git diff --name-only master...HEAD` using the [Phase 2](#phase-2--classify-pr-type) table.\n2. **Walk the bar** in [`pm-the-docs`'s checklist](../pm-the-docs/reference/write-the-docs-checklist.md) — \"What good looks like\" and the Self-review checkboxes.\n3. **Run type-specific checks** from the matching sections below on the current branch (no checkout step). Typical commands:\n\n```bash\n# Pipeline / schema handler\ncd apps/docs && pnpm build:guides-markdown\n# inspect public/markdown/guides/ for affected pages\npnpm build:reference-markdown   # when reference pipeline changed\n```\n\n4. Spot-check frontmatter, internal links, and nav wiring for content changes.\n   For content and tutorial changes, also read the change as a reader, per\n   [Content review](#content-review).\n5. **Offer runnable verification** — for content/tutorial PRs with new or changed procedural fenced blocks, ask whether to run [`test-the-docs`](../test-the-docs/SKILL.md). Prerequisites are class-specific (Docker Compose stack profile for DB/API; examples profile for `example-app`). If accepted, include the verification report; if declined or a required prerequisite for that class is missing, record credible `deferred` reasons for those artifacts only. Do not reimplement sandbox execution here.\n6. Write a short **self-review note** (blockers vs nits) suitable to paste into the future PR body under a \"Self-review\" heading.\n\nThen open the PR and continue with open-PR review if a second pass is needed.\n\n## Phase 1 — Triage (read-only)\n\n### List PRs\n\nFilter by author, label, or list all open docs PRs:\n\n```bash\n# By author\ngh pr list --repo supabase/supabase --author <github-user> --state open \\\n  --json number,title,url,reviewDecision,latestReviews,changedFiles,additions,deletions,labels\n\n# All open docs-labeled PRs\ngh pr list --repo supabase/supabase --state open --label documentation \\\n  --json number,title,url,reviewDecision,latestReviews,author,changedFiles\n```\n\nPRs with empty `reviewDecision` and no `APPROVED` review need approval.\n\n### Map the stack\n\n```bash\ngh pr view <number> --repo supabase/supabase \\\n  --json number,title,baseRefName,headRefName,body,files\n```\n\nStacked series: `master → PR A → PR B → PR C`. Review and merge bottom-up.\n\n## Phase 2 — Classify PR type\n\nInspect changed files from `gh pr view` or:\n\n```bash\ngh pr diff <number> --repo supabase/supabase --name-only\n```\n\n| PR type                     | Path signals                                                                                                               | Primary skill section                                          |\n| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |\n| **Markdown-schema handler** | `apps/docs/internals/markdown-schema/`, `generate-guides-markdown.ts`                                                      | [Schema handler review](#schema-handler-review)                |\n| **Pipeline / internals**    | `apps/docs/internals/` (not just one new handler)                                                                          | [Pipeline review](#pipeline-review)                            |\n| **Content-only MDX**        | `apps/docs/content/**` only                                                                                                | [Content review](#content-review)                              |\n| **Tutorial / quickstart**   | `apps/docs/content/guides/**/tutorials/`, `quickstarts/`, plus `examples/`                                                 | [Tutorial review](#tutorial-review) → also `work-linear-issue` |\n| **Example app only**        | `examples/**` without matching MDX                                                                                         | [Example review](#example-review)                              |\n| **Studio ↔ docs links**     | `apps/studio/**`                                                                                                           | [Studio review](#studio-review)                                |\n| **Docs UI / components**    | `apps/docs/components/`, `apps/docs/features/` (no pipeline)                                                               | [Component review](#component-review)                          |\n| **Docs tooling**            | `.agents/skills/`, `apps/docs/AGENTS.md`, `apps/docs/CONTRIBUTING.md`, `apps/docs/DEVELOPERS.md`, `apps/docs/style-guide/` | [Docs tooling review](#docs-tooling-review)                    |\n| **Mixed**                   | Multiple path groups above                                                                                                 | Run each applicable section; note overlap                      |\n\nWhen a PR spans types (e.g. schema handler + component refactor), run **all** matching sections.\n\n## Phase 3 — Sequential local review\n\nRepeat for **each PR** (bottom of stack first).\n\n### Common steps (all PR types)\n\n**Checkout and install:**\n\n```bash\ncd <your supabase/supabase checkout>\ngh pr checkout <number> --repo supabase/supabase\npnpm install --filter docs...   # when node_modules missing or deps changed\n```\n\n**CI spot-check:**\n\n```bash\ngh pr checks <number> --repo supabase/supabase\n```\n\n**Baseline on master** (when PR fixes missing/broken output):\n\n```bash\ngit checkout master\n# run type-specific verify command (see sections below)\ngit checkout -   # return to PR branch\n```\n\n---\n\n### Schema handler review\n\nFor PRs adding static markdown fallbacks for React MDX components.\n\n**Code checks** — each handler in `apps/docs/internals/markdown-schema/`:\n\n| Check            | What to verify                                                           |\n| ---------------- | ------------------------------------------------------------------------ |\n| Data source      | Same data/constants as the React component — no duplicated config        |\n| CJS interop      | `shared-data` via `createRequire(import.meta.url)` (see `SharedData.ts`) |\n| Local JSON       | Direct imports fine for `apps/docs/data/`                                |\n| Link prefix      | Links use `withDocsBasePath`                                             |\n| SCHEMA wiring    | Registered in `SCHEMA` in `generate-guides-markdown.ts`                  |\n| Props / shapes   | All MDX usages covered — flat arrays and `{ items: [...] }` sections     |\n| Silent fallbacks | `''` for unknown props OK if consistent with existing handlers           |\n\nFind usages: `rg '<ComponentName' apps/docs/content/`\n\n**Build and inspect:**\n\n```bash\ncd apps/docs && pnpm build:guides-markdown\n# Expect: \"Generated N markdown files\" where N roughly matches the .mdx count under content/guides/\n```\n\nInspect `public/markdown/guides/` for affected pages:\n\n- Previously blank sections now have lists, tables, or links\n- All MDX pages using the component are covered, not just the one in the PR description\n- Link format: `/docs/guides/...` locally; absolute URLs when `VERCEL_ENV=production`\n\n---\n\n### Pipeline review\n\nFor AST refactors, link rewriting, reference markdown generation, etc.\n\n```bash\ncd apps/docs\npnpm build:guides-markdown\npnpm build:reference-markdown   # when reference pipeline changed\npnpm test:local:unwatch internals/internal-links.test.ts   # when link handling changed (needs local Supabase — see apps/docs/AGENTS.md)\n```\n\nVerify both guides and reference output when `generate-reference-markdown.ts` or `internal-links.ts` changed.\n\n---\n\n### Content review\n\nMDX prose, partials, navigation — no pipeline or example changes.\n\n**Read the change as a reader first.** A change can pass every checklist item and\nstill read wrong on the page. Before the checklist:\n\n1. Read the whole page that the change edits, not only the diff: every heading, and\n   the full sections around the change.\n2. Read each page and section that the change links to, and search\n   `apps/docs/content/` for other pages on the same topic.\n3. Find what the change is for: the linked issue, or the PR's Problem section (in a\n   self-review, the planned PR description). Check that the page now does that for\n   the reader.\n\nReport each way the change reads wrong on the page. The following problems are\ncommon, but they aren't the full list:\n\n- Content tied to the same problem that the change left as it was, such as a\n  screenshot of an old UI.\n- New text that breaks the pattern of the sections around it, or makes a nearby\n  sentence untrue, such as \"the steps above\".\n- A fact that another section or page already states.\n- Detail that only explains one reporter's case, or an admonition that holds the\n  main explanation.\n- The first question a reader asks next, left unanswered, or a command whose side\n  effect the page doesn't name.\n- Two sections that send the reader to each other.\n\nCheck the prose against the [style guide](../../../apps/docs/style-guide/README.md) yourself. No CI or local\ncheck covers style or terminology. CodeRabbit reviews style, terminology, and\nstructure on `apps/docs/content/**/*.mdx`, but only once the PR is open.\n\nCheck [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md) against the finished page last, using the\ntwo-pass protocol in [Use with an AI agent](../../../apps/docs/style-guide/WORD_LIST.md#use-with-an-ai-agent): [Phrase\ngroups](../../../apps/docs/style-guide/WORD_LIST.md#phrase-groups) for the literal term lists, then `grep '^### '\nWORD_LIST.md` and read only the entries matching words on the page. Include terms\nthe author didn't introduce.\n\nChecklist:\n\n- [ ] Read the change as a reader (above), and each problem is reported\n- [ ] Voice follows [`01-voice-and-tone.md`](../../../apps/docs/style-guide/01-voice-and-tone.md)\n- [ ] Section grouping and chunking follow [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md)\n- [ ] When the page's row in [Choose a template](../../../apps/docs/style-guide/03-page-structure.md#choose-a-template) names a template, the page follows it and passes that template's checklist. A misfit section that `edit-the-docs` kept in place and noted for a split-out is a recommendation to raise, not a failure\n- [ ] Components follow [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md)\n- [ ] Terminology matches [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md)\n- [ ] Frontmatter valid (`title`, `description` where required)\n- [ ] Internal links resolve (`/docs/guides/...`, not broken anchors)\n- [ ] `$CodeSample` paths match existing example directories\n- [ ] Admonitions, tabs, and partial includes render sensibly in PR preview\n- [ ] No accidental whitespace-only or empty sections where components were removed\n- [ ] Offered [`test-the-docs`](../test-the-docs/SKILL.md) for new/changed procedural snippets; verification report present or credible `deferred` reasons recorded\n\nCompare PR preview URL (from Vercel/deployment comment) against production for visual regressions when layout components are involved.\n\n---\n\n### Tutorial review\n\nTutorial MDX plus matching example app. **Read [`work-linear-issue`](https://github.com/supabase/docs-agent-skills/blob/main/.claude/skills/work-linear-issue/SKILL.md)** for full platform E2E — review is not complete without it when auth flows are involved.\n\n```bash\n# Example build (from work-linear-issue)\ncd examples/<example-dir>\nnpm install && npm run build\n```\n\nBefore the checklist, read the tutorial as a reader, per [Content review](#content-review).\nIn a tutorial, check most closely for steps that refer to each other, such as \"the\nsteps above\", and for commands whose side effects the page doesn't name.\n\nChecklist:\n\n- [ ] Read the change as a reader, and each problem is reported\n- [ ] MDX steps match example code after `pnpm codegen:examples` (if `$CodeSample` used)\n- [ ] Env var names and Supabase client setup match current `@supabase/ssr` patterns\n- [ ] Example pins catalog versions — no `\"latest\"` for in-repo packages\n- [ ] Offered [`test-the-docs`](../test-the-docs/SKILL.md) for procedural tutorial steps (or `deferred` with reason)\n- [ ] **Platform E2E** (when auth involved): SQL migration applied, auth flow walked, profiles verified — see `work-linear-issue` Phase 3\n\n---\n\n### Example review\n\nExample-only PRs (or example portion of a tutorial PR).\n\n```bash\ncd examples/<example-dir>\nnpm install && npm run build\n```\n\nChecklist:\n\n- [ ] Build passes with no type errors\n- [ ] `.env.example` documents required vars (no secrets committed)\n- [ ] If docs reference this example, `$CodeSample` paths still valid\n\n---\n\n### Studio review\n\nDashboard changes linking to docs.\n\nChecklist:\n\n- [ ] Links point to hosted docs anchors (e.g. `/guides/auth/auth-email-templates#terminology`)\n- [ ] Local-dev-only doc paths not used as the sole link target\n- [ ] Link text matches the destination section\n\n---\n\n### Component review\n\nReact component changes under `apps/docs/components/` without a new schema handler.\n\nChecklist:\n\n- [ ] No browser-only APIs leaked into build-script imports\n- [ ] Shared constants extracted cleanly when also consumed by markdown handlers\n- [ ] Visual behavior unchanged or intentionally improved — check PR screenshots\n- [ ] If component is used in MDX exported to markdown, confirm a schema handler exists or file an follow-up\n\n---\n\n### Docs tooling review\n\nAgent skills, contributor docs, or skill symlink wiring — no MDX/pipeline changes required.\n\nChecklist:\n\n- [ ] `.agents/skills/` is the canonical location — no skill content added anywhere else\n- [ ] `.claude/skills` is still a single Git symlink to `../.agents/skills` — no per-skill symlinks or copies under `.claude/`\n- [ ] Cross-skill links resolve: relative for in-repo skills; absolute `docs-agent-skills` URLs only for skills that remain in that private repo\n- [ ] No personal vault paths, Obsidian references, or private-process-only instructions\n- [ ] `apps/docs/CONTRIBUTING.md` / `DEVELOPERS.md` / `AGENTS.md` pointers match skill names and checklist stages\n- [ ] A style rule added to a skill belongs in `apps/docs/style-guide/` instead, with the skill pointing at it\n- [ ] Reference files under a skill stay near the ~250-line guideline (split if bloated)\n\n```bash\n# Symlink smoke check\ntest \"$(readlink .claude/skills)\" = \"../.agents/skills\"\ntest -f .claude/skills/<skill-name>/SKILL.md\n\n# Leftover internal refs\nrg -n 'Obsidian|pm-the-docs-full|Priorities/' .agents/skills\n```\n\n---\n\n## Phase 4 — Review report\n\nOne consolidated report after all PRs are reviewed.\n\n### Report template\n\n```markdown\n# PR review report — <author, label, or topic>\n\nReviewed locally in a `supabase/supabase` checkout.\n\n**Stack order:** master → #NNN → … (if applicable)\n\n---\n\n## [#NNN — Title](https://github.com/supabase/supabase/pull/NNN)\n\n**Type:** schema handler | pipeline | content | tutorial | example | studio | component | docs tooling | mixed\n\n**Verdict:** Approve | Approve with nits | Request changes\n\n| Check              | Result |\n| ------------------ | ------ |\n| PR type checks     | …      |\n| Build / lint       | …      |\n| Baseline vs master | …      |\n| CI                 | …      |\n\n**Verified:**\n\n- …\n\n**Notes:**\n\n- …\n\n---\n\n## Summary\n\n| PR   | Type | Recommendation | Blockers |\n| ---- | ---- | -------------- | -------- |\n| #NNN | …    | …              | …        |\n\n**Merge order:** bottom-up after approval (if stacked).\n```\n\n### Verdict guidance\n\n| Verdict               | When                                                                                 |\n| --------------------- | ------------------------------------------------------------------------------------ |\n| **Approve**           | All type-specific checks pass; output correct                                        |\n| **Approve with nits** | Works correctly; minor type/style/docs nits only                                     |\n| **Request changes**   | Build/lint fails, broken links, wrong data, missing coverage, or failed platform E2E |\n\n## Inline review comments\n\n```text\nhttps://github.com/supabase/supabase/pull/<number>/files#diff-<blob-sha>R<line>\n```\n\n```bash\ngh api repos/supabase/supabase/pulls/<number>/files \\\n  --jq '.[] | select(.filename | endswith(\"<file>\")) | .sha'\n```\n\nInclude concrete evidence — JSON line numbers, before/after output snippets, failing command output.\n\n## Handler pattern reference\n\n```typescript\n// apps/docs/internals/markdown-schema/Example.ts\nimport { withDocsBasePath } from '../internal-links'\n\nexport const Example = ({ props }: { props: Record<string, unknown> }): string => {\n  // Same data source as React component → plain markdown string\n}\n```\n\n## Parallel work\n\nIndependent PRs: subagents can review in separate worktrees. **Stacked** series: review sequentially on one clone, bottom-up.\n\n## Output checklist\n\n- [ ] Approval status fetched for all requested PRs\n- [ ] Each PR classified by type\n- [ ] Stack order documented (if applicable)\n- [ ] Type-specific verification run locally (not just schema handler defaults)\n- [ ] Master baseline compared when PR fixes missing output\n- [ ] Platform E2E noted for tutorial/auth PRs (or deferred with reason)\n- [ ] Verdict and blockers stated per PR\n- [ ] Merge order recommended\n- [ ] Inline comment links provided for nits\n", "skills/safe-sql-execution/SKILL.md": "---\nname: safe-sql-execution\ndescription: >-\n  Use whenever code will build, return, fetch, or execute SQL that runs against\n  a user's real Postgres database — even when the request reads like an ordinary\n  feature or bug fix and never says \"security,\" \"injection,\" or\n  \"SafeSqlFragment.\" This covers: writing or editing any pg-meta function, query\n  builder, or endpoint that builds/returns SQL for database objects (tables,\n  views, functions, DB triggers, indexes, RLS policies); interpolating a\n  schema/table/column/search/route-param value into SQL text; storing, fetching,\n  or re-running SQL that round-trips from the database (a policy's definition, a\n  function/view definition, a snippet's saved content); and any\n  \"Run\"/\"Apply\"/\"Execute\" action that sends SQL to a project's database (SQL\n  editor run-selection, policy editor apply, snippet runner). Load this BEFORE\n  writing such code, not only when reviewing a finished diff. Skip only for\n  changes that never touch SQL text or execution — styling, unrelated data\n  hooks, non-SQL form validation, or UI layout work.\n---\n\n# Safe SQL execution\n\nSupabase Studio executes SQL statements directly against the user's database.\nBecause this is the authenticated user's own database, our security model is\ndifferent from most frontend applications: a user should be able to execute any\nSQL statement, as long as it is proven that they themselves authored it. What\nwe SHOULD NOT ALLOW is execution of SQL statements that can be influenced by an\nattacker, such as through URL parameters.\n\n## Security model\n\nThe security model for SQL execution in Supabase Studio is based on the\nprinciple of \"proven authorship\". This means that a user should only be able to\nexecute SQL statements that they have explicitly authored, and not statements\nthat can be influenced by external input.\n\nThere are three classes of SQL fragments:\n\n1.  Hardcoded within the application code. These are safe to execute because\n    they cannot be influenced by an attacker. They can be marked with the\n    `safeSql` utility with `pg-meta`:\n\n    ```ts\n    import { safeSql } from '@supabase/pg-meta'\n\n    const sql = safeSql`\n      SELECT *\n      FROM users\n      WHERE id = 1\n    `\n    ```\n\n    `safeSql` automatically creates a string of the branded type\n    `SafeSqlFragment`. (See Provenance Tracking below.)\n\n2.  Third-party influenceable. These are SQL fragments that can be influenced\n    by an attacker, such as through URL parameters or LLM output. These should\n    be marked with the `untrustedSql` utility with `pg-meta`:\n\n    ```ts\n    import { untrustedSql } from '@supabase/pg-meta'\n\n    const unsafeQuery = searchParams.get('query')\n    const querySql = untrustedSql(unsafeQuery)\n    ```\n\n    `untrustedSql` creates a string of the branded type `UntrustedSqlFragment`.\n    (See Provenance Tracking below.)\n\n3.  User-authored. These are SQL fragments that are authored by the user\n    themselves within the UI, for example in a text input field. Because the\n    user is the author, these should be considered safe to execute.\n\n    However, there is a caveat, where third-party and user-authored code can\n    mix, contaminating the user-authored code (for example, if an input is\n    prefilled from an unsanitized URL parameter). Provenance tracking helps us\n    track these cases.\n\n    For example, a safe input component could be implemented as follows by requiring that its placeholder and controlled value are of type `SafeSqlFragment`. In this case we can use its onChange to promote the user input to `SafeSqlFragment` type, because we know that the user is the author of the input. An implementation of this is in\n    @apps/studio/components/ui/SafeSqlInput.tsx:\n\n    ```ts\n    import { rawSql, type SafeSqlFragment } from '@supabase/pg-meta'\n    import type { ChangeEvent, ComponentProps } from 'react'\n    import { Input } from 'ui-patterns/DataInputs/Input'\n\n    type InputProps = ComponentProps<typeof Input>\n\n    export type SafeSqlInputProps = Omit<\n      InputProps, 'placeholder' | 'value' | 'onChange'\n    > & {\n      placeholder?: SafeSqlFragment\n      value: SafeSqlFragment\n      onChange?:\n        (event: ChangeEvent<HTMLInputElement>, value: SafeSqlFragment) => void\n    }\n\n    export const SafeSqlInput = ({ onChange, ...props }: SafeSqlInputProps) => (\n      <Input\n        {...props}\n        onChange={(event) => onChange?.(event, rawSql(event.target.value))}\n      />\n    )\n    ```\n\n    This is pretty much the ONLY VALID USE CASE of the rawSql export from\n    pg-meta, and it should be used with caution.\n\n## Provenance tracking\n\nBranded types are used to track the provenance of SQL fragments. The types,\nexported from `pg-meta`, are:\n\n- `SafeSqlFragment`: represents SQL fragments that are safe to execute, because\n  they are either hardcoded in the application or authored by the user\n  themselves.\n- `UntrustedSqlFragment`: represents SQL fragments that can be influenced by an\n  attacker, such as through URL parameters or LLM output.\n\nThese are valid ways to generate a `SafeSqlFragment`:\n\n- Using the `safeSql` utility from `pg-meta` to create hardcoded SQL fragments.\n- Using the sanitization utilities from `pg-meta` to sanitize untrusted input\n  and promote it to a `SafeSqlFragment`:\n  - `ident`\n  - `literal`\n  - `keyword`\n- Using the safe SQL manipulation utilities:\n  - `joinSqlFragments` (from `pg-meta`)\n  - `trimSafeSqlFragment` (from `apps/studio/lib/sql.ts`)\n\n`UntrustedSqlFragments` can be generated from raw strings using\n`untrustedSql()`.\n\nThere is also a union type, `DisplayableSqlFragment`, which represents SQL fragments that can be safely displayed in the UI, but not necessarily executed. This includes both `SafeSqlFragment` and `UntrustedSqlFragment`.\n\n## Security of SQL round-tripped from the user's database\n\nSQL derived directly from catalog tables (e.g., function definitions, RLS\nexpressions, etc.) is considered safe, and it is promoted AT THE POINT OF\nBEING QUERIED from the database. In most cases, this is in an\napps/studio/data/\\*_/_.ts file, in the utility function that makes the API or\ndatabase fetch.\n\nA critical exception to the safety of SQL round-tripped from the database is\nuser snippets. These must NEVER BE CONSIDERED SAFE because they are both (a)\nexternally influenceable and (b) auto-saved. The snippet type uses the\n`unchecked_sql` property, which is an `UntrustedSqlFragment`, to enforce this.\n\n## Promoting SQL fragments to `SafeSqlFragment` type\n\nGiven an insecure string or `UntrustedSqlFragment`, how do we promote it safely\nto a `SafeSqlFragment`?\n\n### Sanitization utilities\n\nThis is the preferred method when the input is sanitizable, e.g., it is a\nrelation name, a column name, will be compared as a literal, etc.\n\nThe pg-meta library provides the following sanitization utilities that can be\nused to safely promote untrusted input to `SafeSqlFragment`:\n\n- `ident`: for sanitizing identifiers such as table names or column names.\n- `literal`: for sanitizing literal values that will be used in SQL statements.\n- `keyword`: for sanitizing SQL keywords.\n\n### `acceptUntrustedSql`\n\nSome untrusted SQL fragments cannot be sanitized with the above utilities. For\nexample, the `USING` expression in the RLS policy editor is an arbitrary SQL\nexpression.\n\nIn these cases, we can promote the SQL fragment _upon explicit user action_.\nUser action indicates that the user has seen the SQL and is OK with running it.\nFor example, an explicit user action could be clicking a \"Run\" button.\n\nThe promotion happens with the `acceptUntrustedSql` utility from `pg-meta`,  \nwhich takes an `UntrustedSqlFragment` and returns a `SafeSqlFragment`.\n\nThis utility MUST ONLY BE USED IN event handlers. It should NEVER be used in\na useQuery, direct in the render body of a component, in a useEffect, or\nanywhere it could auto-run without explicit user action.\n\nThis is safe:\n\n```ts\nimport { acceptUntrustedSql } from '@supabase/pg-meta'\n\nfunction SafeComponent() {\n  const { mutate: execute } = useExecuteSqlMutation()\n\n  const handleRun = () => {\n    // ✅ GOOD: Safe because it is in an event handler which requires a user\n    // click\n    execute({ sql: acceptUntrustedSql(/* sql */) })\n  }\n\n  return (\n    <button onClick={handleRun}>Run</button>\n  )\n}\n```\n\nThis is unsafe:\n\n```ts\nimport { acceptUntrustedSql } from '@supabase/pg-meta'\n\nfunction UnsafeComponent() {\n  const { data } = useQuery({\n    queryKey: ['execute-sql', sql],\n    queryFn: () => {\n      // 🛑 BAD: Unsafe because it is in a query which could auto-run without\n      // explicit user action\n      return execute({ sql: acceptUntrustedSql(/* sql */) })\n    },\n  })\n}\n```\n\n## Type guarantees\n\nSQL run against the user's Postgres database runs through the `executeSql`\nfunction, which only takes arguments of type `SafeSqlFragment` for the SQL\nparameter. Raw strings or `UntrustedSqlFragment`s will error at compile time.\n\n## Examples\n\n### Hard-coded SQL\n\n```ts\n// ✅ GOOD: Automatically safe with `safeSql` utility\nconst selectStatement = safeSql`select 1`\n```\n\n### SQL with sanitizable interpolations\n\n```ts\n// ✅ GOOD: `pg-meta` utilities sanitize the input\nconst tableName = ident(userInputTableName)\nconst searchString = literal(userInputSearchString)\nconst sqlStatement = safeSql`\n  SELECT *\n  FROM ${tableName}\n  WHERE search_column = ${searchString}\n`\n```\n\n```ts\n// 🛑 BAD: Passing raw strings will type error\nconst tableName = 'my_table'\nconst sqlStatement = safeSql`\n  SELECT *\n  FROM ${tableName}\n`\n```\n\n### Non-sanitizable SQL from a user input\n\n```ts\n// ✅ GOOD: SafeSqlInput only allows a value that is a SafeSqlFragment\nimport { SafeSqlInput } from '@apps/studio/components/ui/SafeSqlInput'\n\nfunction MyComponent() {\n  const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)\n\n  return (\n    <SafeSqlInput\n      placeholder={safeSql`Enter your SQL query here...`}\n      value={sql}\n      onChange={(event, value) => setSql(value)}\n    />\n  )\n}\n```\n\n```ts\n// 🛑 BAD: This input mixes SafeSqlFragments and unsafe strings\n\nfunction MyBadComponent() {\n  const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)\n\n  return (\n    <Input\n    // 🛑 BAD: This is unsafe because the placeholder is a raw string\n      placeholder=\"Enter your SQL query here...\"\n      value={sql}\n      onChange={(event) => setSql(event.target.value)}\n    />\n  )\n}\n```\n\n### Round-tripping SQL from the database (NOT snippet content)\n\n```ts\n// ✅ GOOD: SQL from the database is promoted to SafeSqlFragment at the point\n// of fetching\n\n// data/function-definitions.ts\nfunction markFunctionDefinitionSafe(\n  functionDefinition: FunctionDefinition\n): SafeFunctionDefinition {\n  return {\n    ...functionDefinition,\n    definition: functionDefinition.definition as SafeSqlFragment,\n  }\n}\n\n// data/function-definitions.ts\nfunction getFunctionDefinitions() {\n  return GET(`/function-definitions`).then((functionDefinitions) =>\n    functionDefinitions.map(markFunctionDefinitionSafe)\n  )\n}\n```\n\n```ts\n// 🛑 BAD: Strings are promoted to SafeSqlFragment in a utility function, where\n// it is impossible to easily determine the safety of the input\n\n// utils.ts\nfunction markFunctionDefinitionSafe(\n  functionDefinition: FunctionDefinition\n): SafeFunctionDefinition {\n  return {\n    ...functionDefinition,\n    definition: functionDefinition.definition as SafeSqlFragment,\n  }\n}\n\n// Component.ts\nfunction MyComponent() {\n  const { data: functionDefinitions } = useFunctionDefinitions()\n  const safeFunctionDefinitions = functionDefinitions.map(markFunctionDefinitionSafe)\n}\n```\n\n### Snippet content is ALWAYS UNSAFE\n\nSnippets are auto-persisted to the database and can be created or modified\nthrough externally influenceable channels (e.g., prefilled from URL params).\nThe `unchecked_sql` property is typed as `UntrustedSqlFragment` to enforce this\n— it must only be promoted to `SafeSqlFragment` via `acceptUntrustedSql` in an\nevent handler that requires explicit user action.\n\n```ts\n// 🛑 BAD: Snippet content is executed automatically via useQuery, with no\n// explicit user action confirming that the user has reviewed the SQL.\nimport { acceptUntrustedSql } from '@supabase/pg-meta'\n\nfunction UnsafeSnippetPreview({ snippet }: { snippet: Snippet }) {\n  const { data } = useExecuteSqlQuery({\n    sql: acceptUntrustedSql(snippet.content.unchecked_sql),\n  })\n\n  return <Results data={data} />\n}\n```\n\n```ts\n// 🛑 BAD: Casting bypasses the type system entirely. The snippet's\n// `unchecked_sql` is `UntrustedSqlFragment` for a reason — never cast it.\nfunction UnsafeSnippetRunner({ snippet }: { snippet: Snippet }) {\n  const { mutate: execute } = useExecuteSqlMutation()\n\n  useEffect(() => {\n    execute({ sql: snippet.content.unchecked_sql as SafeSqlFragment })\n  }, [snippet])\n}\n```\n\n```ts\n// ✅ GOOD: Snippet content is only promoted to SafeSqlFragment inside an event\n// handler, after the user clicks Run. The user has seen the SQL in the editor\n// and explicitly chosen to execute it.\nimport { acceptUntrustedSql } from '@supabase/pg-meta'\n\nfunction SnippetRunner({ snippet }: { snippet: Snippet }) {\n  const { mutate: execute } = useExecuteSqlMutation()\n\n  const handleRun = () => {\n    execute({ sql: acceptUntrustedSql(snippet.content.unchecked_sql) })\n  }\n\n  return (\n    <>\n      <SnippetEditor snippet={snippet} />\n      <button onClick={handleRun}>Run</button>\n    </>\n  )\n}\n```\n\n## Analytics SQL (BigQuery / ClickHouse)\n\nThe same security model applies to analytics queries, which target BigQuery\nor ClickHouse via the\n`/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel}` endpoints.\nFilter keys and values from URL parameters and UI inputs are spliced into SQL\nthat runs against the project's logs, so the same injection risk exists.\n\nAnalytics SQL uses its own `SafeLogSqlFragment` brand\n(`apps/studio/data/logs/safe-analytics-sql.ts`), intentionally **disjoint**\nfrom the pg-meta `SafeSqlFragment` brand. The brands are kept separate because\nescape semantics differ — Postgres-safe `E'…'` strings, `::jsonb` casts, and\ndouble-quoted identifiers are unsafe for BigQuery and/or ClickHouse, and vice\nversa. Crossing the brands would silently emit unsafe SQL.\n\nThe wire boundary is `executeAnalyticsSql` in\n`apps/studio/data/logs/execute-analytics-sql.ts`, analogous to pg-meta's\n`executeSql`; it accepts only `SafeLogSqlFragment`, and an eslint\n`no-restricted-syntax` rule in `apps/studio/eslint.config.cjs` blocks direct\n`post()`/`get()` calls to the `logs.all` endpoints from any other file.\n\nBuild fragments with the helpers in `safe-analytics-sql.ts`:\n\n- `safeSql` — template tag that only accepts `SafeLogSqlFragment`\n  interpolations; plain strings and Postgres `SafeSqlFragment`s are rejected at\n  compile time.\n- `analyticsLiteral(value)` — sanitizes string/number/boolean literals.\n- `quotedIdent(name)` — validates and backtick-quotes dotted identifiers.\n- `keyword(value, allowed)` — resolves a value against an allow-list of\n  fragments (e.g. `AND`/`OR`); never returns the raw input.\n- `joinSqlFragments(fragments, separator)` — composes already-branded\n  fragments.\n\n```ts\nimport { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'\nimport { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'\n\n// ✅ GOOD: every interpolation is sanitized.\nconst sql = safeSql`\n  SELECT timestamp, event_message\n  FROM ${quotedIdent(table)}\n  WHERE id = ${analyticsLiteral(id)}\n`\n\nawait executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })\n```\n\n```ts\n// 🛑 BAD: raw string interpolation. This fails to type-check at the\n// executeAnalyticsSql boundary because the result is `string`, not\n// `SafeLogSqlFragment`.\nconst sql = `SELECT * FROM ${table} WHERE id = '${id}'`\nawait executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start, iso_timestamp_end })\n```\n\nThe only path that runs SQL not built from these helpers is user-authored\neditor text: `untrustedLogSql(text)` marks it `UntrustedLogSqlFragment`\n(displayable and storable, never executable), and `acceptUntrustedLogsSql`\npromotes it to `SafeLogSqlFragment`. That promotion is a **security boundary**\n— call it only from a run gesture (Run button click, Cmd+Enter) or an\napproval-gated tool call (the AI notebook tools). Never from render,\n`useEffect`, or any automatic path. The notebook persist path also promotes\ncells because the writable notebook type requires the safe brand; that is\nstorage typing, not execution approval, and is not precedent for promoting\nanywhere else. The same rule as `acceptUntrustedSql` on the Postgres side.\n\nEndpoint selection, the OTEL query builders, and the rest of the Studio\nwiring live in the `clickhouse-logs-queries` skill\n(`references/codebase-integration.md`).\n", "skills/studio-e2e-tests/SKILL.md": "---\nname: studio-e2e-tests\ndescription: Write and run Playwright E2E tests for Supabase Studio (e2e/studio).\n  Use when asked to run e2e tests, write new E2E tests, or debug flaky or failing\n  Playwright tests. Covers running commands, avoiding race conditions, waiting\n  strategies, selectors, helper functions, and CI vs local differences.\n---\n\n# E2E Studio Tests\n\nRun Playwright end-to-end tests for the Studio application.\n\n## Running Tests\n\nTests must be run from the `e2e/studio` directory:\n\n```bash\ncd e2e/studio && pnpm run e2e\n```\n\n### Run specific file\n\n```bash\ncd e2e/studio && pnpm run e2e -- features/cron-jobs.spec.ts\n```\n\n### Run with grep filter\n\n```bash\ncd e2e/studio && pnpm run e2e -- --grep \"test name pattern\"\n```\n\n### UI mode for debugging\n\n```bash\ncd e2e/studio && pnpm run e2e -- --ui\n```\n\n## Environment Setup\n\n- Tests auto-start Supabase local containers via web server config\n- Self-hosted mode (`IS_PLATFORM=false`) runs tests in parallel (3 workers)\n- No manual setup needed for self-hosted tests\n\n## Test File Structure\n\n- Tests are in `e2e/studio/features/*.spec.ts`\n- Use custom test utility: `import { test } from '../utils/test.js'`\n- Test fixtures provide `page`, `ref`, and other helpers\n\n## Common Patterns\n\nWait for elements with generous timeouts:\n\n```typescript\nawait expect(locator).toBeVisible({ timeout: 30000 })\n```\n\nUse serial mode for tests sharing database state:\n\n```typescript\ntest.describe.configure({ mode: 'serial' })\n```\n\n## Writing Robust Selectors\n\n### Selector priority (best to worst)\n\n1. **`getByRole` with accessible name** - Most robust, tests accessibility\n\n   ```typescript\n   page.getByRole('button', { name: 'Save' })\n   page.getByRole('button', { name: 'Configure API privileges' })\n   ```\n\n2. **`getByTestId`** - Stable, explicit test hooks\n\n   ```typescript\n   page.getByTestId('table-editor-side-panel')\n   ```\n\n3. **`getByText` with exact match** - Good for unique text\n\n   ```typescript\n   page.getByText('Data API access', { exact: true })\n   ```\n\n4. **`locator` with CSS** - Use sparingly, more fragile\n   ```typescript\n   page.locator('[data-state=\"open\"]')\n   ```\n\n### Patterns to avoid\n\n- **XPath selectors** - Fragile to DOM changes\n\n  ```typescript\n  // BAD\n  locator('xpath=ancestor::div[contains(@class, \"space-y\")]')\n  ```\n\n- **Parent traversal with `locator('..')`** - Breaks when structure changes\n\n  ```typescript\n  // BAD\n  element.locator('..').getByRole('button')\n  ```\n\n- **Broad `filter({ hasText })` on generic elements** - May match multiple elements\n  ```typescript\n  // BAD - popover may have more than one combobox\n  // Could consider scoping down the container or filtering the combobox more specifically\n  popover.getByRole('combobox')\n  ```\n\n### Add accessible labels to components\n\nWhen a component lacks a good accessible name, add one in the source code:\n\n```tsx\n// In the React component\n<Button aria-label=\"Configure API privileges\">\n  <Settings />\n</Button>\n```\n\nThen use it in tests:\n\n```typescript\npage.getByRole('button', { name: 'Configure API privileges' })\n```\n\n### Narrowing search scope\n\nScope selectors to specific containers to avoid matching wrong elements:\n\n```typescript\n// Good - scoped to side panel\nconst sidePanel = page.getByTestId('table-editor-side-panel')\nconst toggle = sidePanel.getByRole('switch')\n\n// Good - find unique element, then scope from there\nconst popover = page.locator('[data-radix-popper-content-wrapper]')\nconst roleSection = popover.getByText('Anonymous (anon)', { exact: true })\n```\n\n## Avoiding Race Conditions\n\n**Set up API waiters BEFORE triggering actions.** This is the most common source of flaky tests.\n\n```ts\n// ❌ Race condition — response may complete before waiter is set up\nawait page.getByRole('button', { name: 'Save' }).click()\nawait waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')\n\n// ✅ Waiter is ready before the action\nconst apiPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')\nawait page.getByRole('button', { name: 'Save' }).click()\nawait apiPromise\n```\n\nSame rule applies before navigation:\n\n```ts\nconst loadPromise = waitForTableToLoad(page, ref)\nawait page.goto(toUrl(`/project/${ref}/editor?schema=public`))\nawait loadPromise\n```\n\nWhen an action triggers multiple API calls, wait for all of them:\n\n```ts\nconst createTablePromise = waitForApiResponseWithTimeout(page, (r) =>\n  r.url().includes('query?key=table-create')\n)\nconst tablesPromise = waitForApiResponseWithTimeout(page, (r) =>\n  r.url().includes('tables?include_columns=true')\n)\n\nawait page.getByRole('button', { name: 'Save' }).click()\nawait Promise.all([createTablePromise, tablesPromise])\n```\n\n## Waiting Strategies\n\nPlaywright auto-waits for elements to be actionable — prefer this over manual timeouts.\n\nUse `expect.poll` for dynamic state changes:\n\n```ts\nawait expect.poll(async () => await page.getByLabel(`View ${tableName}`).count()).toBe(0)\n```\n\nUse `waitForSelector` with state for element lifecycle:\n\n```ts\nawait page.waitForSelector('[data-testid=\"side-panel\"]', { state: 'detached' })\n```\n\nAvoid `networkidle` — use specific API waits instead:\n\n```ts\n// ❌ Unreliable and slow\nawait page.waitForLoadState('networkidle')\n\n// ✅ Specific API response\nawait waitForApiResponse(page, 'pg-meta', ref, 'tables')\n```\n\nThe only acceptable use of `waitForTimeout` is a client-side debounce:\n\n```ts\nawait page.getByRole('textbox').fill('search term')\nawait page.waitForTimeout(300) // allow debounce\n```\n\n## Avoiding `waitForTimeout`\n\nNever use `waitForTimeout` to wait for UI or network — always wait for something specific (the debounce case above is the sole exception):\n\n```typescript\n// BAD\nawait page.waitForTimeout(1000)\n\n// GOOD - wait for UI element\nawait expect(page.getByText('Success')).toBeVisible()\n\n// GOOD - wait for API response\nconst apiPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=table-create')\nawait saveButton.click()\nawait apiPromise\n\n// GOOD - wait for toast indicating operation complete\nawait expect(page.getByText('Table created successfully')).toBeVisible({ timeout: 15000 })\n```\n\n## Avoiding `force: true` on clicks\n\nInstead of forcing clicks on hidden elements, make them visible first:\n\n```typescript\n// BAD\nawait menuButton.click({ force: true })\n\n// GOOD - hover to reveal, then click\nawait tableRow.hover()\nawait expect(menuButton).toBeVisible()\nawait menuButton.click()\n```\n\n## Test Structure\n\nAlways import from the custom test utility:\n\n```ts\nimport { test } from '../utils/test.js'\n```\n\nUse `withFileOnceSetup` for expensive setup that should run once per file:\n\n```ts\ntest.beforeAll(async ({ browser, ref }) => {\n  await withFileOnceSetup(import.meta.url, async () => {\n    const ctx = await browser.newContext()\n    const page = await ctx.newPage()\n    await deleteTestTables(page, ref)\n  })\n})\n\ntest.afterAll(async () => {\n  await releaseFileOnceCleanup(import.meta.url)\n})\n```\n\nDismiss toasts before interacting — they can overlay buttons:\n\n```ts\nconst dismissToastsIfAny = async (page: Page) => {\n  const closeButtons = page.getByRole('button', { name: 'Close toast' })\n  const count = await closeButtons.count()\n  for (let i = 0; i < count; i++) {\n    await closeButtons.nth(i).click()\n  }\n}\n\nawait dismissToastsIfAny(page)\nawait page.getByRole('button', { name: 'New table' }).click()\n```\n\n## Assertions\n\nAlways include descriptive messages for easier debugging:\n\n```ts\n// ❌ No context on failure\nawait expect(page.getByRole('button', { name: 'Save' })).toBeVisible()\n\n// ✅ Clear message on failure\nawait expect(\n  page.getByRole('button', { name: 'Save' }),\n  'Save button should be visible after form is filled'\n).toBeVisible()\n```\n\nUse explicit timeouts for slow operations:\n\n```ts\nawait expect(\n  page.getByText(`Table ${tableName} is good to go!`),\n  'Success toast should be visible after table creation'\n).toBeVisible({ timeout: 50000 })\n```\n\n## Helper Functions\n\nExtract reusable operations into domain helpers (e.g. `e2e/studio/utils/storage-helpers.ts`).\nUse the existing wait utilities:\n\n```ts\nimport {\n  createApiResponseWaiter,\n  waitForApiResponse,\n  waitForGridDataToLoad,\n  waitForTableToLoad,\n} from '../utils/wait-for-response.js'\n```\n\nUse `expectClipboardValue` instead of manual clipboard reads with hardcoded timeouts:\n\n```ts\n// ❌ Brittle\nawait page.evaluate(() => navigator.clipboard.readText())\nawait page.waitForTimeout(500)\n\n// ✅ Uses Playwright auto-retries\nawait expectClipboardValue({ page, value: 'expectedValue' })\n```\n\n## API Mocking\n\n```ts\nawait page.route('*/**/logs.all*', async (route) => {\n  await route.fulfill({ body: JSON.stringify(mockAPILogs) })\n})\n```\n\nUse soft waits for optional API calls:\n\n```ts\nawait waitForApiResponse(page, 'pg-meta', ref, 'optional-endpoint', {\n  soft: true,\n  fallbackWaitMs: 1000,\n})\n```\n\n## Cleanup\n\nClean up test data in `beforeAll`/`beforeEach`. Check before deleting to handle existing state gracefully:\n\n```ts\nconst bucketRow = page.getByRole('row').filter({ hasText: bucketName })\nif ((await bucketRow.count()) === 0) return\n// proceed with deletion\n```\n\nReset local storage after tests that modify it:\n\n```ts\nimport { resetLocalStorage } from '../utils/reset-local-storage.js'\n\nawait resetLocalStorage(page, ref)\n```\n\n## Debugging\n\n### View trace\n\n```bash\ncd e2e/studio && pnpm exec playwright show-trace <path-to-trace.zip>\n```\n\n### View HTML report\n\n```bash\ncd e2e/studio && pnpm exec playwright show-report\n```\n\n### Error context\n\nError context files are saved in the `test-results/` directory.\n\n### Playwright MCP tools\n\nUse Playwright MCP tools to inspect UI when debugging locally.\n\n## CI vs Local Development\n\nThe key difference is **cold start vs warm state**:\n\n### CI (cold start)\n\nTests run from a blank database slate. Each test run resets the database and starts fresh containers. Extensions like pg_cron are NOT enabled by default.\n\n### Local dev with `pnpm dev:studio-local`\n\nWhen debugging with a running dev server, the database may already have state from previous runs (extensions enabled, test data present).\n\n## Handling Cold Start Bugs\n\nTests that work locally but fail in CI often have assumptions about existing state.\n\n### Common issues\n\n1. Extension not enabled (must enable in test setup)\n2. Race conditions when parallel tests try to modify shared state (use `test.describe.configure({ mode: 'serial' })`)\n3. Locators matching wrong elements because the page structure differs when state isn't set up\n\n### Reproducing CI behavior locally\n\nThe test framework automatically resets the database when running `pnpm run e2e`. This matches CI behavior.\n\nIf using `pnpm dev:studio-local` for Playwright MCP debugging, remember the state differs from CI.\n\n## Debugging Workflow for CI Failures\n\n1. First, run the test locally with `pnpm run e2e -- features/<file>.spec.ts` (cold start)\n2. Check error context in `test-results/` directory\n3. If you need to inspect UI state, start `pnpm dev:studio-local` and use Playwright MCP tools\n4. Remember: what you see in the dev server may have state that doesn't exist in CI\n", "skills/studio-error-handling/SKILL.md": "---\nname: studio-error-handling\ndescription: Error display and troubleshooting pattern for Supabase Studio. Use when\n  showing a failed API request or query error in the UI (AlertError, toast, inline\n  message), adding troubleshooting steps for a new error type, or wiring up the AI\n  assistant debug button from an error state.\n---\n\n# Studio Error Handling Pattern\n\nFull docs and code examples: `apps/studio/components/interfaces/ErrorHandling/README.md`\n\n## How it works\n\nClassification happens in the **data layer**: `handleError` in `data/fetchers.ts` tests the error message against `ERROR_PATTERNS` and throws the matching tagged error (e.g. `ConnectionTimeoutError`, tag `DbConnectionTimeout`). The component (`ErrorMatcher`) looks up the mapping by the error's class — it never does regex matching.\n\n```\nhandleError() → throws ConnectionTimeoutError → React Query catches → ErrorMatcher looks up the class → renders troubleshooting\n```\n\nEvery error `handleError` throws is an Effect `Data.TaggedError` carrying `_tag`, `fault` (`user | platform | third_party | studio`), `reason`, `classifiedBy` (`rule | default`), `retryable` and `service`, alongside the legacy fields (`message`, `code`, `requestId`, …). Check for one with `isStudioError(e)` from `lib/errors/studio-errors`, never `instanceof`. `StudioError` is the union type of all Studio errors (type only); two classifiers in `data/error-classification.ts`, and `handleError` picks between them. `classifyResponseError({ message, code })` is only for errors from an API response (pattern match wins, else 5xx `PlatformError`, 4xx `UnclassifiedApiError`, no status `UnexpectedError`). `classifyError(e)` is for everything else (tagged passes through, abort `RequestAborted`, fetch failure `NetworkUnreachable`, otherwise `UnexpectedError`). Never pass a made-up status to `classifyResponseError`. SQL errors go through `classifySqlResponseError`: SQL the user wrote is `UserSqlError`; SQL Studio wrote is `StudioSqlError`, with reason `user_input` and fault `user` when the caller passed `isUserFaultSqlState` to `executeSql` and it accepts the SQLSTATE (`isUserFaultForValues` for typed values such as table editor filters and row edits; `isUserFaultForSql` for user-written SQL such as policy and function bodies; both in `data/error-classification.ts`, composable). The class decides privacy (`UserSqlError`, the user's own SQL, is never sent; `StudioSqlError` is sent with a redacted message), `ERROR_ROUTING` gives the rate for each tag and fault. `lib/errors/error-routing.ts` is a total tag-then-fault to `{ sentrySampleRate }` table (rates are the `SAMPLE_NEVER`/`SAMPLE_OTHER`/`SAMPLE_OWNED`/`SAMPLE_ALWAYS` constants, 0-1), and `getErrorRouting(error)` looks the entry up (a user fault that can still be reported gets `SAMPLE_USER_FAULT`, default 0.01). `reportStudioError` sends to Sentry at that rate (tagging `sample_rate`, applied in `beforeSend`, and `reason`) and sets `errorEventId`. Reporting happens in the QueryCache/MutationCache `onError` (`reportQueryError`) after the last retry, using the `sentryContext` and `alwaysCapture` that `handleError` remembered. A successful JSON `GET` that stays empty after recovery rejects from the fetch layer with `MalformedResponseError` (`normalizeEmptyBodyResponse`), so it never reaches `handleError`; the query cache reports it like any other thrown tagged error. Pass `reportImmediately: true` to `handleError` only for callers outside React Query (never reached by a query or mutation). See the README for details.\n\n## Key files\n\n| File                                  | Purpose                                                           |\n| ------------------------------------- | ----------------------------------------------------------------- |\n| `data/error-patterns.ts`              | Array of `{ pattern, ErrorClass }` — the regex lives here         |\n| `lib/errors/studio-errors.ts`         | Tagged error classes, `StudioError` (union type), `isStudioError` |\n| `data/error-classification.ts`        | `classifyResponseError`, `classifyError` (default rules)          |\n| `lib/errors/error-routing.ts`         | `ERROR_ROUTING` rate per tag and fault, `getErrorRouting` lookup  |\n| `ErrorMatcher.tsx`                    | Component — looks up the mapping by error class, renders          |\n| `error-mappings.tsx`                  | `Map<ErrorClass, { id, Troubleshooting: ComponentType }>`         |\n| `errorMappings/ConnectionTimeout.tsx` | Reference troubleshooting component                               |\n| `TroubleshootingSections.tsx`         | Reusable accordion section components                             |\n| `TroubleshootingAccordion.tsx`        | Accordion wrapper with telemetry                                  |\n\n## Which component\n\n| Situation                                                                                           | Use                                                                                                                      |\n| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |\n| A query failed and the page/section can't render its data (the default case — most of Studio)       | `AlertError` from `components/ui/AlertError`                                                                             |\n| The error may be a **classified** type with its own troubleshooting steps (e.g. connection timeout) | `ErrorMatcher` from `components/interfaces/ErrorHandling/ErrorMatcher` — pass a `fallback` for the unclassified case     |\n| A mutation failed                                                                                   | The mutation hook's default `onError` toast (`toast.error` from `sonner`) — don't render an alert (see `studio-queries`) |\n\n### `AlertError` (default)\n\nRenders a warning `Admonition` with the error message, generic \"try refreshing / contact support\" instructions, and a **contact support** link pre-filled with `projectRef`, `subject`, and the error message.\n\n```tsx\nif (isError) return <AlertError error={error} subject=\"Failed to retrieve invoices\" />\n```\n\n- `subject` is the human-readable title, phrased `Failed to <verb> <thing>`. Pass `projectRef` when in a project context so the support form is pre-filled.\n- `error` is the React Query error object (anything with `message`); `503` responses are reworded automatically.\n- When `error` is a Studio error (`isStudioError`), `AlertError` applies defaults by tag and fault from `getErrorPresentation` (`AlertError.utils.ts`), and props you pass still win. It shows the request ID, the Sentry event ID (labeled \"before sampling\") and a **Copy details** button next to `additionalActions`. Copied text (`formatErrorDetails`) never includes `formattedError`, `metadata`, `cause` or SQL, and has no message for SQL errors. An error with fault `user` (`isUserError`) shows its message with \"Please try again. If the issue persists, try refreshing your browser.\" and no support link, IDs or copy button; offline (`NetworkUnreachable`, reason `offline`) shows only a dedicated offline message.\n- Use `additionalActions` for a retry or navigate button; `hideContactSupport` only when support genuinely can't help and the error isn't already a user fault (those hide it automatically).\n- Prefer the early-return form for the page/section's primary data; use inline `{isError && <AlertError … />}` for secondary panels that shouldn't block the rest of the page.\n\n### `ErrorMatcher` (classified errors)\n\nUse when the data layer may have classified the error into a tagged class with dedicated troubleshooting UI. It looks up the error's class and renders the mapped `Troubleshooting` component, or `fallback` when there is no mapping. Today this is wired for the table editor sidebar; reach for it when adding troubleshooting for a new error type rather than as a general replacement for `AlertError`.\n\n## `ErrorMatcher` usage\n\nPass the **full error object** from React Query — not `error.message`:\n\n```tsx\n{\n  isError && (\n    <ErrorMatcher title=\"Failed to load tables\" error={error} supportFormParams={{ projectRef }} />\n  )\n}\n```\n\n## What NOT to do\n\n- Do not pass `error.message` to `ErrorMatcher` — pass the full `error` object so the class is preserved.\n- Do not put regex patterns in `error-mappings.tsx` — they belong in `data/error-patterns.ts`.\n- Do not use `Object.assign` to stamp a `_tag` onto an error — add a tagged class instead.\n- Do not pass a raw URL string for support — use `supportFormParams={{ projectRef }}`.\n- Do not put the page title inside the error mapping — it belongs on the `<ErrorMatcher>` caller.\n- Do not add callback props (`onDebugWithAI`, `onRestartProject`) to troubleshooting components — use hooks inside them instead.\n", "skills/studio-mock-api-tests/SKILL.md": "---\nname: studio-mock-api-tests\ndescription: Component tests for Supabase Studio that mock API requests at the\n  network layer with MSW. Use when writing or reviewing a component test that\n  exercises a React Query hook or mutation, or when migrating an existing\n  test away from vi.mock('@/data/...'). Covers the customRender + addAPIMock\n  template and the jsdom/MSW gotchas that cost real debugging time.\n---\n\n# Studio MSW component tests\n\nMount a Studio component, intercept its network calls with MSW, assert\nwhat renders and what gets sent. The infrastructure is already wired up —\nthis skill is the working template plus the gotchas.\n\n## When to use\n\n- The component (or any descendant it renders) calls a React Query hook\n  or mutation that hits `/platform/...`, `/v1/...`, or another endpoint\n  in `apps/studio/data/api.d.ts`.\n- You'd otherwise be tempted to write `vi.mock('@/data/some-query', ...)`.\n  **Don't.** Mock the network instead — see \"Why not vi.mock\" below.\n\nIf the component is purely presentational with no data fetching, you\ndon't need MSW; render and assert directly.\n\n## The template\n\n```tsx\nimport { screen } from '@testing-library/react'\nimport { platformComponents as components } from 'api-types'\nimport { mockAnimationsApi } from 'jsdom-testing-mocks'\nimport { HttpResponse } from 'msw'\nimport { describe, expect, test } from 'vitest'\n\nimport { MyComponent } from './MyComponent'\nimport { createMockOrganizationResponse } from '@/tests/helpers'\nimport { customRender } from '@/tests/lib/custom-render'\nimport { addAPIMock } from '@/tests/lib/msw'\n\ntype OrganizationResponse = components['schemas']['OrganizationResponse']\n\nmockAnimationsApi()\n\ndescribe('MyComponent', () => {\n  test('renders rows from the API', async () => {\n    addAPIMock({\n      method: 'get',\n      path: '/platform/organizations',\n      response: () =>\n        HttpResponse.json<OrganizationResponse[]>([\n          createMockOrganizationResponse({ name: 'Acme' }),\n        ]),\n    })\n\n    customRender(<MyComponent />)\n\n    expect(await screen.findByText('Acme')).toBeInTheDocument()\n  })\n})\n```\n\nUse `mockAnimationsApi()` when the component renders Radix UI that needs Web\nAnimations, such as a Sheet, Modal, or Popover. Add `fireEvent`, `waitFor`, or `userEvent` as the\ninteractions need them — see the gotchas below. Server lifecycle (`listen`/`resetHandlers`/\n`close`) is handled by `apps/studio/tests/vitestSetup.ts` — handlers\nregistered via `addAPIMock` are scoped to the current test.\n\n## Gotchas that will eat your afternoon\n\n### 1. Path params use `:slug`, not `{slug}`\n\n`addAPIMock` is typed from the OpenAPI `paths`, but path params are\nremapped to MSW's `:param` format. Autocomplete will guide you, but if\ntypecheck reports the path isn't assignable, you're using the OpenAPI\n`{slug}` form.\n\n```ts\n// ❌ TypeScript error, MSW won't match\npath: '/platform/organizations/{slug}/projects'\n\n// ✅ Correct\npath: '/platform/organizations/:slug/projects'\n```\n\n### 2. Use `HttpResponse.json`, not `new HttpResponse`\n\nFor success responses, always go through `HttpResponse.json` — even for\n204/201-no-content endpoints. A raw `new HttpResponse(null, { status: 201 })`\nreturns no content-type, and `openapi-fetch` can hang the mutation flow,\nwhich silently breaks `onSuccess` callbacks.\n\n```ts\n// ❌ Mutation onSuccess silently never fires\nresponse: () => new HttpResponse(null, { status: 201 })\n\n// ✅ Works (pass the OpenAPI body shape explicitly — see gotcha #8)\nresponse: () => HttpResponse.json<MyResponse>({}, { status: 201 })\n```\n\n### 3. Submit buttons in Sheets/Modals need `fireEvent.click`\n\nThe convention `<Button form={FORM_ID} type=\"submit\" />` (button\noutside the form, associated by id) doesn't reliably trigger submission\nunder `userEvent.click` in jsdom. Use `fireEvent.click` for the submit\nbutton. If that still doesn't submit, call\n`fireEvent.submit(document.getElementById(FORM_ID)!)` directly. Fill inputs\nwith `user.paste` rather than `user.type` (see \"Keep Tests Fast\" in\n`studio-testing`).\n\n```ts\nawait user.click(screen.getByPlaceholderText('value'))\nawait user.paste('hello')\nfireEvent.click(await screen.findByRole('button', { name: 'Save' }))\n```\n\n### 4. Profile-gated queries need a `profileContext`\n\nMany hooks (`useOrganizationsQuery`, anything in `data/projects/`,\nanything that calls `useProfile`) refuse to fire until a profile is\nloaded. Pass one explicitly:\n\n```ts\nimport type { ProfileContextType } from '@/lib/profile'\n\nconst PROFILE_CONTEXT: ProfileContextType = {\n  profile: {\n    id: 1,\n    auth0_id: 'auth0|test',\n    gotrue_id: 'gotrue-test',\n    username: 'testuser',\n    primary_email: 'test@example.com',\n    first_name: null,\n    last_name: null,\n    mobile: null,\n    is_alpha_user: false,\n    is_sso_user: false,\n    disabled_features: [],\n    free_project_limit: null,\n  },\n  error: null,\n  isLoading: false,\n  isError: false,\n  isSuccess: true,\n}\n\ncustomRender(<MyComponent />, { profileContext: PROFILE_CONTEXT })\n```\n\n### 5. `useParams` is globally mocked to `{ ref: 'default' }`\n\nYou don't need to mock the Next router for project-scoped components.\nJust use `'default'` as the project ref in your mock paths:\n`/v1/projects/default/secrets`, `/platform/projects/default/...`. If\nyou need a different ref, override with `routerMock.setCurrentUrl(...)`\n(see `apps/studio/tests/lib/route-mock.ts`).\n\n### 6. Unhandled requests fail loudly — mock every endpoint a render triggers\n\n`mswServer.listen({ onUnhandledRequest: 'error' })` is set globally. If a\ncomponent (or any child it renders) fires an unmocked request, you'll see\nMSW errors in stderr and likely flaky behavior. Cards, lists, and details\npanels often fire nested queries (e.g. `OrganizationCard` calls\n`useOrgProjectsInfiniteQuery`) — read what the rendered subtree does and\nmock those endpoints at the network boundary. Keep child components and hooks\nreal so the test exercises their integration. If a heavy dependency cannot run\nin jsdom, use an existing injection point with a faithful test implementation\nat its boundary, or extract the independently testable behavior. Do not replace\nthe child or shared hook with a module mock.\n\n### 7. Don't put query strings in the handler `path`\n\n`addAPIMock` accepts `?foo=bar` suffixes via `TrimQueryParams`, but the\nhelper strips them before matching. MSW v2 doesn't match query params via\npath strings — read them inside the resolver instead:\n\n```ts\naddAPIMock({\n  method: 'get',\n  path: '/platform/projects',\n  response: ({ request }) => {\n    const limit = new URL(request.url).searchParams.get('limit')\n    // ...\n  },\n})\n```\n\n### 8. Always pass an explicit generic to `HttpResponse.json`\n\n`addAPIMock`'s resolver is typed against the OpenAPI success body (and the\nstandard `{ message: string }` error envelope, exported as `APIErrorBody`).\nBut MSW's `HttpResponse.json` uses `NoInfer`, so the body type doesn't\nnarrow from context. Pass the expected shape explicitly — it doubles as a\nself-documenting contract assertion:\n\n```ts\nimport { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'\n\nresponse: () => HttpResponse.json<OrganizationResponse[]>([...])\nresponse: () =>\n  HttpResponse.json<APIErrorBody>({ message: 'Boom' }, { status: 500 })\n```\n\nA mock that drifts from the contract (wrong envelope, missing fields,\nstale enum values) now fails at compile time, not at runtime. The cost is\none type annotation per resolver — well worth it.\n\nFor mocks at the network boundary, also prefer `createMockOrganizationResponse`\n(returns the raw OpenAPI `OrganizationResponse`) over `createMockOrganization`\n(which extends with frontend-derived `managed_by` / `partner_id` that the\nquery layer attaches). Same pattern applies to any type that's a frontend\nextension of an OpenAPI schema: build a `createMockXResponse` helper that\nreturns the raw API shape.\n\n### 9. Mock FGA permissions with `mockPermissions`\n\nComponents that check permissions (`useGrant`, `useAsyncCheckPermissionsV2`)\nrequest `/platform/profile/permissions/v2`. There's no global default — mock it\nin each test that needs it:\n\n```ts\nimport { mockPermissions, mockPermissionsError } from '@/tests/lib/msw-permissions'\nimport { allPermissionsFor, NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'\n\nmockPermissions(allPermissionsFor(['my-org'])) // everything in my-org\nmockPermissions(NO_PERMISSIONS) // denied everywhere\nmockPermissions({ organizations: [{ slug: 'my-org', role: 'developer', permissions: [...], projects: [] }] })\nmockPermissionsError({ status: 500 }) // grant resolves to an error\n```\n\nUnit tests of fetchers or query options that take a grant can use\n`testGrant(endpoint, { projectRef })` from `@/tests/lib/test-grant` instead of\ngoing through permissions at all.\n\n## Prefer asserting on UI state\n\nMSW's own best-practices doc explicitly recommends asserting on what\nrenders, not on whether a handler was called. The \"did the form\nsubmit?\" question is best answered by `expect(onClose).toHaveBeenCalled()`\nor by `findByText('Saved')` — not by spying on the resolver.\n\nThere's one legitimate exception: **the request body itself is the\ncontract you care about**, and the server's reply doesn't reflect it\nback. Bulk-create endpoints (like `POST /v1/projects/:ref/secrets`) are\nthe canonical case — 201 with no body, so the only way to verify the\nshape sent is to capture it:\n\n```ts\nconst requests: Array<{ ref: string | undefined; body: unknown }> = []\naddAPIMock({\n  method: 'post',\n  path: '/v1/projects/:ref/secrets',\n  response: async ({ request, params }) => {\n    requests.push({ ref: params.ref as string | undefined, body: await request.json() })\n    return HttpResponse.json<CreateSecretsResponse>({}, { status: 201 })\n  },\n})\n\n// ... drive the UI ...\n\nexpect(requests).toEqual([{ ref: 'default', body: [{ name: 'API_KEY', value: 'new-value' }] }])\n```\n\nWhen in doubt, assert on the UI first; reach for request capture only\nwhen the UI doesn't observably encode the contract.\n\n## Debugging an MSW test\n\nIf a request isn't being matched, wire up MSW's lifecycle events at the\ntop of the test file (or temporarily in `msw.ts`):\n\n```ts\nimport { mswServer } from '@/tests/lib/msw'\n\nmswServer.events.on('request:unhandled', ({ request }) => {\n  console.log('[MSW] UNHANDLED:', request.method, request.url)\n})\nmswServer.events.on('response:mocked', ({ request, response }) => {\n  console.log('[MSW] MATCHED:', request.method, request.url, response.status)\n})\n```\n\n`request:start` is already wired in `msw.ts`. Add `request:unhandled` and\n`response:mocked` locally when a test misbehaves — usually surfaces a\npath-param mismatch or a nested query you forgot to mock.\n\n## Why not `vi.mock('@/data/...')`\n\nIt bypasses the network boundary, so:\n\n- It hides real bugs: a renamed query key or a changed request payload\n  passes the test, then breaks in production.\n- It doesn't exercise React Query's caching, retry, or invalidation\n  paths — `onMutate`, `onSuccess`, and `onError` callbacks won't run as\n  they do in real life. ([tkdodo.eu/blog/testing-react-query](https://tkdodo.eu/blog/testing-react-query))\n- It drifts independently from the OpenAPI types — handlers stay in sync,\n  module-level mocks don't.\n\nDo not add module mocks for non-network dependencies either. Use supported\nproviders and context for shared state, inject a faithful boundary implementation\nfor unavailable infrastructure, or extract logic behind a useful public contract.\nKeep the interactions under test real.\n\nThe existing global harness includes router and environment mocks. Use its\nsupported configuration instead of adding local replacements; this guidance does\nnot require migrating unrelated harness mocks as part of a focused test change.\n\n## Further reading\n\n- [TkDodo — Testing React Query](https://tkdodo.eu/blog/testing-react-query) —\n  canonical reference for the principles behind everything in this skill.\n- [MSW best practices: structuring handlers](https://mswjs.io/docs/best-practices/structuring-handlers/)\n  and [overriding network behavior](https://mswjs.io/docs/best-practices/network-behavior-overrides/) —\n  the baseline-handlers + per-test-`server.use()` pattern.\n- [MSW best practices: avoid request assertions](https://mswjs.io/docs/best-practices/avoid-request-assertions/) —\n  the source of the \"assert on UI state\" guidance above.\n\n## Codebase references\n\n| What                                                           | Where                                                                                                   |\n| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |\n| Query-only example (loading, error, success)                   | `apps/studio/components/interfaces/Organization/OrgNotFound.test.tsx`                                   |\n| Mutation example (form, payload assertion)                     | `apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EditSecretSheet.test.tsx`              |\n| SQL-via-pg-meta example (POST resolver branch on `query` body) | `apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx`       |\n| `addAPIMock` source                                            | `apps/studio/tests/lib/msw.ts`                                                                          |\n| `customRender` source                                          | `apps/studio/tests/lib/custom-render.tsx`                                                               |\n| Global handlers + lifecycle                                    | `apps/studio/tests/lib/msw-global-api-mocks.ts`, `apps/studio/tests/vitestSetup.ts`                     |\n| Permissions mocks + `testGrant`                                | `apps/studio/tests/lib/msw-permissions.ts`, `apps/studio/tests/lib/test-grant.ts`                       |\n| Related skills                                                 | `studio-testing` (when to write a component test at all), `studio-queries` (hook conventions), `vitest` |\n", "skills/studio-queries/SKILL.md": "---\nname: studio-queries\ndescription: React Query conventions for data fetching in Supabase Studio. Use when\n  writing or reviewing query hooks, mutation hooks, or query keys in apps/studio/data/\n  — including adding the first fetch or mutation for a new API endpoint or resource.\n  Covers queryOptions pattern, keys.ts structure, mutation hook template, and imperative\n  fetching.\n---\n\n# Studio Queries & Mutations (React Query)\n\nFollow the patterns in `apps/studio/data/`. Reference examples:\n\n- Query options: `apps/studio/data/table-editor/table-editor-query.ts`\n- Mutation hook: `apps/studio/data/edge-functions/edge-functions-update-mutation.ts`\n- Keys: `apps/studio/data/edge-functions/keys.ts`\n\n## Query Keys\n\nDefine a `keys.ts` per domain. Export `*Keys` helpers using array keys with `as const`. Never inline query keys in components.\n\n```ts\nexport const edgeFunctionsKeys = {\n  list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const,\n  detail: (projectRef: string | undefined, slug: string | undefined) =>\n    ['projects', projectRef, 'edge-function', slug, 'detail'] as const,\n}\n```\n\n## Query Options (preferred pattern)\n\nUse `queryOptions` from `@tanstack/react-query`. This gives type safety and works with both `useQuery()` and `queryClient.fetchQuery()`.\n\nRules:\n\n- Export `XVariables`, `XData`, and `XError` types (prefixed with the domain name)\n- Implement a **private** `getX(variables, signal?)` function:\n  - Throws if required variables are missing\n  - Passes `signal` for cancellation\n  - Calls `handleError(error)` on failure (which throws); returns `data` on success\n  - Not exported — use `queryClient.fetchQuery(xQueryOptions(...))` for imperative fetching\n- Export `xQueryOptions()` using `queryOptions`\n- Gate with `enabled` so the query doesn't run until required variables exist\n- Platform-only queries: include `IS_PLATFORM` from `lib/constants` in `enabled`\n- Don't add extra params to `xQueryOptions` — callers override by destructuring: `{ ...xQueryOptions(vars), enabled: true }`. Exception: grant-gated queries (see below)\n\n```ts\nimport { queryOptions } from '@tanstack/react-query'\n\nimport { xKeys } from './keys'\nimport { get, handleError } from '@/data/fetchers'\nimport { IS_PLATFORM } from '@/lib/constants'\nimport type { StudioError } from '@/lib/errors/studio-errors'\n\nexport type XVariables = { projectRef?: string }\nexport type XError = StudioError\n\nasync function getX({ projectRef }: XVariables, signal?: AbortSignal) {\n  if (!projectRef) throw new Error('projectRef is required')\n  const { data, error } = await get('/v1/projects/{ref}/x', {\n    params: { path: { ref: projectRef } },\n    signal,\n  })\n  if (error) handleError(error)\n  return data\n}\n\nexport type XData = Awaited<ReturnType<typeof getX>>\n\nexport const xQueryOptions = ({ projectRef }: XVariables) =>\n  queryOptions({\n    queryKey: xKeys.list(projectRef),\n    queryFn: ({ signal }) => getX({ projectRef }, signal),\n    enabled: IS_PLATFORM && typeof projectRef !== 'undefined',\n  })\n```\n\n## Grant-gated queries\n\nQuery options that take a `grant` (see `lib/grants.ts`) are an exception to the spread-and-override guidance. Build them with `grantedQueryOptions` from `@/data/granted-query-options`, and let callers pass their options as the **second argument**. Never spread them.\n\n```ts\nexport const xQueryOptions = <TData = XData>(\n  { projectRef, grant }: XVariables,\n  options?: GrantedQueryCallerOptions<XData, XError, TData, ReturnType<typeof xKeys.list>>\n) =>\n  grantedQueryOptions(\n    {\n      queryKey: xKeys.list(projectRef),\n      queryFn:\n        projectRef && grant ? ({ signal }) => getX({ projectRef, grant }, signal) : undefined,\n    },\n    options\n  )\n\n// Caller\nuseQuery(xQueryOptions({ projectRef, grant: xGrant.grant }, { select, enabled: open }))\n```\n\nWhy: TanStack keeps one options object per cache entry, overwritten by whichever observer rendered last, and invalidation refetches with it. A factory passes `queryFn: undefined` when a grant or required variable is missing; `grantedQueryOptions` forces `enabled: false` and substitutes a delegating placeholder `queryFn` (not `skipToken`, which would make invalidation fail with `Missing queryFn` if a grant-less observer rendered last, and not leaving `queryFn: undefined`, which triggers TanStack's dev-mode `No queryFn was passed` console error on every render). The helper owns `queryKey`, `queryFn`, and the `enabled` gate, so a caller can't override the grant check. `grantedQueryOptions` brands its return type (a type-only `__grantedQueryOptions` property), and the type-aware `fga/no-spread-granted-query-options` lint rule reports any object spread or `Object.assign` of a branded value, however it was obtained (variable, wrapper, renamed import).\n\n## Using Query Options in Components\n\n```ts\nimport { useQuery } from '@tanstack/react-query'\n\nimport { xQueryOptions } from '@/data/x/x-query'\n\nconst { data, isPending, isError } = useQuery(xQueryOptions({ projectRef: project?.ref }))\n```\n\n## Imperative Fetching (outside React or in callbacks)\n\n```ts\nconst queryClient = useQueryClient()\nconst { data: project } = useSelectedProjectQuery()\n\nconst handleClick = useCallback(\n  async (id: number) => {\n    const data = await queryClient.fetchQuery(xQueryOptions({ id, projectRef: project?.ref }))\n    // use data...\n  },\n  [project?.ref, queryClient]\n)\n```\n\n## Mutation Hook\n\n- Export a `Variables` type with `projectRef`, identifiers, and `payload`\n- Implement a private `updateX(vars)` function with required variable validation and `handleError`\n- Wrap in `useXMutation()`:\n  - Accepts `UseMutationOptions` (omit `mutationFn`)\n  - Invalidates `list()` + `detail()` keys in `onSuccess` with `await Promise.all([...])`\n  - Defaults to `toast.error(...)` when `onError` isn't provided\n\n```ts\nimport { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'\nimport { toast } from 'sonner'\n\nimport { xKeys } from './keys'\n\ntype XUpdateVariables = { projectRef: string; slug: string; payload: XPayload }\n\nexport const useXUpdateMutation = ({\n  onSuccess,\n  onError,\n  ...options\n}: UseMutationOptions<XData, XError, XUpdateVariables> = {}) => {\n  const queryClient = useQueryClient()\n  return useMutation({\n    mutationFn: updateX,\n    async onSuccess(data, variables, context) {\n      await Promise.all([\n        queryClient.invalidateQueries({\n          queryKey: xKeys.detail(variables.projectRef, variables.slug),\n        }),\n        queryClient.invalidateQueries({ queryKey: xKeys.list(variables.projectRef) }),\n      ])\n      await onSuccess?.(data, variables, context)\n    },\n    async onError(error, variables, context) {\n      if (onError === undefined) toast.error(`Failed to update: ${error.message}`)\n      else onError(error, variables, context)\n    },\n    ...options,\n  })\n}\n```\n\n## Component Usage\n\n- Use React Query v5 flags: `isPending` for initial load, `isFetching` for background refetches\n- Render states explicitly in order: pending → error → success\n", "skills/studio-shortcuts/SKILL.md": "---\nname: studio-shortcuts\ndescription: Keyboard shortcut conventions for Supabase Studio. Use when adding a\n  repeated user action, toolbar action, list/table operation, or sub-page navigation\n  that should have shortcut coverage, when registering or changing a shortcut, or when\n  adding a search/filter Input (which needs the staged-Escape handler). Covers the\n  shortcut registry, useShortcut, ShortcutTooltip/ShortcutBadge, the reference sheet,\n  and collision rules.\n---\n\n# Studio Keyboard Shortcuts\n\nWhen Studio UI changes introduce or materially alter repeated user actions, consider whether keyboard shortcut coverage should be added or updated. Shortcuts use the shared Studio shortcut system and must be discoverable from the visible UI.\n\n## Rules\n\n- Never add a one-off `keydown` listener for a normal Studio action — register it through the shortcut registry and `useShortcut`.\n- Every registered shortcut is exposed where the action is visible, via `ShortcutTooltip`, `ShortcutBadge`, or a command-menu badge.\n- `G then …` chords are reserved for navigation.\n- Avoid broad `Mod+letter` shortcuts that overlap common browser, editor, system, copy/save/search, or devtools behavior.\n- Before adding a shortcut, check the registry and any remaining non-registry listeners for collisions.\n- Every search/filter `<Input>` gets `onKeyDown={onSearchInputEscape(...)}` — see [Search inputs](#search-inputs).\n\n## Preferred pattern\n\n- Add definitions in `apps/studio/state/shortcuts/registry.ts` or `apps/studio/state/shortcuts/registry/*`.\n- Register with `useShortcut`.\n- Gate availability with `enabled`.\n- Surface visible actions with `ShortcutTooltip` or `ShortcutBadge`.\n- Prefer scoped, mnemonic sequential chords over global modifier chords.\n- Set `showInSettings: false` on contextual shortcuts (scoped to a specific page state, sheet, or panel).\n- When a shortcut group should appear in the reference sheet (`Shift+?`), add the group key to `SHORTCUT_REFERENCE_GROUP_ORDER` in `apps/studio/state/shortcuts/referenceGroups.ts` and a human label to `GROUP_LABELS` in `ShortcutsReferenceSheet.tsx`.\n- For sheet-scoped shortcuts (active only while a `<Sheet>` is open), mount `useShortcut` inside the sheet component gated by the `open` prop (`{ enabled: open }`) — `apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksDeliveryDetailsSheet.tsx` is the canonical example. A shortcut that _opens_ a sheet from anywhere is global instead, gated by whatever makes the action valid (e.g. `useConnectSheetShortcut` checks project health).\n\n## Search inputs\n\nEvery `<Input>` used as a search or filter field must include the staged-Escape handler from `apps/studio/lib/keyboard.ts`:\n\n```tsx\nimport { onSearchInputEscape } from '@/lib/keyboard'\n\n;<Input\n  value={query}\n  onChange={(e) => setQuery(e.target.value)}\n  onKeyDown={onSearchInputEscape(query, setQuery)}\n/>\n```\n\nBehavior:\n\n- **Escape while the input has a value** → clears the value, keeps focus (so a second Escape then blurs)\n- **Escape while the input is empty** → blurs the input\n- Stops propagation on Escape so the keystroke does not accidentally close a parent dialog or sheet\n\nWhen pairing with `useShortcut(LIST_PAGE_FOCUS_SEARCH, ...)` to focus a search input via keyboard, always also add `onSearchInputEscape` on the same input — focus and escape-to-blur are always a pair.\n\n## Key files\n\n`apps/studio/state/shortcuts/registry.ts`, `apps/studio/state/shortcuts/useShortcut.tsx`, `apps/studio/components/ui/Shortcut*.tsx`, `apps/studio/lib/keyboard.ts`.\n\n## Tests\n\nE2E tests for a feature with shortcuts cover both click interactions and the keyboard path — see `studio-e2e-tests`.\n", "skills/studio-testing/SKILL.md": "---\nname: studio-testing\ndescription: Testing strategy for Supabase Studio. Use when selecting, writing,\n  or reviewing tests, or extracting logic for testing. Covers meaningful unit,\n  component, and E2E coverage and scoped verification.\n---\n\n# Studio Testing Strategy\n\nProtect meaningful observable behavior and plausible regressions. Choose the\nfastest test that catches the failure; do not chase coverage percentages or\nexhaustive input permutations.\n\n## Choose coverage by behavior\n\nBefore adding a test, identify what would get worse for a user or caller if the\nbehavior broke. Read nearby tests first so new coverage fills a real gap.\n\n| Layer           | Use for                                                                                                        |\n| --------------- | -------------------------------------------------------------------------------------------------------------- |\n| Static analysis | Types, invalid imports, and other guarantees the compiler or linter already checks                             |\n| Unit tests      | Pure calculations, parsing, validation, permissions, and data transformations                                  |\n| Component tests | Rendered behavior and consequential interactions, including simple forms that submit, mutate data, or navigate |\n| E2E tests       | Critical user journeys and integration or environment differences that lower layers cannot establish           |\n\nExtract pure logic into a co-located `.utils.ts` when that clarifies the component\nand gives the logic a useful independent contract. Do not extract solely to avoid\ntesting the component's wiring. Utility tests commonly live under\n`apps/studio/tests/components/.../ComponentName.utils.test.ts`, mirroring the\nsource path; follow nearby conventions for co-located tests.\n\nCover expected usage, realistic failures, relevant boundaries, and known\nregressions. For a bug fix, reproduce the failure before fixing it. Respect\nbackend and API guarantees rather than inventing unsupported inputs. A change\nto prose, a constant, a re-export, pure markup, or a guarantee already established\nby static analysis does not need a new test merely because a file changed.\n\n## Assert observable outcomes\n\nTest what the end user sees and does, or the public contract a caller consumes.\nPrefer roles and labels to test IDs. Check visible text, disabled state,\nnavigation, public callbacks, or a meaningful request contract.\n\nDo not assert on internal state, refs, private methods, child-component render\nspies, hook calls inside components, CSS classes, DOM structure, or whole-tree\nsnapshots as proxies for behavior. A behavior-preserving refactor should not\nrequire changing assertions. Pure utility input/output tests remain valid when\nthey protect a public contract.\n\nReuse production definitions, representative inputs, and existing test factories\nbefore copying configuration or API fixtures. Keep expected outcomes independent:\ndo not calculate an expected result with the same helper being tested. Small\nexplicit inputs are useful when they make a calculation or boundary clear.\n\nRemove redundant cases when they catch the same failure. Use `test.each` for\ndistinct scenarios sharing a setup, not to multiply equivalent literals.\nPreserve distinct boundary, permission, security, error, and historical-data\ncoverage. If a brittle assertion is the only protection for a meaningful\nregression, replace it with an observable assertion before removing it.\n\n## Component and E2E integration\n\nUse `customRender` from `@/tests/lib/custom-render` for Studio providers. Mock\nAPI requests at the network boundary with `addAPIMock`, keeping real query and\nmutation behavior. Pass the OpenAPI body type to `HttpResponse.json<…>`:\n\n```tsx\nimport { screen } from '@testing-library/react'\nimport { platformComponents as components } from 'api-types'\nimport { HttpResponse } from 'msw'\n\nimport { customRender } from '@/tests/lib/custom-render'\nimport { addAPIMock } from '@/tests/lib/msw'\n\ntype OrganizationResponse = components['schemas']['OrganizationResponse']\n\naddAPIMock({\n  method: 'get',\n  path: '/platform/organizations',\n  response: () => HttpResponse.json<OrganizationResponse[]>([]),\n})\ncustomRender(<MyComponent />)\nexpect(await screen.findByText('No organizations')).toBeInTheDocument()\n```\n\nFollow [studio-mock-api-tests](../studio-mock-api-tests/SKILL.md) for the full\nMSW template, faithful boundary replacements, and harness requirements. Do not\nadd module mocks for queries, children, or shared hooks to bypass integration.\n\nA feature being shared by self-hosted and platform does not alone justify E2E\ncoverage. Use E2E for critical journeys or behavior that differs across those\nenvironments and cannot be established in a focused test. Cover mouse and\nkeyboard behavior where each protects the journey. Reuse interactions in\n`e2e/studio/utils/*-helpers.ts`, and clean up resources in `finally`. Follow\n[studio-e2e-tests](../studio-e2e-tests/SKILL.md) for execution.\n\n## Keep tests fast\n\nChoose the appropriate environment and avoid unnecessary work in interactions.\n\n### Put pure logic in `.test.ts` so it runs in node\n\n`vitest.config.ts` runs `**/*.test.ts` in the `node` environment and\n`**/*.test.tsx` in `jsdom`. jsdom costs ~1s of setup per file, so:\n\n- Utility, schema, and resolver tests: name the file `.test.ts` and don't\n  import anything from Testing Library.\n- Tests that need the DOM, including `renderHook` and `window.localStorage`:\n  use `.test.tsx` rather than adding an environment directive.\n- `.platform.test.tsx` files run with `NEXT_PUBLIC_IS_PLATFORM=true`.\n\nDOM setup files (`tests/setup/dom.ts`, `tests/setup/radix.js`) no-op in node.\n\n### Never wait on real time\n\nDon't sleep (`setTimeout(resolve, …)`), raise `findBy*` timeouts to wait out\na poll interval, or bump per-test timeouts. Use fake timers and advance\nthem. `shouldAdvanceTime: true` keeps `waitFor` polling, MSW, and router\nmicrotasks working:\n\n```tsx\nbeforeEach(() => {\n  vi.useFakeTimers({ shouldAdvanceTime: true })\n})\nafterEach(() => {\n  vi.useRealTimers()\n})\n\nconst advancePoll = () => act(() => vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS))\n\nawait advancePoll()\nexpect(await screen.findByText('Restoration complete!')).toBeInTheDocument()\n```\n\nThe same applies to debounces: `act(() => vi.advanceTimersByTimeAsync(650))`\ninstead of a 650ms sleep. Reuse the existing interval/debounce constant rather than duplicating its value.\n\n### Paste, don't type\n\n`user.type` fires keydown/keypress/input/keyup per character, and each one\ncan re-render a whole form. Unless keystroke-level behavior is what you're\ntesting (input masks, shortcuts, per-key validation), set the value in one go:\n\n```tsx\nawait user.click(input)\nawait user.paste('my-project')\n```\n\nA single `fireEvent.change` is also suitable when keyboard behavior is irrelevant.\nWhen using `userEvent` with fake timers, configure its `advanceTimers` option.\n\n### Scope `*ByRole` queries\n\n`*ByRole` checks accessibility (including `getComputedStyle`) for every\ncandidate element. Radix `Select` renders a hidden native `<option>` for\neach item, so an unscoped `findByRole('option')` on a large form checks\nhundreds of elements. Scope it to the open listbox:\n\n```tsx\nconst findOption = async (name: string | RegExp) =>\n  within(await screen.findByRole('listbox')).findByRole('option', { name })\n\nawait user.click(await findOption('East US'))\n```\n\n## Verify the affected behavior\n\n1. Run relevant existing unit and integration tests with retries disabled, even\n   when no new tests are needed for the executable change. Record the command\n   and result. An environment or dependency failure is a blocker, not a pass.\n2. When investigating order dependence or flakiness, repeat affected tests and\n   shuffle where supported, with retries disabled. Record reproducible seeds.\n   Fix shared state, timing, ordering, or cleanup rather than masking failures\n   with retries, longer timeouts, or skips.\n3. For new or changed assertions and regression-critical coverage, temporarily\n   introduce a realistic scoped production fault, such as omitting a side effect\n   or removing a guard. Confirm the relevant assertion fails for that behavior;\n   import errors, compile errors, timeouts, and infrastructure failures do not\n   count. Save the original bytes first and restore them in `finally` or an\n   equivalent guaranteed cleanup, preserving unrelated edits. Rerun the restored\n   code and check that no mutation remains.\n4. Check formatting and relevant types separately; passing Vitest does not prove\n   TypeScript correctness. Report checks actually run and any blocked evidence.\n\nUse focused existing tooling; do not add automated test machinery or mutation\nprobes for prose or static guarantees. For read-only reviews, report missing\nverification evidence without changing source or introducing mutations.\n\n## Codebase References\n\n| What                    | Where                                                                                                                                                                                     |\n| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Util test examples      | `apps/studio/tests/components/Grid/Grid.utils.test.ts`, `apps/studio/tests/components/Billing/TaxID.utils.test.ts`, `apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts` |\n| Component test examples | `apps/studio/tests/features/logs/LogsFilterPopover.test.tsx`, `apps/studio/tests/components/CopyButton.test.tsx`                                                                          |\n| Fake timers (polling)   | `apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx`                                                                                                                    |\n| Fake timers (debounce)  | `apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx`                                                                                                          |\n| Scoped listbox queries  | `apps/studio/tests/pages/new/[slug].test.tsx`, `apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx`                                           |\n| E2E test example        | `e2e/studio/features/filter-bar.spec.ts`                                                                                                                                                  |\n| E2E helpers pattern     | `e2e/studio/utils/filter-bar-helpers.ts`                                                                                                                                                  |\n| Custom render           | `apps/studio/tests/lib/custom-render.tsx`                                                                                                                                                 |\n| MSW mock setup          | `apps/studio/tests/lib/msw.ts` (`addAPIMock`)                                                                                                                                             |\n| Test README             | `apps/studio/tests/README.md`                                                                                                                                                             |\n| Vitest config           | `apps/studio/vitest.config.ts`                                                                                                                                                            |\n| Related skills          | `studio-e2e-tests` (running E2E), `vitest` (API reference), `vercel-composition-patterns` (component architecture)                                                                        |\n", "skills/studio-ui-patterns/SKILL.md": "---\nname: studio-ui-patterns\ndescription: Design system UI patterns for Supabase Studio. Use when building or updating\n  pages, forms, tables, charts, empty states, navigation, cards, alerts, or side panels\n  (sheets). Covers layout selection, component choice, and placement conventions.\n---\n\n# Studio UI Patterns\n\nThe Design System docs and demos are the source of truth. Always check the relevant\ndemo file before composing new UI.\n\n## Layout\n\nDocs: `apps/design-system/content/docs/ui-patterns/layout.mdx`\n\nBuild pages with `PageContainer`, `PageHeader`, and `PageSection`.\n\n| Content type      | `size`      |\n| ----------------- | ----------- |\n| Settings / config | `\"default\"` |\n| Lists / tables    | `\"large\"`   |\n| Full-screen views | `\"full\"`    |\n\n- If filters/search exist on a list page, align table actions with the filters (don't use `PageHeaderAside`/`PageSectionAside` for those actions)\n- If no filters, actions can go in `PageHeaderAside` or `PageSectionAside`\n\nDemos: `page-layout-settings.tsx`, `page-layout-list.tsx`, `page-layout-list-simple.tsx`, `page-layout-detail.tsx`\n(all in `apps/design-system/registry/default/example/`)\n\n## Forms\n\nDocs: `apps/design-system/content/docs/ui-patterns/forms.mdx`\n\n- Use `react-hook-form` + `zod`\n- Use `FormItemLayout` instead of manually composing `FormItem`/`FormLabel`/`FormMessage`/`FormDescription`\n- Wrap inputs with `FormControl`; import primitives from `ui`\n\nLayout selection:\n\n| Context                                    | Layout                                     | Container                                                  |\n| ------------------------------------------ | ------------------------------------------ | ---------------------------------------------------------- |\n| Page (settings/config)                     | `FormItemLayout layout=\"flex-row-reverse\"` | `Card` (`CardContent` per field; `CardFooter` for actions) |\n| Side panel — wide                          | `FormItemLayout layout=\"horizontal\"`       | `SheetSection`                                             |\n| Side panel — narrow (`size=\"sm\"` or below) | `FormItemLayout layout=\"vertical\"`         | `SheetSection`                                             |\n\nDirty state / submit:\n\n- Use `isDirty` to show Cancel and disable Save. Destructure it from `form.formState` only in the component that owns `useForm`; anywhere else subscribe with `useFormState({ control })` (see the `react-hook-form` skill)\n- Show loading on submit button via `loading` prop\n- If submit button is outside `<form>`, set a stable `formId` and use `form` prop on the button\n\nDemos: `form-patterns-pagelayout.tsx`, `form-patterns-sidepanel.tsx`\n\n## Tables\n\nDocs: `apps/design-system/content/docs/ui-patterns/tables.mdx`\n\n| Pattern    | Use when                                                                |\n| ---------- | ----------------------------------------------------------------------- |\n| `Table`    | Simple, static, semantic display                                        |\n| Data Table | TanStack-powered; sorting, filtering, pagination; composed per use-case |\n| Data Grid  | Virtualization, column resizing, or complex cell editing                |\n\n- Actions: above the table, aligned right\n- Search/filters: above the table, aligned left\n- If table is primary content with no filters, actions can live in the page's primary/secondary actions area\n\nDemos: `table-demo.tsx`, `data-table-demo.tsx`, `data-grid-demo.tsx`\n\n## Charts\n\nDocs: `apps/design-system/content/docs/ui-patterns/charts.mdx`\n\n- Use provided chart building blocks; avoid passing raw Recharts components to `ChartContent`\n- Use `useChart` context flags for loading/disabled states\n- Keep composition straightforward — avoid over-abstraction\n\nDemos (in `apps/design-system/registry/default/block/`): `chart-composed-demo.tsx`, `chart-composed-basic.tsx`, `chart-composed-states.tsx`, `chart-composed-metrics.tsx`, `chart-composed-actions.tsx`, `chart-composed-table.tsx`\n\n## Empty States\n\nDocs: `apps/design-system/content/docs/ui-patterns/empty-states.mdx`\n\n| Scenario                 | Pattern                                                             |\n| ------------------------ | ------------------------------------------------------------------- |\n| Initial / onboarding     | Presentational empty state with value prop + clear next action      |\n| Data-heavy lists         | Informational empty state matching the list/table layout            |\n| Zero results from search | Keep layout consistent with data state to avoid jarring transitions |\n| Missing route            | Centered `Admonition`                                               |\n\nDemos: `empty-state-presentational-icon.tsx`, `empty-state-initial-state-informational.tsx`, `empty-state-zero-items-table.tsx`, `data-grid-empty-state.tsx`, `empty-state-missing-route.tsx`\n\n## Navigation\n\nDocs: `apps/design-system/content/docs/ui-patterns/navigation.mdx`\n\n- Use `NavMenu` for a horizontal list of related views within a consistent page layout\n- Activating an item must trigger a **URL change** — no local-only tab state\n\nFor feature-flagged replacements in Studio, verify both states: off preserves existing navigation and destinations; on exposes the replacement. Treat intentionally hidden surfaces as explicit exceptions.\n\n## Cards\n\n- Group related information in cards\n- `CardContent` for sections, `CardFooter` for actions\n- Only use `CardHeader`/`CardTitle` when context isn't already provided by surrounding content\n- Use headers/titles when multiple cards represent distinct groups (e.g. multiple settings sections)\n\n## Alerts\n\n- Use `Admonition` to call out important actions, restrictions, or critical context\n- Place at the **top of a page's content** (below page title) or **top of the relevant section** (below section title)\n- Use sparingly\n\n## Sheets (Side Panels)\n\nUse a `Sheet` when switching pages would be disruptive and the user needs to maintain context (e.g. selecting a row from a list to edit).\n\nStructure:\n\n- `SheetContent` with `size=\"lg\"` for forms needing horizontal layout\n- Use `SheetHeader`, `SheetTitle`, `SheetSection`, `SheetFooter`\n- Submit/cancel actions go in `SheetFooter`\n\nForms in sheets:\n\n- `layout=\"horizontal\"` for wider sheets\n- `layout=\"vertical\"` for narrow sheets (`size=\"sm\"` or below)\n- When the sheet contains a form, wire dirty dismissal with `useConfirmOnClose` +\n  `DiscardChangesConfirmationDialog` (Cancel, Escape, and backdrop). Source of\n  truth: `apps/design-system/content/docs/ui-patterns/modality.mdx` (Dirty form\n  dismissal). Also see the react-hook-form skill for `isDirty` destructuring.\n\n## Copy\n\nSource of truth: `apps/design-system/content/docs/copywriting.mdx` — sentence case, title case, proper nouns, voice and tone.\n\nWhen changing visible copy, grep `e2e/studio/` for the old string.\n", "skills/telemetry-standards/SKILL.md": "---\nname: telemetry-standards\ndescription: PostHog event tracking standards for Supabase Studio. Use when adding\n  useTrack() calls, defining events in packages/common/telemetry-constants.ts,\n  implementing tracking for a new feature, or reviewing PRs for telemetry compliance.\n  Covers event naming, property conventions, privacy rules for event properties,\n  URL state and consent, approved patterns, and implementation guide.\n---\n\n# Telemetry Standards for Supabase Studio\n\nStandards for PostHog event tracking in `apps/studio/`. Apply these when\nreviewing PRs that touch tracking or when implementing new tracking.\n\n## Event Naming\n\n**Format:** `[object]_[verb]` in snake_case\n\n**Approved verbs only:**\nopened, clicked, submitted, created, removed, updated, evaluated, added,\nenabled, disabled, copied, exposed, failed, closed, completed, applied\n\nThis list is the authority. `packages/common/telemetry-constants.ts` still holds older events with other verbs, so don't take a verb from an existing event.\n\n`created` is for a new named resource, `added` for content put into an existing one. `evaluated` is for a decision the system made, not a user action.\n\n`clicked` and `submitted` name the user's action and fire in its handler. The other verbs name a result and fire once it has happened.\n\n**Flag these:**\n\n- Unapproved verbs (saved, viewed, seen, pressed, etc.)\n- Wrong order: `click_product_card` → should be `product_card_clicked`\n- Wrong casing: `productCardClicked` → should be `product_card_clicked`\n\n**Good examples:**\n\n- `product_card_clicked`\n- `backup_button_clicked`\n- `sql_query_submitted`\n\n**Common mistakes with corrections:**\n\n- `database_saved` → `save_button_clicked` or `database_updated` (unapproved verb)\n- `snippet_moved` → `snippet_folder_updated` (unapproved verb: a move updates where the item lives)\n- `click_backup_button` → `backup_button_clicked` (wrong order)\n- `dashboardViewed` → don't track passive views on page load\n- `component_rendered` → don't track — no user interaction\n\n## Property Standards\n\n**Casing:** camelCase preferred for new events. The codebase has existing snake_case properties (e.g., `schema_name`, `table_name`) — when adding properties to an existing event, match its established casing. Match casing only: don't copy these properties into new events, because they carry user-defined names (see [Privacy](#privacy-user-defined-names-and-identifiers)).\n\n**Names must be self-explanatory:**\n\n- `{ productType: 'database', planTier: 'pro' }`\n- `{ assistantType: 'sql', suggestionType: 'optimization' }`\n\n**Flag these:**\n\n- Generic names: `label`, `value`, `name`, `data`\n- PascalCase properties\n- Inconsistent names across similar events (e.g., `assistantType` in one event, `aiType` in a related event)\n- Mixing camelCase and snake_case within the same event\n- A name another event already sends with a different type. PostHog keeps one type per property name across the whole project, so values of another type can read as empty in insights. Generic names (`step`, `type`, `status`, `count`) collide most: search `packages/common/telemetry-constants.ts` for the name first\n\n## What NOT to Track\n\n- Passive views/renders on page load (`dashboard_viewed`, `sidebar_appeared`, `page_loaded`)\n- Component appearances without user interaction\n- Generic \"viewed\" or \"seen\" events — already captured by pageview events\n\n**DO track:** user clicks, form submissions, explicit opens/closes, user-initiated actions.\n\n**Exception:** `_exposed` events for A/B experiment exposure tracking are valid even though they fire on render.\n\n## Privacy: User-Defined Names and Identifiers\n\n**Never track PII** (emails, names, IPs, etc.) in event properties.\n\nEvent properties must also never contain anything a user chose or typed for their own project. These are customer data even though they are not PII, and sending them is outside our privacy policy. Mask or omit:\n\n- Schema, table, column, function, bucket, policy, project and branch names\n- Any other user-defined name or label (index, trigger, role, extension setting, edge function, secret key, and so on)\n- SQL text, filters, search terms, file or object paths, and other free-text input\n- Row, object or record IDs, and any ID or ref not already attached by `useTrack`\n- Raw error messages or stack traces, which often quote schema, table or column names. Send an error code or category instead\n\n`useTrack` attaches `groups.project` (project ref) and `groups.organization` (org slug) whenever a project or org is selected. Don't add these, or other IDs, as properties. To attribute an event to a different project or org (one that was just created, for example), pass it as the third argument to `track()`.\n\n**Send a count, enum, boolean or action category instead of the raw value.** Type new properties as string-literal unions or `boolean`/`number` rather than plain `string`, so a raw name is harder to pass by accident. Feature flag values are a separate case and follow the feature flag section below.\n\n```typescript\n// Don't (illustrative): raw names identify the customer's data model\ntrack('table_copied', { schemaName: 'billing_internal', tableName: 'invoices' })\n\n// Do (illustrative): categories, counts and booleans carry the same product insight\ntrack('database_schema_visualizer_copied', { content: 'table_sql' })\ntrack('database_schema_selector_updated', { schemaType: 'custom' }) // 'public' | 'protected' | 'custom'\ntrack('policy_created', { operation: 'select', hasCheckExpression: true })\n```\n\nIf you need to tell values apart, derive a category (`public` / `protected` / `custom`), a count (`tableCount`), or a boolean (`isDefaultSchema`). If a raw name seems essential, stop and ask before adding it.\n\nThis section takes precedence over \"match similar events\" guidance elsewhere in this skill: if a similar event carries a user-defined name, don't copy that property.\n\n## Privacy: Secrets, Project Content and URL State\n\nTelemetry only runs for visitors who accepted analytics. Consent does not make it acceptable to collect secrets or the data customers keep in their projects.\n\n**Also never send, in any property:**\n\n- Secrets: API keys, JWTs, access or refresh tokens, passwords, connection strings, invite or OAuth codes. Pasted input often contains them\n- Content read from a project: row values, log lines, query results, AI responses\n- Ids of a customer's end users, and phone numbers\n\n**Helpers that send the shape instead of the text:**\n\n- Search input: `describeSearchQuery` in `packages/common/search-query-telemetry.ts`\n- Errors: `useTrackFunnelError` in `apps/studio/lib/telemetry/use-track-funnel-error.ts`, which only accepts a classified reason from `funnel-errors.ts`\n\n**The page URL goes out with every event.** Pageviews and custom events carry the current URL and the referrer automatically, so URL state is telemetry:\n\n- Do not put tokens, user input or row values in the query string or hash of a route\n- If a feature needs URL state like that, redact it in `packages/common/telemetry-utils.ts` in the same PR and add a test\n\n## Consent and Transport\n\n- Send events only through `useTrack` (Studio) or the app's `useSendTelemetryEvent`, and pageviews through `PageTelemetry`. They check consent. Never import `posthog-js` outside `packages/common/posthog-client.ts` or post to an analytics endpoint directly\n- Don't add a direct `sendTelemetryEvent` call in Studio. `useStudioCommandMenuTelemetry` is the one caller besides `useTrack`: it forwards events the shared command menu has already built\n- Always pass the real consent state to `posthogClient` methods. Never rely on a parameter default\n- Do not write analytics cookies or storage (ids, attribution, experiment assignment) before the visitor accepts. Anything stored after consent must be cleared in `revokeTrackingConsent` (`packages/common/consent-state.ts`) when consent is withdrawn\n- A new third-party script, pixel or embed that receives visitor data needs a consent gate and a Legal review before it merges. Ask @supabase/growth-eng to route it\n- Nothing may be sent when `IS_PLATFORM` is false. Self-hosted Studio sends no telemetry\n\n## Required Pattern\n\nImport `useTrack` from `@/lib/telemetry/track` (within `apps/studio/`).\n\n```typescript\nimport { useTrack } from '@/lib/telemetry/track'\n\nconst MyComponent = () => {\n  const track = useTrack()\n\n  const handleClick = () => {\n    track('product_card_clicked', {\n      productType: 'database',\n      planTier: 'pro',\n      source: 'dashboard',\n    })\n  }\n\n  return <button onClick={handleClick}>Click me</button>\n}\n```\n\nWhere the `track()` call goes:\n\n- **`data-attr` is not tracking.** PostHog autocapture is off (`autocapture: false` in `packages/common/posthog-client.ts`), so the attribute sends nothing. A click you want measured gets a `track()` call. Keep any `data-attr` value a static string, never built from user-defined names, in case autocapture is enabled later.\n- **Mutation outcomes.** Don't track in the callbacks passed as the second argument to `mutate()` (`onSuccess`, `onError`): they are skipped if the component unmounts first. Track around `await mutateAsync()` (after it for success, in a `catch` for failure), or in the callbacks passed to the mutation hook itself (`useXMutation({ onSuccess, onError })`) when the hook always calls them: some return early, on a 202 for example. The selected project can change before the response arrives, so attribute the event to the mutation's own project or org (from its variables, or from the response for a create) with the third `track()` argument, for example `{ project: variables.projectRef }`.\n- **One meaning per event.** When one event name fires from several places, every call site fires on the same kind of user action, so the counts are comparable. Don't mix a `copy` event handler on a DOM element, which also fires on keyboard and partial-selection copies, with a Copy button's click callback under one event name: track the same action in both, or add a property that tells them apart.\n- **Submitted values.** Capture what the user submitted at submit time, not in the success callback. A form can stay editable while the request is in flight, so reading it on success can report a value that was not the one sent.\n- **Dismiss and abandonment events.** Every property must be able to take a different value at that call site. Read it from state that exists while the user is still in the flow, not from a result that is only set after success: otherwise every abandonment reports the same value. The success path (a Done button, for example) must not go through the dismiss handler, or each success also counts as an abandonment.\n- **Conditionally rendered elements.** A `track()` call on an element that renders only for some items (a link rendered only when the item has an `href`, for example) never fires for the others, and they read as zero. Track the same action on whatever the other items render in its place (a button instead of the link, for example). Don't move the call to a wider element such as the row: that counts clicks that were not on the link.\n- **Debounced or delayed sends.** `useTrack` reads the project, org and pathname when the event is sent, not when the user acted. An event sent from a debounce or timer that outlives a navigation is attributed to the destination page. Send on the action where possible. When the send has to wait, the third argument can pin the project or org, but the page cannot be overridden.\n- **Events sent just before leaving the page.** A request started right before a full-page navigation (an external link, an OAuth redirect) can be cancelled. Add the event's action to `KEEPALIVE_ACTIONS` in `packages/common/telemetry-event.ts`. Never turn keepalive on for every event: the browser's in-flight keepalive budget is small and shared, so other events would be dropped.\n- **Actions that change nothing.** An event named for a result (`closed`, `removed`, `updated`) fires only when the handler changed something. Bulk and menu actions can run on nothing: Close Others with one tab open, a move into the folder the items are already in, a sort set to its current value. Guard the `track()` call on the items that will change, not on the click. A count property reports the items that changed, not the items selected.\n\n## Feature Flag Measurement\n\nA feature flag that gates behavior needs telemetry on both the flag state and how users respond to the new behavior (toggle clicks, opt-in actions), so the rollout can be measured.\n\n- **PostHog flags** (`usePHFlag`, or PostHog-backed hooks such as `useDataApiRevokeOnCreateDefaultEnabled`): capture the flag value in a relevant `track()` call.\n- **ConfigCat flags** (`useFlag` from `common`) are a different system — this pattern does not apply to them.\n\n`usePHFlag` returns `undefined` while the PostHog store is still loading. Read the raw flag via `usePHFlag('flagName')`, **not** through wrapper hooks that coerce `undefined` to `false`, and use a conditional spread so the property is omitted (not `false`) until the flag has resolved:\n\nAs always, `track()` runs inside the user-action handler — never in the component body or an effect (experiment `_exposed` events excepted, see [What NOT to Track](#what-not-to-track)):\n\n```typescript\nconst track = useTrack()\nconst flagValue = usePHFlag<boolean>('myBooleanFlag') // for boolean flags\n\nconst handleSubmit = () => {\n  track('event_name', {\n    ...(flagValue !== undefined && { myFlagEnabled: flagValue }),\n  })\n}\n```\n\n**Experiment exposure.** Send `<experiment_id>_experiment_exposed` through `useTrack` with the `variant`, once per mount, and only once flags have loaded for the signed-in user (`hasFlagsForSignedInUser` from `useFeatureFlags()` in `packages/common/feature-flags.tsx`): the value held before that belongs to the logged-out visitor.\n\nFor string-valued flags (e.g. experiment variants), use `usePHFlag<string>('flagName')`; a flag that may be migrated from boolean to multivariate is typed `usePHFlag<boolean | string>`. `ProjectCreationForm.tsx` (`dataApiRevokeOnCreateDefault`) is the canonical example.\n\n## Event Definitions\n\nAll events must be defined as TypeScript interfaces in `packages/common/telemetry-constants.ts`:\n\n```typescript\n/**\n * [Event description]\n *\n * @group Events\n * @source [what triggers this event]\n */\nexport interface MyFeatureClickedEvent {\n  action: 'my_feature_clicked'\n  properties: {\n    /** Description of property */\n    featureType: 'basic' | 'advanced'\n  }\n  groups: TelemetryGroups\n}\n```\n\nAdd the new interface to the `TelemetryEvent` union type so `useTrack` picks it up.\n`@group Events` and `@source` are required on every event; add `@page` when the event fires from a specific page. All three must be accurate.\n\nAn event fired from an organization-level page (`/org/[slug]/...`) gets its own event name and `groups: Omit<TelemetryGroups, 'project'>` (see `organization_mfa_enforcement_updated`). Don't reuse a project-scoped event there: no project is selected, so `useTrack` sends it without the project group and the type does not catch it.\n\n## Review Rules\n\nWhen reviewing a PR, flag a break of any of these as a **required change**, even when the value looks harmless:\n\n1. **Naming**: [Event Naming](#event-naming)\n2. **Properties**: [Property Standards](#property-standards). Search `packages/common/telemetry-constants.ts` for similar events and check that property names match\n3. **Passive view tracking**: [What NOT to Track](#what-not-to-track)\n4. **Inaccurate docs**: `@source` or `@page` that doesn't match the implementation ([Event Definitions](#event-definitions))\n5. **Feature flags and experiment exposure**: [Feature Flag Measurement](#feature-flag-measurement)\n6. **User-defined names or identifiers in properties**: [Privacy: User-Defined Names and Identifiers](#privacy-user-defined-names-and-identifiers)\n7. **Secrets, project content, URL state or consent**: [Privacy: Secrets, Project Content and URL State](#privacy-secrets-project-content-and-url-state) and [Consent and Transport](#consent-and-transport)\n8. **Tracking placement**: the placement rules under [Required Pattern](#required-pattern)\n9. **Org-level events**: a project-scoped event reused on an organization-level page ([Event Definitions](#event-definitions))\n\nWhen a PR adds user-facing interactions (buttons, forms, toggles, modals) **without** tracking, suggest:\n\n- \"This adds a user interaction that may benefit from tracking.\"\n- Propose the event name following `[object]_[verb]` convention\n- Propose the `useTrack()` call with suggested properties\n\n## Well-Formed Event Examples\n\nFrom the actual codebase:\n\n```typescript\n// User copies a connection string\ntrack('connection_string_copied', {\n  connectionType: 'psql',\n  connectionMethod: 'transaction_pooler',\n  connectionTab: 'Connection String',\n})\n\n// User enables a feature preview\ntrack('feature_preview_enabled', {\n  feature: 'realtime_inspector',\n})\n\n// User clicks a banner CTA\ntrack('index_advisor_banner_dismiss_button_clicked')\n\n// Experiment exposure (fires on render — valid exception)\ntrack('home_new_experiment_exposed', {\n  variant: 'treatment',\n})\n```\n\n## Implementing New Tracking\n\nTo add tracking for a user action:\n\n1. **Name the event**: [Event Naming](#event-naming)\n2. **Choose properties**: [Property Standards](#property-standards) and both Privacy sections. Search `packages/common/telemetry-constants.ts` for similar events and match their property names and casing\n3. **Define the event**: [Event Definitions](#event-definitions)\n4. **Call `track()`**: [Required Pattern](#required-pattern), plus [Feature Flag Measurement](#feature-flag-measurement) when a flag gates the behavior\n5. **Verify**: in the browser network tab, the action sends one `telemetry/event` request with the expected properties, and the same action with nothing to change (nothing to close, the same value picked again, a cancelled confirmation) sends no result event. A `clicked` or `submitted` event for the click itself still fires\n", "skills/test-the-docs/SKILL.md": "---\nname: test-the-docs\ndescription: >-\n  Execute runnable docs snippets and examples inside a disposable Docker Compose\n  sandbox (runner container + local Supabase stack via `supabase start`). Use\n  after Draft or during Self-review when asked to test the docs, fact-check\n  CLI/SQL/code samples, or produce a verification report for a docs PR.\n  Complements review-the-docs build and review checks; does not replace them.\n---\n\n# Test the docs\n\nRuns procedural docs content **inside disposable containers**, not on the host shell and not against production. Produces a verification report for the PR body / self-review note.\n\nFor markdown rebuilds, example-app triage, and PR review, use [`review-the-docs`](../review-the-docs/SKILL.md). For Frame/Shape and cross-repo product lookup, use [`pm-the-docs`](../pm-the-docs/SKILL.md).\n\n## When to invoke\n\n- After Draft, before or during Self-review (checklist Stage 4).\n- Standalone: \"test the docs\", \"fact-check these snippets\", \"run the examples\".\n- Content or tutorial PRs that add or change procedural fenced blocks.\n\n**Not for:** generated reference pages, docs-app architecture questions, or hosted/production projects.\n\n## Core rules\n\n1. **Never run against production.** Local stack or temp dir only.\n2. **Never run MDX fences on the host shell.** Use the Compose sandbox — see [reference/sandbox-setup.md](reference/sandbox-setup.md) and [`sandbox/run.sh`](sandbox/run.sh).\n3. **Proportional:** Tier A (one end-to-end path) is required; Tier B spot-checks new/changed procedural blocks, not every fence on every page.\n4. **Product bugs** found while testing get linked or filed separately; fix docs only when the docs are wrong.\n\n## Phases\n\n### 1. Scope\n\nFrom explicit MDX paths, or:\n\n```bash\ngit diff --name-only master...HEAD -- 'apps/docs/content/**'\n```\n\nSkip generated reference output under `features/docs/generated/`.\n\n### 2. Extract\n\nList runnable artifacts from changed MDX:\n\n- Fenced blocks: `bash`, `sh`, `sql`, `javascript`, `typescript`, `tsx`, `jsx`\n- `$CodeSample` paths → treat as `example-app` (build under `examples/`)\n- Skip: `mermaid`, incomplete illustrative fragments, partial-only includes\n\n### 3. Classify\n\nAssign each artifact a class per [reference/snippet-classes.md](reference/snippet-classes.md):\n\n| Class                 | Action                                         |\n| --------------------- | ---------------------------------------------- |\n| `runnable-local`      | Run in temp stack / temp dir                   |\n| `runnable-with-setup` | Run after documented setup (migrations, seed)  |\n| `example-app`         | `npm install && npm run build` in `examples/…` |\n| `illustrative-only`   | No run required                                |\n| `deferred`            | Record reason; do not silently skip            |\n\n### 4. Sandbox setup\n\nFollow [reference/sandbox-setup.md](reference/sandbox-setup.md) and drive lifecycle with [`sandbox/run.sh`](sandbox/run.sh):\n\n1. Refuse if the **host** is running as root.\n2. Require `docker` + `docker info` + `docker compose` on the host for any in-container run.\n3. Gate profiles **per artifact class**:\n   - `runnable-local` / `runnable-with-setup` that need DB/API: `./sandbox/run.sh up-stack` (DinD + runner → `supabase init` / `supabase start` in `/work`).\n   - CLI-only blocks with no DB: still use a runner profile so fences stay off-host; skip `supabase start` when unused.\n   - `example-app`: `TTD_EXAMPLE_DIR=<repo>/examples/<app> ./sandbox/run.sh up-examples` (Node in runner; **no** DinD). Do **not** defer solely because the host lacks a global Supabase CLI.\n4. Always `./sandbox/run.sh down` when finished (cleanup trap on the host session).\n5. Capture connection **URLs only** inside the runner; never paste credential fields into notes or logs.\n\nIf a **required** prerequisite for that artifact is unavailable, mark that artifact `deferred` with the specific reason — never silent skip, and do not defer unrelated classes.\n\n### 5. Execute\n\n- **Tier A:** one copy-pasteable end-to-end path from the page.\n- **Tier B:** each new/changed block classified `runnable-*` **or** `example-app` (build and record the result).\n- Run every fence via `./sandbox/run.sh exec` or `exec-timeout` (never a bare host shell).\n- Bound every artifact: default **60s** for shell / SQL / JS / TypeScript / `tsx` / `jsx`; allow longer for `example-app` install/build (e.g. **5m**). On timeout, kill the process **group** inside the runner, then record `fail` or `deferred` with reason.\n- `curl` / `wget` only to filtered stack URLs (or page-documented local endpoints). `npm` / `npx` / `node` only for mounted `example-app` builds.\n- Capture exit code, stdout/stderr (redact secrets), and observed vs expected behavior.\n\n### 6. Report\n\nWrite a verification report per [reference/verification-report.md](reference/verification-report.md) for the PR body / self-review note.\n\n## Related skills\n\n- [`write-the-docs`](../write-the-docs/SKILL.md) — Draft; hands off here before PR\n- [`review-the-docs`](../review-the-docs/SKILL.md) — build/classify; consumes verification report\n- [`pm-the-docs`](../pm-the-docs/SKILL.md) — Frame/Shape; universe for cross-repo product lookup\n", "skills/test-the-docs/reference/sandbox-setup.md": "# Sandbox setup\n\nContainerized local execution for `/test-the-docs`. The **host** only starts Docker Compose and tears it down. Every MDX fence (shell, SQL, JS/TS, example-app builds) runs **inside** the disposable `runner` container — never as a host shell.\n\nAssets live in [`../sandbox/`](../sandbox/): `compose.yaml`, `Dockerfile`, `run.sh`.\n\n## Threat model and guardrails\n\n| Layer                  | What it does                                                                                                                                                                                                                                                                                                                             |\n| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Host                   | `docker compose` lifecycle only (`run.sh up-*` / `down`). No fence execution.                                                                                                                                                                                                                                                            |\n| Runner container       | Executes fences as non-root `runner` (uid 1001). No `$HOME` mount. Work dir is `/work`; optional read-only `/examples`.                                                                                                                                                                                                                  |\n| DinD (`stack` profile) | Privileged `docker:dind` runs an isolated Docker daemon. `supabase start` creates stack containers **inside DinD**. The runner shares DinD’s network namespace (`network_mode: service:dind`) so `127.0.0.1` healthchecks and client URLs work. Residual risk: privileged DinD; mitigate with ephemeral project names and `run.sh down`. |\n| Examples profile       | No DinD and no docker.sock — Node-only builds.                                                                                                                                                                                                                                                                                           |\n\nThis skill is for docs authors and reviewers verifying intended content. It is not unattended CI over arbitrary hostile input.\n\nGuardrails:\n\n- **Fences in-container only.** Never run MDX fences on the host shell. Use `./sandbox/run.sh exec` or `exec-timeout`.\n- **Local stack only.** Reject snippets that target hosted or production Supabase projects.\n- **No secrets in notes.** Never paste `PUBLISHABLE_KEY`, `SECRET_KEY`, `JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY`, `S3_PROTOCOL_ACCESS_KEY_ID`, `S3_PROTOCOL_ACCESS_KEY_SECRET`, or other keys into the verification report, PR body, or chat logs. Capture **URLs only** from `supabase status -o env`.\n- **`curl` / `wget`.** Only to URLs from the filtered status capture (`API_URL`, `DB_URL`, `DATABASE_URL`), or to local endpoints the page under test documents. Mark other targets `deferred`.\n- **`npm` / `npx` / `node`.** Only for `example-app` artifacts. Mount the app read-only at `/examples`, copy into `/work/example`, then `npm install && npm run build` (or the page’s documented build). Arbitrary `node -e`, remote `npx`, or Node from unrelated bash fences → `deferred`.\n- **Prefer page commands.** Run documented steps from the MDX under test.\n- **Fail closed** when Docker/Compose prerequisites for that artifact class are missing (see skill Phase 4).\n\n## Host prerequisites (fail closed)\n\n```bash\nif [[ \"$(id -u)\" = \"0\" ]]; then\n  echo \"error: refuse to run as root\" >&2\n  exit 1\nfi\ncommand -v docker >/dev/null || { echo \"error: docker not found\" >&2; exit 1; }\ndocker info >/dev/null 2>&1 || { echo \"error: Docker is not running\" >&2; exit 1; }\ndocker compose version >/dev/null || { echo \"error: docker compose not available\" >&2; exit 1; }\n```\n\nThe host does **not** need a global `supabase` CLI or Node for stack/example runs; those tools live in the runner image. If Docker/Compose is unavailable, mark artifacts that need the runner `deferred`.\n\n`run.sh` creates temp work/output dirs world-writable (`chmod 0777`) so the non-root runner (`uid 1001`) can write into the host bind mounts.\n\n## Lifecycle (`run.sh`)\n\nFrom `.agents/skills/test-the-docs/sandbox/`:\n\n```bash\n# Optional: pin dirs / project name for the session\neval \"$(./run.sh env)\"\n\n# Stack profile: DinD + runner → supabase init/start inside /work\n./run.sh up-stack\n\n# Capture URLs only inside the runner (never log credential fields)\n./run.sh exec -- bash -lc '\n  eval \"$(supabase status -o env | grep -E \"^(API_URL|DB_URL|DATABASE_URL)=\")\"\n  echo \"API_URL is set (value omitted from logs)\"\n'\n\n# Run a fence with a deadline (process group killed on timeout)\n./run.sh exec-timeout 60 -- bash -lc 'eval \"$(supabase status -o env | grep -E \"^(API_URL|DB_URL|DATABASE_URL)=\")\"; psql \"$DB_URL\" -c \"select 1\"'\n\n# Examples profile (no DinD): mount the app, then build\nTTD_EXAMPLE_DIR=/path/to/repo/examples/auth/hono ./run.sh up-examples\n./run.sh exec-timeout 300 -- bash -lc 'cd /work/example && npm install && npm run build'\n\n# Always tear down\n./run.sh down\n```\n\n## Profiles\n\n| Profile    | Services                | Isolation                        | Use when                                      |\n| ---------- | ----------------------- | -------------------------------- | --------------------------------------------- |\n| `stack`    | `dind` + `runner-stack` | Privileged DinD; fences off-host | SQL, CLI, client calls against local Supabase |\n| `examples` | `runner`                | No Docker daemon in-sandbox      | `example-app` install/build only              |\n\nDo not start the stack unless the artifact needs it.\n\n## Teardown\n\nAlways `./run.sh down` (stops `supabase` project containers when possible, `compose down -v`, removes temp work/output dirs). Leave Docker Desktop running for the next session.\n", "skills/test-the-docs/reference/snippet-classes.md": "# Snippet classes\n\nClassify each extracted artifact before running it.\n\n| Class                 | Meaning                                                                          | Run?                                   |\n| --------------------- | -------------------------------------------------------------------------------- | -------------------------------------- |\n| `runnable-local`      | Complete CLI, SQL, or script that works against a local stack or temp dir        | Yes                                    |\n| `runnable-with-setup` | Needs migrations, seed data, `.env`, or prior steps from the same page           | Yes, after setup                       |\n| `example-app`         | `$CodeSample` or path under `examples/`                                          | Build (`npm install && npm run build`) |\n| `illustrative-only`   | Incomplete on purpose, omits required context, or is conceptual                  | No                                     |\n| `deferred`            | Needs production, paid feature, destructive op, or missing required prerequisite | No — record reason                     |\n\n## Safety\n\n- Prefer read-only SQL and non-destructive CLI flags.\n- Never target a linked hosted/production project from this skill.\n- Do not print secrets (service role keys, PATs) into Verification notes or logs.\n- Mark incomplete copy-paste blocks `illustrative-only` rather than forcing a run that cannot succeed.\n- Execute fences only inside the Compose runner per [sandbox-setup.md](sandbox-setup.md). Restrict `curl`/`wget` to filtered stack URLs; restrict `npm`/`npx`/`node` to `example-app` mounts. Mark out-of-policy fences `deferred`.\n\n## Language heuristics\n\n| Fence                                       | Typical class                                                               |\n| ------------------------------------------- | --------------------------------------------------------------------------- |\n| `sql`                                       | `runnable-local` or `runnable-with-setup` if ordered migrations             |\n| `bash` / `sh`                               | `runnable-local` if self-contained; else `deferred` / `illustrative-only`   |\n| `javascript` / `typescript` / `tsx` / `jsx` | Often `illustrative-only` unless a full runnable script or example-app path |\n| `mermaid`                                   | Skip (not executable)                                                       |\n", "skills/test-the-docs/reference/verification-report.md": "# Verification report\n\nPaste into the PR body or self-review note under a **Verification** heading.\n\n## Template\n\n```markdown\n## Verification (`/test-the-docs`)\n\n| Snippet / step                | Class          | Sandbox                           | Result   | Notes                    |\n| ----------------------------- | -------------- | --------------------------------- | -------- | ------------------------ |\n| e.g. `create type …` SQL      | runnable-local | Compose runner + `supabase start` | pass     |                          |\n| e.g. `supabase db diff`       | runnable-local | Compose runner + local stack      | fail     | product bug → link issue |\n| e.g. paid Dashboard-only step | deferred       | —                                 | deferred | needs hosted project     |\n\n**Tier A path:** <one-line description of the end-to-end path run>\n\n**Environment:** Docker Desktop <version if known>; compose sandbox (`sandbox/run.sh`); fences in-container only\n```\n\nDo **not** put secrets (`JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY`, access tokens) in Notes or Environment.\n\n## Results\n\n| Result     | Meaning                                                              |\n| ---------- | -------------------------------------------------------------------- |\n| `pass`     | Command exited 0 and matched expected behavior                       |\n| `fail`     | Ran but wrong output / non-zero exit — docs wrong **or** product bug |\n| `deferred` | Not run; reason required in Notes                                    |\n| `skipped`  | Out of scope (`illustrative-only`)                                   |\n\n## Product bugs\n\nIf the snippet matches the code and still fails:\n\n1. Prefer linking an existing issue in the owning repo.\n2. Otherwise note the repro in the PR and file/follow up with the product owner.\n3. Do not \"fix\" the docs to hide a real platform bug without calling it out.\n", "skills/test-the-docs/sandbox/Dockerfile": "# Runner for /test-the-docs: executes MDX fences inside the container.\nFROM node:26-bookworm-slim\n\nARG TARGETARCH\nARG SUPABASE_CLI_VERSION=2.39.2\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n      ca-certificates \\\n      curl \\\n      postgresql-client \\\n    && rm -rf /var/lib/apt/lists/*\n\n# Docker CLI only (daemon is DinD over TCP for stack profile)\nCOPY --from=docker:27-cli /usr/local/bin/docker /usr/local/bin/docker\n\nRUN set -eux; \\\n    arch=\"${TARGETARCH}\"; \\\n    case \"${arch}\" in \\\n      amd64) cli_arch=amd64 ;; \\\n      arm64) cli_arch=arm64 ;; \\\n      *) cli_arch=amd64 ;; \\\n    esac; \\\n    curl -fsSL \"https://github.com/supabase/cli/releases/download/v${SUPABASE_CLI_VERSION}/supabase_linux_${cli_arch}.tar.gz\" \\\n      | tar -xz -C /usr/local/bin supabase; \\\n    chmod +x /usr/local/bin/supabase; \\\n    supabase --version\n\nRUN useradd --create-home --uid 1001 --shell /bin/bash runner \\\n    && mkdir -p /work /output /examples \\\n    && chown -R runner:runner /work /output /examples\n\nUSER runner\nWORKDIR /work\nCMD [\"bash\"]\n", "skills/test-the-docs/sandbox/compose.yaml": "# Disposable compose project for /test-the-docs.\n# Host only starts/stops this project; MDX fences run inside the runner.\n#\n# Profiles:\n#   stack    — privileged DinD + runner sharing DinD network (supabase start uses 127.0.0.1)\n#   examples — runner only; copies /examples into /work/example for npm install (no DinD)\n\nservices:\n  dind:\n    image: docker:27-dind\n    privileged: true\n    environment:\n      DOCKER_TLS_CERTDIR: ''\n    command: ['dockerd', '--host=tcp://0.0.0.0:2375', '--host=unix:///var/run/docker.sock']\n    healthcheck:\n      test: ['CMD', 'docker', 'info']\n      interval: 2s\n      timeout: 5s\n      retries: 30\n      start_period: 5s\n    profiles:\n      - stack\n\n  runner:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    working_dir: /work\n    user: '1001:1001'\n    environment:\n      TTD_IN_CONTAINER: '1'\n    command: ['sleep', 'infinity']\n    volumes:\n      - type: bind\n        source: ${TTD_WORK_DIR:?set TTD_WORK_DIR}\n        target: /work\n      - type: bind\n        source: ${TTD_OUTPUT_DIR:?set TTD_OUTPUT_DIR}\n        target: /output\n      - type: bind\n        source: ${TTD_EXAMPLE_DIR:-./.empty}\n        target: /examples\n        read_only: true\n    networks:\n      - ttd\n    profiles:\n      - examples\n\n  runner-stack:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    working_dir: /work\n    user: '1001:1001'\n    # Share DinD's network namespace so supabase healthchecks on 127.0.0.1 succeed\n    network_mode: 'service:dind'\n    environment:\n      TTD_IN_CONTAINER: '1'\n      DOCKER_HOST: tcp://127.0.0.1:2375\n    command: ['sleep', 'infinity']\n    volumes:\n      - type: bind\n        source: ${TTD_WORK_DIR:?set TTD_WORK_DIR}\n        target: /work\n      - type: bind\n        source: ${TTD_OUTPUT_DIR:?set TTD_OUTPUT_DIR}\n        target: /output\n      - type: bind\n        source: ${TTD_EXAMPLE_DIR:-./.empty}\n        target: /examples\n        read_only: true\n    depends_on:\n      dind:\n        condition: service_healthy\n    profiles:\n      - stack\n\nnetworks:\n  ttd:\n    driver: bridge\n    name: ${TTD_NETWORK_NAME:-ttd-sandbox}\n", "skills/test-the-docs/sandbox/run.sh": "#!/usr/bin/env bash\n# Host-side lifecycle for /test-the-docs sandbox.\n# Starts a disposable compose project and execs fences inside the runner container.\n# Usage:\n#   eval \"$(./run.sh env)\"           # export TTD_* for the session\n#   ./run.sh up-stack                # DinD + runner; supabase init/start in /work\n#   ./run.sh up-examples             # runner only (no DinD); example-app builds in /work/example\n#   ./run.sh exec -- <cmd...>        # run a command in the active runner\n#   ./run.sh exec-timeout 60 -- <cmd...>\n#   ./run.sh down                    # compose down -v and remove work/output dirs created by this script\nset -euo pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nCOMPOSE_FILE=\"${SCRIPT_DIR}/compose.yaml\"\n\ndie() {\n  echo \"error: $*\" >&2\n  exit 1\n}\n\nrequire_host_prereqs() {\n  if [[ \"$(id -u)\" = \"0\" ]]; then\n    die \"refuse to run as root on the host\"\n  fi\n  command -v docker >/dev/null || die \"docker not found — install Docker Desktop\"\n  docker info >/dev/null 2>&1 || die \"Docker is not running — start Docker Desktop\"\n  docker compose version >/dev/null 2>&1 || die \"docker compose not available\"\n}\n\ncompose() {\n  docker compose -p \"${TTD_PROJECT_NAME}\" -f \"${COMPOSE_FILE}\" \"$@\"\n}\n\nrunner_service() {\n  case \"${TTD_PROFILE:-}\" in\n    stack) echo runner-stack ;;\n    examples) echo runner ;;\n    *) die \"TTD_PROFILE unset; run up-stack or up-examples first\" ;;\n  esac\n}\n\nensure_state_dir() {\n  mkdir -p \"${SCRIPT_DIR}/.state\"\n}\n\nwrite_env_file() {\n  ensure_state_dir\n  cat >\"${SCRIPT_DIR}/.state/current.env\" <<EOF\nexport TTD_PROJECT_NAME=$(printf '%q' \"${TTD_PROJECT_NAME}\")\nexport TTD_WORK_DIR=$(printf '%q' \"${TTD_WORK_DIR}\")\nexport TTD_OUTPUT_DIR=$(printf '%q' \"${TTD_OUTPUT_DIR}\")\nexport TTD_EXAMPLE_DIR=$(printf '%q' \"${TTD_EXAMPLE_DIR}\")\nexport TTD_NETWORK_NAME=$(printf '%q' \"${TTD_NETWORK_NAME}\")\nexport TTD_PROFILE=$(printf '%q' \"${TTD_PROFILE}\")\nEOF\n}\n\nload_env_file() {\n  [[ -f \"${SCRIPT_DIR}/.state/current.env\" ]] || die \"no active sandbox; run up-stack or up-examples first\"\n  # shellcheck disable=SC1091\n  source \"${SCRIPT_DIR}/.state/current.env\"\n}\n\ncmd_env() {\n  require_host_prereqs\n  local stamp project work output\n  stamp=\"$(date +%Y%m%d%H%M%S)-$$\"\n  project=\"ttd-${stamp}\"\n  work=\"$(mktemp -d \"${TMPDIR:-/tmp}/ttd-work.XXXXXX\")\"\n  output=\"$(mktemp -d \"${TMPDIR:-/tmp}/ttd-out.XXXXXX\")\"\n  # World-writable so compose user 1001:1001 can write into host bind mounts\n  chmod 0777 \"${work}\" \"${output}\"\n  cat <<EOF\nexport TTD_PROJECT_NAME=$(printf '%q' \"${project}\")\nexport TTD_WORK_DIR=$(printf '%q' \"${work}\")\nexport TTD_OUTPUT_DIR=$(printf '%q' \"${output}\")\nexport TTD_EXAMPLE_DIR=$(printf '%q' \"${TTD_EXAMPLE_DIR:-${SCRIPT_DIR}/.empty}\")\nexport TTD_NETWORK_NAME=$(printf '%q' \"${project}-net\")\nEOF\n}\n\nprepare_exports() {\n  require_host_prereqs\n  if [[ -z \"${TTD_PROJECT_NAME:-}\" || -z \"${TTD_WORK_DIR:-}\" || -z \"${TTD_OUTPUT_DIR:-}\" ]]; then\n    eval \"$(cmd_env)\"\n  fi\n  export TTD_EXAMPLE_DIR=\"${TTD_EXAMPLE_DIR:-${SCRIPT_DIR}/.empty}\"\n  export TTD_NETWORK_NAME=\"${TTD_NETWORK_NAME:-${TTD_PROJECT_NAME}-net}\"\n  mkdir -p \"${TTD_WORK_DIR}\" \"${TTD_OUTPUT_DIR}\"\n  # Re-apply in case dirs were pre-created without cmd_env chmod\n  chmod 0777 \"${TTD_WORK_DIR}\" \"${TTD_OUTPUT_DIR}\"\n}\n\ncmd_up_stack() {\n  prepare_exports\n  export TTD_PROFILE=stack\n  write_env_file\n  compose --profile stack build runner-stack\n  compose --profile stack up -d --remove-orphans dind runner-stack\n  # Wait until the runner can talk to DinD\n  compose --profile stack exec -T runner-stack bash -lc '\n    set -euo pipefail\n    for i in $(seq 1 60); do\n      if docker info >/dev/null 2>&1; then\n        break\n      fi\n      sleep 1\n    done\n    docker info >/dev/null\n    cd /work\n    if [[ ! -f supabase/config.toml ]]; then\n      printf 'n\\nn\\n' | supabase init\n    fi\n    supabase start\n  '\n  echo \"sandbox ready: project=${TTD_PROJECT_NAME} work=${TTD_WORK_DIR} profile=stack (DinD)\" >&2\n}\n\ncmd_up_examples() {\n  prepare_exports\n  export TTD_PROFILE=examples\n  write_env_file\n  compose --profile examples build runner\n  compose --profile examples up -d --remove-orphans runner\n  # Copy read-only mount into writable /work so npm can install without mutating the repo\n  compose --profile examples exec -T runner \\\n    bash -lc 'rm -rf /work/example && mkdir -p /work/example && cp -a /examples/. /work/example/'\n  echo \"sandbox ready: project=${TTD_PROJECT_NAME} work=${TTD_WORK_DIR} profile=examples (build in /work/example)\" >&2\n}\n\ncmd_exec() {\n  load_env_file\n  local svc\n  svc=\"$(runner_service)\"\n  compose --profile \"${TTD_PROFILE}\" exec -T \"${svc}\" \"$@\"\n}\n\ncmd_exec_timeout() {\n  load_env_file\n  local secs=\"$1\"\n  shift\n  if [[ \"${1:-}\" == \"--\" ]]; then\n    shift\n  fi\n  local svc\n  svc=\"$(runner_service)\"\n  compose --profile \"${TTD_PROFILE}\" exec -T \"${svc}\" \\\n    timeout --foreground --signal=TERM --kill-after=5s \"${secs}s\" \"$@\"\n}\n\ncmd_down() {\n  if [[ -f \"${SCRIPT_DIR}/.state/current.env\" ]]; then\n    # shellcheck disable=SC1091\n    source \"${SCRIPT_DIR}/.state/current.env\"\n  else\n    die \"no active sandbox state\"\n  fi\n  if [[ \"${TTD_PROFILE:-}\" == \"stack\" ]]; then\n    compose --profile stack exec -T runner-stack bash -lc 'cd /work && supabase stop 2>/dev/null || true' 2>/dev/null || true\n  fi\n  compose --profile \"${TTD_PROFILE:-stack}\" down -v --remove-orphans 2>/dev/null || true\n  rm -rf \"${TTD_WORK_DIR:-}\" \"${TTD_OUTPUT_DIR:-}\" 2>/dev/null || true\n  rm -f \"${SCRIPT_DIR}/.state/current.env\"\n  echo \"sandbox torn down: ${TTD_PROJECT_NAME:-unknown}\" >&2\n}\n\nusage() {\n  sed -n '2,10p' \"$0\" | sed 's/^# //; s/^#//'\n}\n\nmain() {\n  local cmd=\"${1:-}\"\n  shift || true\n  case \"${cmd}\" in\n    env) cmd_env \"$@\" ;;\n    up-stack) cmd_up_stack \"$@\" ;;\n    up-examples) cmd_up_examples \"$@\" ;;\n    exec)\n      if [[ \"${1:-}\" == \"--\" ]]; then shift; fi\n      cmd_exec \"$@\"\n      ;;\n    exec-timeout) cmd_exec_timeout \"$@\" ;;\n    down) cmd_down \"$@\" ;;\n    -h | --help | help | \"\") usage ;;\n    *) die \"unknown command: ${cmd}\" ;;\n  esac\n}\n\nmain \"$@\"\n", "skills/test-the-docs/sandbox/.empty/.keep": "# Keep empty bind-mount target for compose when no example is mounted.\n", "skills/turbo-scripts/SKILL.md": "---\nname: turbo-scripts\ndescription: Conventions for package.json scripts and turbo.jsonc tasks in the monorepo. Use\n  when adding, changing or reviewing scripts in any apps/* or packages/* package.json, any\n  turbo.jsonc (root or per-package), pre/post hooks, script chains (&&, run-p), maybe-turbo,\n  or turbo task inputs, outputs, env and caching. Includes an audit script that flags scripts\n  that should use maybe-turbo.\n---\n\n# Turbo scripts\n\nTask ordering belongs in `turbo.jsonc` (`dependsOn`), not in `package.json`. pnpm `pre`/`post` hooks and `&&`/`run-p` chains hide steps from turbo, so it can't cache or parallelize them, and running the script through turbo can run them twice. `apps/docs` is the reference implementation.\n\n## Audit first\n\nRun the audit for every package you touch, before and after your change:\n\n```sh\nnode .agents/skills/turbo-scripts/scripts/audit.mjs apps/docs\n```\n\nIt lists each turbo task the package can run (its own `turbo.jsonc` plus the root's) and reports:\n\n- `NEEDS maybe-turbo`: the task has same-package `dependsOn` entries, but the script isn't wrapped.\n- `pre/post hooks to migrate`: `pre<name>`/`post<name>` scripts. `preinstall` is ignored.\n- `scripts that call other scripts`: chains such as `pnpm a && pnpm b` or `run-p a b`. An alias that calls a single script with extra args or env (`pnpm run embeddings --refresh`) isn't reported.\n- `maybe-turbo scripts with no turbo task`: `turbo run` fails for these with `Could not find task`.\n\nFix every finding in the package you're changing, or tell the user why one stays.\n\n## Rules\n\n### Ordering\n\n- Express ordering as `dependsOn` in the package's `turbo.jsonc`. Remove the hook or chain it replaces.\n- Wrap a script with `maybe-turbo` (from `packages/maybe-turbo`; add `\"maybe-turbo\": \"workspace:*\"` to `devDependencies`) when its task has same-package `dependsOn` entries. Outside turbo, `pnpm <script>` then runs `turbo run <script> --filter=<package>`, so prerequisites still run. Leaf scripts with no dependencies don't need it.\n- Don't split a task into a `turbo run <name>-inner` script plus an inner script. Use `maybe-turbo`, so each task has one script name for callers and `turbo.jsonc`.\n- Put compound commands in one quoted argument: `\"typecheck\": \"maybe-turbo \\\"next typegen && tsc --noEmit\\\"\"`. `maybe-turbo` exits with an error if `&&`, `||`, `;` or `|` appears outside the quotes.\n- A task that only groups other tasks gets a bare `\"<name>\": \"maybe-turbo\"` script, so `pnpm <name>` still works.\n- Every wrapped script needs a task in `turbo.jsonc` (the package's or the root's).\n- When you override `dependsOn` for a root task such as `build` or `typecheck`, keep `^build` / `^typecheck`.\n- Persistent sidecars that must run next to `dev` (for example `velite dev`) go in the task's `with` key, not `run-p`.\n\n### Caching\n\n- Declare `outputs` for every cacheable task that writes files. If two tasks write into the same directory, list only each task's own files.\n- Mark tasks that fetch remote content or check local state as `\"cache\": false`.\n- Default `inputs` skip gitignored files, and plain globs are hashed when `turbo` starts, before any task runs. A task that reads gitignored files written by an uncached task must list them in `jit` mode, or a cache hit can restore output built from stale content:\n\n  ```jsonc\n  \"inputs\": [\"$TURBO_DEFAULT$\", { \"mode\": \"jit\", \"globs\": [\"content/guides/**\"] }]\n  ```\n\n- Keep generated output deterministic (sorted keys, stable order). A tracked file that a task rewrites differently on every run invalidates the whole package's cache.\n\n### Env\n\n- Turbo runs tasks in strict env mode, which drops undeclared variables. Declare every variable the task reads: `env` for values that change the output, `passThroughEnv` for secrets and credentials that don't.\n- Check what the script and the modules it imports read (`git grep \"process.env\"`), including shared packages.\n\n### Side effects\n\n- On a cache hit, turbo restores outputs without running the script. Keep uploads, deploys and database writes in uncached tasks or outside turbo (for example in a `vercel.json` `buildCommand` after `pnpm build`).\n\n### Callers\n\n- Find everything that runs the scripts you change: `.github/workflows`, `vercel.json`, root `package.json`, other apps' scripts, `e2e/*`, and docs/READMEs. A plain `pnpm <script>` keeps working once the script is wrapped with `maybe-turbo`.\n- A wrapped script called from inside another turbo task sees `TURBO_HASH` and runs without its prerequisites. Declare the dependency in `turbo.jsonc` instead of calling the script from another script.\n\n## Verify\n\n1. Run the audit again.\n2. Check the graph: `pnpm turbo run <task> --filter=<package> --dry=json`.\n3. Run the entry point the way callers do, for example `pnpm build` in the package, then run it again and confirm the second run hits the cache. Tasks that use `jit` inputs report `hash: null` in `--dry=json`; that's expected.\n", "skills/turbo-scripts/scripts/audit.mjs": "#!/usr/bin/env node\n// Lists every turbo task a workspace package can run (its own turbo.jsonc plus the root's) and\n// whether the matching package.json script is wrapped with maybe-turbo.\n//\n//   node .agents/skills/turbo-scripts/scripts/audit.mjs apps/docs\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst dir = process.argv[2]\nif (!dir) {\n  console.error('Usage: node audit.mjs <package dir>, for example apps/docs')\n  process.exit(1)\n}\n\nconst readJsonc = (path) =>\n  existsSync(path)\n    ? JSON.parse(\n        readFileSync(path, 'utf8')\n          .replace(/^\\s*\\/\\/.*$/gm, '')\n          .replace(/,(\\s*[}\\]])/g, '$1')\n      )\n    : { tasks: {} }\n\nconst scripts = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).scripts ?? {}\nconst local = readJsonc(join(dir, 'turbo.jsonc')).tasks ?? {}\nconst root = readJsonc('turbo.jsonc').tasks ?? {}\n\nconst rows = [...new Set([...Object.keys(local), ...Object.keys(root)])].sort().map((task) => {\n  const config = { ...root[task], ...local[task] }\n  const script = scripts[task]\n  const deps = (config.dependsOn ?? []).filter((dep) => !dep.startsWith('^'))\n  const wrapped = script?.startsWith('maybe-turbo') ?? false\n  let status = 'ok'\n  if (script === undefined) status = deps.length > 0 ? 'no script (aggregate?)' : 'no script'\n  else if (deps.length > 0 && !wrapped) status = 'NEEDS maybe-turbo'\n  return [\n    task,\n    local[task] ? 'package' : 'root',\n    wrapped ? 'yes' : 'no',\n    config.cache === false ? 'no' : 'yes',\n    status,\n    deps.join(', ') || '-',\n  ]\n})\n\n// pnpm runs `pre<name>`/`post<name>` around `<name>`. `preinstall` is an install hook, not ordering.\nconst hooks = Object.keys(scripts).filter((name) => {\n  const match = name.match(/^(?:pre|post)(.+)$/)\n  return match && match[1] !== 'install' && scripts[match[1]] !== undefined\n})\n\n// Scripts that sequence other scripts (`pnpm a && pnpm b`, `run-p a b`) hide steps from turbo.\n// An alias that calls one script with extra args or env (`pnpm run embeddings --refresh`) is fine.\nconst names = Object.keys(scripts)\nconst matchScripts = (pattern) =>\n  pattern.endsWith('*')\n    ? names.filter((name) => name.startsWith(pattern.slice(0, -1)))\n    : names.filter((name) => name === pattern)\nconst scriptsCalledBy = (segment) => {\n  const words = segment\n    .trim()\n    .split(/\\s+/)\n    .filter((word) => !/^\\w+=/.test(word))\n  if (words[0] === 'pnpm') {\n    const rest = words.slice(1).filter((word) => !word.startsWith('-'))\n    return matchScripts(rest[0] === 'run' ? (rest[1] ?? '') : (rest[0] ?? ''))\n  }\n  if (['run-p', 'run-s', 'npm-run-all'].includes(words[0])) {\n    return words\n      .slice(1)\n      .filter((word) => !word.startsWith('-'))\n      .flatMap(matchScripts)\n  }\n  return []\n}\nconst chains = Object.entries(scripts)\n  .map(([name, command]) => {\n    const segments = command.split(/&&|\\|\\||;/)\n    const called = [...new Set(segments.flatMap(scriptsCalledBy))].filter((other) => other !== name)\n    const isAlias = segments.length === 1 && called.length === 1\n    return called.length > 0 && !isAlias ? `${name} -> ${called.join(', ')}` : null\n  })\n  .filter(Boolean)\n\nconst orphans = Object.entries(scripts)\n  .filter(([name, command]) => command.startsWith('maybe-turbo') && !local[name] && !root[name])\n  .map(([name]) => name)\n\nconst header = ['task', 'defined in', 'maybe-turbo', 'cached', 'status', 'same-package deps']\nconst widths = header.map((_, i) => Math.max(...[header, ...rows].map((row) => row[i].length)))\nfor (const row of [header, ...rows])\n  console.log(row.map((cell, i) => cell.padEnd(widths[i])).join('  '))\n\nif (hooks.length > 0) console.log(`\\npre/post hooks to migrate: ${hooks.join(', ')}`)\nif (chains.length > 0) console.log(`\\nscripts that call other scripts:\\n  ${chains.join('\\n  ')}`)\nif (orphans.length > 0)\n  console.log(`\\nmaybe-turbo scripts with no turbo task: ${orphans.join(', ')}`)\n", "skills/vercel-composition-patterns/SKILL.md": "---\nname: vercel-composition-patterns\ndescription: React composition patterns that scale. Use when refactoring components with\n  boolean prop proliferation, building flexible component libraries, or\n  designing reusable APIs. Triggers on tasks involving compound components,\n  render props, context providers, or component architecture. Includes React 19\n  API changes.\nlicense: MIT\nmetadata:\n  author: vercel\n  version: '1.0.0'\n---\n\n# React Composition Patterns\n\nComposition patterns for building flexible, maintainable React components. Avoid\nboolean prop proliferation by using compound components, lifting state, and\ncomposing internals. These patterns make codebases easier for both humans and AI\nagents to work with as they scale.\n\n## When to Apply\n\nReference these guidelines when:\n\n- Refactoring components with many boolean props\n- Building reusable component libraries\n- Designing flexible component APIs\n- Reviewing component architecture\n- Working with compound components or context providers\n\n## Rule Categories by Priority\n\n| Priority | Category                | Impact | Prefix          |\n| -------- | ----------------------- | ------ | --------------- |\n| 1        | Component Architecture  | HIGH   | `architecture-` |\n| 2        | State Management        | MEDIUM | `state-`        |\n| 3        | Implementation Patterns | MEDIUM | `patterns-`     |\n| 4        | React 19 APIs           | MEDIUM | `react19-`      |\n\n## Quick Reference\n\n### 1. Component Architecture (HIGH)\n\n- `architecture-avoid-boolean-props` - Don't add boolean props to customize\n  behavior; use composition\n- `architecture-compound-components` - Structure complex components with shared\n  context\n\n### 2. State Management (MEDIUM)\n\n- `state-decouple-implementation` - Provider is the only place that knows how\n  state is managed\n- `state-context-interface` - Define generic interface with state, actions, meta\n  for dependency injection\n- `state-lift-state` - Move state into provider components for sibling access\n\n### 3. Implementation Patterns (MEDIUM)\n\n- `patterns-explicit-variants` - Create explicit variant components instead of\n  boolean modes\n- `patterns-children-over-render-props` - Use children for composition instead\n  of renderX props\n\n### 4. React 19 APIs (MEDIUM)\n\n> **⚠️ React 19+ only.** Skip these patterns if you're on React 18 or earlier.\n\n- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/architecture-avoid-boolean-props.md\nrules/state-context-interface.md\n```\n\nEach rule file contains:\n\n- Brief explanation of why it matters\n- Incorrect code example with explanation\n- Correct code example with explanation\n- Additional context and references\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded, read the files under `rules/`\n", "skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md": "---\ntitle: Avoid Boolean Prop Proliferation\nimpact: CRITICAL\nimpactDescription: prevents unmaintainable component variants\ntags: composition, props, architecture\n---\n\n## Avoid Boolean Prop Proliferation\n\nDon't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize\ncomponent behavior. Each boolean doubles possible states and creates\nunmaintainable conditional logic. Use composition instead.\n\n**Incorrect (boolean props create exponential complexity):**\n\n```tsx\nfunction Composer({\n  onSubmit,\n  isThread,\n  channelId,\n  isDMThread,\n  dmId,\n  isEditing,\n  isForwarding,\n}: Props) {\n  return (\n    <form>\n      <Header />\n      <Input />\n      {isDMThread ? (\n        <AlsoSendToDMField id={dmId} />\n      ) : isThread ? (\n        <AlsoSendToChannelField id={channelId} />\n      ) : null}\n      {isEditing ? (\n        <EditActions />\n      ) : isForwarding ? (\n        <ForwardActions />\n      ) : (\n        <DefaultActions />\n      )}\n      <Footer onSubmit={onSubmit} />\n    </form>\n  )\n}\n```\n\n**Correct (composition eliminates conditionals):**\n\n```tsx\n// Channel composer\nfunction ChannelComposer() {\n  return (\n    <Composer.Frame>\n      <Composer.Header />\n      <Composer.Input />\n      <Composer.Footer>\n        <Composer.Attachments />\n        <Composer.Formatting />\n        <Composer.Emojis />\n        <Composer.Submit />\n      </Composer.Footer>\n    </Composer.Frame>\n  )\n}\n\n// Thread composer - adds \"also send to channel\" field\nfunction ThreadComposer({ channelId }: { channelId: string }) {\n  return (\n    <Composer.Frame>\n      <Composer.Header />\n      <Composer.Input />\n      <AlsoSendToChannelField id={channelId} />\n      <Composer.Footer>\n        <Composer.Formatting />\n        <Composer.Emojis />\n        <Composer.Submit />\n      </Composer.Footer>\n    </Composer.Frame>\n  )\n}\n\n// Edit composer - different footer actions\nfunction EditComposer() {\n  return (\n    <Composer.Frame>\n      <Composer.Input />\n      <Composer.Footer>\n        <Composer.Formatting />\n        <Composer.Emojis />\n        <Composer.CancelEdit />\n        <Composer.SaveEdit />\n      </Composer.Footer>\n    </Composer.Frame>\n  )\n}\n```\n\nEach variant is explicit about what it renders. We can share internals without\nsharing a single monolithic parent.\n", "skills/vercel-composition-patterns/rules/architecture-compound-components.md": "---\ntitle: Use Compound Components\nimpact: HIGH\nimpactDescription: enables flexible composition without prop drilling\ntags: composition, compound-components, architecture\n---\n\n## Use Compound Components\n\nStructure complex components as compound components with a shared context. Each\nsubcomponent accesses shared state via context, not props. Consumers compose the\npieces they need.\n\n**Incorrect (monolithic component with render props):**\n\n```tsx\nfunction Composer({\n  renderHeader,\n  renderFooter,\n  renderActions,\n  showAttachments,\n  showFormatting,\n  showEmojis,\n}: Props) {\n  return (\n    <form>\n      {renderHeader?.()}\n      <Input />\n      {showAttachments && <Attachments />}\n      {renderFooter ? (\n        renderFooter()\n      ) : (\n        <Footer>\n          {showFormatting && <Formatting />}\n          {showEmojis && <Emojis />}\n          {renderActions?.()}\n        </Footer>\n      )}\n    </form>\n  )\n}\n```\n\n**Correct (compound components with shared context):**\n\n```tsx\nconst ComposerContext = createContext<ComposerContextValue | null>(null)\n\nfunction ComposerProvider({ children, state, actions, meta }: ProviderProps) {\n  return (\n    <ComposerContext value={{ state, actions, meta }}>\n      {children}\n    </ComposerContext>\n  )\n}\n\nfunction ComposerFrame({ children }: { children: React.ReactNode }) {\n  return <form>{children}</form>\n}\n\nfunction ComposerInput() {\n  const {\n    state,\n    actions: { update },\n    meta: { inputRef },\n  } = use(ComposerContext)\n  return (\n    <TextInput\n      ref={inputRef}\n      value={state.input}\n      onChangeText={(text) => update((s) => ({ ...s, input: text }))}\n    />\n  )\n}\n\nfunction ComposerSubmit() {\n  const {\n    actions: { submit },\n  } = use(ComposerContext)\n  return <Button onPress={submit}>Send</Button>\n}\n\n// Export as compound component\nconst Composer = {\n  Provider: ComposerProvider,\n  Frame: ComposerFrame,\n  Input: ComposerInput,\n  Submit: ComposerSubmit,\n  Header: ComposerHeader,\n  Footer: ComposerFooter,\n  Attachments: ComposerAttachments,\n  Formatting: ComposerFormatting,\n  Emojis: ComposerEmojis,\n}\n```\n\n**Usage:**\n\n```tsx\n<Composer.Provider state={state} actions={actions} meta={meta}>\n  <Composer.Frame>\n    <Composer.Header />\n    <Composer.Input />\n    <Composer.Footer>\n      <Composer.Formatting />\n      <Composer.Submit />\n    </Composer.Footer>\n  </Composer.Frame>\n</Composer.Provider>\n```\n\nConsumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.\n", "skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md": "---\ntitle: Prefer Composing Children Over Render Props\nimpact: MEDIUM\nimpactDescription: cleaner composition, better readability\ntags: composition, children, render-props\n---\n\n## Prefer Children Over Render Props\n\nUse `children` for composition instead of `renderX` props. Children are more\nreadable, compose naturally, and don't require understanding callback\nsignatures.\n\n**Incorrect (render props):**\n\n```tsx\nfunction Composer({\n  renderHeader,\n  renderFooter,\n  renderActions,\n}: {\n  renderHeader?: () => React.ReactNode\n  renderFooter?: () => React.ReactNode\n  renderActions?: () => React.ReactNode\n}) {\n  return (\n    <form>\n      {renderHeader?.()}\n      <Input />\n      {renderFooter ? renderFooter() : <DefaultFooter />}\n      {renderActions?.()}\n    </form>\n  )\n}\n\n// Usage is awkward and inflexible\nreturn (\n  <Composer\n    renderHeader={() => <CustomHeader />}\n    renderFooter={() => (\n      <>\n        <Formatting />\n        <Emojis />\n      </>\n    )}\n    renderActions={() => <SubmitButton />}\n  />\n)\n```\n\n**Correct (compound components with children):**\n\n```tsx\nfunction ComposerFrame({ children }: { children: React.ReactNode }) {\n  return <form>{children}</form>\n}\n\nfunction ComposerFooter({ children }: { children: React.ReactNode }) {\n  return <footer className='flex'>{children}</footer>\n}\n\n// Usage is flexible\nreturn (\n  <Composer.Frame>\n    <CustomHeader />\n    <Composer.Input />\n    <Composer.Footer>\n      <Composer.Formatting />\n      <Composer.Emojis />\n      <SubmitButton />\n    </Composer.Footer>\n  </Composer.Frame>\n)\n```\n\n**When render props are appropriate:**\n\n```tsx\n// Render props work well when you need to pass data back\n<List\n  data={items}\n  renderItem={({ item, index }) => <Item item={item} index={index} />}\n/>\n```\n\nUse render props when the parent needs to provide data or state to the child.\nUse children when composing static structure.\n", "skills/vercel-composition-patterns/rules/patterns-explicit-variants.md": "---\ntitle: Create Explicit Component Variants\nimpact: MEDIUM\nimpactDescription: self-documenting code, no hidden conditionals\ntags: composition, variants, architecture\n---\n\n## Create Explicit Component Variants\n\nInstead of one component with many boolean props, create explicit variant\ncomponents. Each variant composes the pieces it needs. The code documents\nitself.\n\n**Incorrect (one component, many modes):**\n\n```tsx\n// What does this component actually render?\n<Composer\n  isThread\n  isEditing={false}\n  channelId='abc'\n  showAttachments\n  showFormatting={false}\n/>\n```\n\n**Correct (explicit variants):**\n\n```tsx\n// Immediately clear what this renders\n<ThreadComposer channelId=\"abc\" />\n\n// Or\n<EditMessageComposer messageId=\"xyz\" />\n\n// Or\n<ForwardMessageComposer messageId=\"123\" />\n```\n\nEach implementation is unique, explicit and self-contained. Yet they can each\nuse shared parts.\n\n**Implementation:**\n\n```tsx\nfunction ThreadComposer({ channelId }: { channelId: string }) {\n  return (\n    <ThreadProvider channelId={channelId}>\n      <Composer.Frame>\n        <Composer.Input />\n        <AlsoSendToChannelField channelId={channelId} />\n        <Composer.Footer>\n          <Composer.Formatting />\n          <Composer.Emojis />\n          <Composer.Submit />\n        </Composer.Footer>\n      </Composer.Frame>\n    </ThreadProvider>\n  )\n}\n\nfunction EditMessageComposer({ messageId }: { messageId: string }) {\n  return (\n    <EditMessageProvider messageId={messageId}>\n      <Composer.Frame>\n        <Composer.Input />\n        <Composer.Footer>\n          <Composer.Formatting />\n          <Composer.Emojis />\n          <Composer.CancelEdit />\n          <Composer.SaveEdit />\n        </Composer.Footer>\n      </Composer.Frame>\n    </EditMessageProvider>\n  )\n}\n\nfunction ForwardMessageComposer({ messageId }: { messageId: string }) {\n  return (\n    <ForwardMessageProvider messageId={messageId}>\n      <Composer.Frame>\n        <Composer.Input placeholder=\"Add a message, if you'd like.\" />\n        <Composer.Footer>\n          <Composer.Formatting />\n          <Composer.Emojis />\n          <Composer.Mentions />\n        </Composer.Footer>\n      </Composer.Frame>\n    </ForwardMessageProvider>\n  )\n}\n```\n\nEach variant is explicit about:\n\n- What provider/state it uses\n- What UI elements it includes\n- What actions are available\n\nNo boolean prop combinations to reason about. No impossible states.\n", "skills/vercel-composition-patterns/rules/react19-no-forwardref.md": "---\ntitle: React 19 API Changes\nimpact: MEDIUM\nimpactDescription: cleaner component definitions and context usage\ntags: react19, refs, context, hooks\n---\n\n## React 19 API Changes\n\n> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.\n\nIn React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.\n\n**Incorrect (forwardRef in React 19):**\n\n```tsx\nconst ComposerInput = forwardRef<TextInput, Props>((props, ref) => {\n  return <TextInput ref={ref} {...props} />\n})\n```\n\n**Correct (ref as a regular prop):**\n\n```tsx\nfunction ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {\n  return <TextInput ref={ref} {...props} />\n}\n```\n\n**Incorrect (useContext in React 19):**\n\n```tsx\nconst value = useContext(MyContext)\n```\n\n**Correct (use instead of useContext):**\n\n```tsx\nconst value = use(MyContext)\n```\n\n`use()` can also be called conditionally, unlike `useContext()`.\n", "skills/vercel-composition-patterns/rules/state-context-interface.md": "---\ntitle: Define Generic Context Interfaces for Dependency Injection\nimpact: HIGH\nimpactDescription: enables dependency-injectable state across use-cases\ntags: composition, context, state, typescript, dependency-injection\n---\n\n## Define Generic Context Interfaces for Dependency Injection\n\nDefine a **generic interface** for your component context with three parts:\n`state`, `actions`, and `meta`. This interface is a contract that any provider\ncan implement—enabling the same UI components to work with completely different\nstate implementations.\n\n**Core principle:** Lift state, compose internals, make state\ndependency-injectable.\n\n**Incorrect (UI coupled to specific state implementation):**\n\n```tsx\nfunction ComposerInput() {\n  // Tightly coupled to a specific hook\n  const { input, setInput } = useChannelComposerState()\n  return <TextInput value={input} onChangeText={setInput} />\n}\n```\n\n**Correct (generic interface enables dependency injection):**\n\n```tsx\n// Define a GENERIC interface that any provider can implement\ninterface ComposerState {\n  input: string\n  attachments: Attachment[]\n  isSubmitting: boolean\n}\n\ninterface ComposerActions {\n  update: (updater: (state: ComposerState) => ComposerState) => void\n  submit: () => void\n}\n\ninterface ComposerMeta {\n  inputRef: React.RefObject<TextInput>\n}\n\ninterface ComposerContextValue {\n  state: ComposerState\n  actions: ComposerActions\n  meta: ComposerMeta\n}\n\nconst ComposerContext = createContext<ComposerContextValue | null>(null)\n```\n\n**UI components consume the interface, not the implementation:**\n\n```tsx\nfunction ComposerInput() {\n  const {\n    state,\n    actions: { update },\n    meta,\n  } = use(ComposerContext)\n\n  // This component works with ANY provider that implements the interface\n  return (\n    <TextInput\n      ref={meta.inputRef}\n      value={state.input}\n      onChangeText={(text) => update((s) => ({ ...s, input: text }))}\n    />\n  )\n}\n```\n\n**Different providers implement the same interface:**\n\n```tsx\n// Provider A: Local state for ephemeral forms\nfunction ForwardMessageProvider({ children }: { children: React.ReactNode }) {\n  const [state, setState] = useState(initialState)\n  const inputRef = useRef(null)\n  const submit = useForwardMessage()\n\n  return (\n    <ComposerContext\n      value={{\n        state,\n        actions: { update: setState, submit },\n        meta: { inputRef },\n      }}\n    >\n      {children}\n    </ComposerContext>\n  )\n}\n\n// Provider B: Global synced state for channels\nfunction ChannelProvider({ channelId, children }: Props) {\n  const { state, update, submit } = useGlobalChannel(channelId)\n  const inputRef = useRef(null)\n\n  return (\n    <ComposerContext\n      value={{\n        state,\n        actions: { update, submit },\n        meta: { inputRef },\n      }}\n    >\n      {children}\n    </ComposerContext>\n  )\n}\n```\n\n**The same composed UI works with both:**\n\n```tsx\n// Works with ForwardMessageProvider (local state)\n<ForwardMessageProvider>\n  <Composer.Frame>\n    <Composer.Input />\n    <Composer.Submit />\n  </Composer.Frame>\n</ForwardMessageProvider>\n\n// Works with ChannelProvider (global synced state)\n<ChannelProvider channelId=\"abc\">\n  <Composer.Frame>\n    <Composer.Input />\n    <Composer.Submit />\n  </Composer.Frame>\n</ChannelProvider>\n```\n\n**Custom UI outside the component can access state and actions:**\n\nThe provider boundary is what matters—not the visual nesting. Components that\nneed shared state don't have to be inside the `Composer.Frame`. They just need\nto be within the provider.\n\n```tsx\nfunction ForwardMessageDialog() {\n  return (\n    <ForwardMessageProvider>\n      <Dialog>\n        {/* The composer UI */}\n        <Composer.Frame>\n          <Composer.Input placeholder=\"Add a message, if you'd like.\" />\n          <Composer.Footer>\n            <Composer.Formatting />\n            <Composer.Emojis />\n          </Composer.Footer>\n        </Composer.Frame>\n\n        {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}\n        <MessagePreview />\n\n        {/* Actions at the bottom of the dialog */}\n        <DialogActions>\n          <CancelButton />\n          <ForwardButton />\n        </DialogActions>\n      </Dialog>\n    </ForwardMessageProvider>\n  )\n}\n\n// This button lives OUTSIDE Composer.Frame but can still submit based on its context!\nfunction ForwardButton() {\n  const {\n    actions: { submit },\n  } = use(ComposerContext)\n  return <Button onPress={submit}>Forward</Button>\n}\n\n// This preview lives OUTSIDE Composer.Frame but can read composer's state!\nfunction MessagePreview() {\n  const { state } = use(ComposerContext)\n  return <Preview message={state.input} attachments={state.attachments} />\n}\n```\n\nThe `ForwardButton` and `MessagePreview` are not visually inside the composer\nbox, but they can still access its state and actions. This is the power of\nlifting state into providers.\n\nThe UI is reusable bits you compose together. The state is dependency-injected\nby the provider. Swap the provider, keep the UI.\n", "skills/vercel-composition-patterns/rules/state-decouple-implementation.md": "---\ntitle: Decouple State Management from UI\nimpact: MEDIUM\nimpactDescription: enables swapping state implementations without changing UI\ntags: composition, state, architecture\n---\n\n## Decouple State Management from UI\n\nThe provider component should be the only place that knows how state is managed.\nUI components consume the context interface—they don't know if state comes from\nuseState, Zustand, or a server sync.\n\n**Incorrect (UI coupled to state implementation):**\n\n```tsx\nfunction ChannelComposer({ channelId }: { channelId: string }) {\n  // UI component knows about global state implementation\n  const state = useGlobalChannelState(channelId)\n  const { submit, updateInput } = useChannelSync(channelId)\n\n  return (\n    <Composer.Frame>\n      <Composer.Input\n        value={state.input}\n        onChange={(text) => sync.updateInput(text)}\n      />\n      <Composer.Submit onPress={() => sync.submit()} />\n    </Composer.Frame>\n  )\n}\n```\n\n**Correct (state management isolated in provider):**\n\n```tsx\n// Provider handles all state management details\nfunction ChannelProvider({\n  channelId,\n  children,\n}: {\n  channelId: string\n  children: React.ReactNode\n}) {\n  const { state, update, submit } = useGlobalChannel(channelId)\n  const inputRef = useRef(null)\n\n  return (\n    <Composer.Provider\n      state={state}\n      actions={{ update, submit }}\n      meta={{ inputRef }}\n    >\n      {children}\n    </Composer.Provider>\n  )\n}\n\n// UI component only knows about the context interface\nfunction ChannelComposer() {\n  return (\n    <Composer.Frame>\n      <Composer.Header />\n      <Composer.Input />\n      <Composer.Footer>\n        <Composer.Submit />\n      </Composer.Footer>\n    </Composer.Frame>\n  )\n}\n\n// Usage\nfunction Channel({ channelId }: { channelId: string }) {\n  return (\n    <ChannelProvider channelId={channelId}>\n      <ChannelComposer />\n    </ChannelProvider>\n  )\n}\n```\n\n**Different providers, same UI:**\n\n```tsx\n// Local state for ephemeral forms\nfunction ForwardMessageProvider({ children }) {\n  const [state, setState] = useState(initialState)\n  const forwardMessage = useForwardMessage()\n\n  return (\n    <Composer.Provider\n      state={state}\n      actions={{ update: setState, submit: forwardMessage }}\n    >\n      {children}\n    </Composer.Provider>\n  )\n}\n\n// Global synced state for channels\nfunction ChannelProvider({ channelId, children }) {\n  const { state, update, submit } = useGlobalChannel(channelId)\n\n  return (\n    <Composer.Provider state={state} actions={{ update, submit }}>\n      {children}\n    </Composer.Provider>\n  )\n}\n```\n\nThe same `Composer.Input` component works with both providers because it only\ndepends on the context interface, not the implementation.\n", "skills/vercel-composition-patterns/rules/state-lift-state.md": "---\ntitle: Lift State into Provider Components\nimpact: HIGH\nimpactDescription: enables state sharing outside component boundaries\ntags: composition, state, context, providers\n---\n\n## Lift State into Provider Components\n\nMove state management into dedicated provider components. This allows sibling\ncomponents outside the main UI to access and modify state without prop drilling\nor awkward refs.\n\n**Incorrect (state trapped inside component):**\n\n```tsx\nfunction ForwardMessageComposer() {\n  const [state, setState] = useState(initialState)\n  const forwardMessage = useForwardMessage()\n\n  return (\n    <Composer.Frame>\n      <Composer.Input />\n      <Composer.Footer />\n    </Composer.Frame>\n  )\n}\n\n// Problem: How does this button access composer state?\nfunction ForwardMessageDialog() {\n  return (\n    <Dialog>\n      <ForwardMessageComposer />\n      <MessagePreview /> {/* Needs composer state */}\n      <DialogActions>\n        <CancelButton />\n        <ForwardButton /> {/* Needs to call submit */}\n      </DialogActions>\n    </Dialog>\n  )\n}\n```\n\n**Incorrect (useEffect to sync state up):**\n\n```tsx\nfunction ForwardMessageDialog() {\n  const [input, setInput] = useState('')\n  return (\n    <Dialog>\n      <ForwardMessageComposer onInputChange={setInput} />\n      <MessagePreview input={input} />\n    </Dialog>\n  )\n}\n\nfunction ForwardMessageComposer({ onInputChange }) {\n  const [state, setState] = useState(initialState)\n  useEffect(() => {\n    onInputChange(state.input) // Sync on every change 😬\n  }, [state.input])\n}\n```\n\n**Incorrect (reading state from ref on submit):**\n\n```tsx\nfunction ForwardMessageDialog() {\n  const stateRef = useRef(null)\n  return (\n    <Dialog>\n      <ForwardMessageComposer stateRef={stateRef} />\n      <ForwardButton onPress={() => submit(stateRef.current)} />\n    </Dialog>\n  )\n}\n```\n\n**Correct (state lifted to provider):**\n\n```tsx\nfunction ForwardMessageProvider({ children }: { children: React.ReactNode }) {\n  const [state, setState] = useState(initialState)\n  const forwardMessage = useForwardMessage()\n  const inputRef = useRef(null)\n\n  return (\n    <Composer.Provider\n      state={state}\n      actions={{ update: setState, submit: forwardMessage }}\n      meta={{ inputRef }}\n    >\n      {children}\n    </Composer.Provider>\n  )\n}\n\nfunction ForwardMessageDialog() {\n  return (\n    <ForwardMessageProvider>\n      <Dialog>\n        <ForwardMessageComposer />\n        <MessagePreview /> {/* Custom components can access state and actions */}\n        <DialogActions>\n          <CancelButton />\n          <ForwardButton /> {/* Custom components can access state and actions */}\n        </DialogActions>\n      </Dialog>\n    </ForwardMessageProvider>\n  )\n}\n\nfunction ForwardButton() {\n  const { actions } = use(Composer.Context)\n  return <Button onPress={actions.submit}>Forward</Button>\n}\n```\n\nThe ForwardButton lives outside the Composer.Frame but still has access to the\nsubmit action because it's within the provider. Even though it's a one-off\ncomponent, it can still access the composer's state and actions from outside the\nUI itself.\n\n**Key insight:** Components that need shared state don't have to be visually\nnested inside each other—they just need to be within the same provider.\n", "skills/vitest/GENERATION.md": "# Generation Info\n\n- **Source:** `sources/vitest`\n- **Git SHA:** `4a7321e10672f00f0bb698823a381c2cc245b8f7`\n- **Generated:** 2026-01-28\n", "skills/vitest/SKILL.md": "---\nname: vitest\ndescription: >-\n  Vitest API and config reference (Jest-compatible) — mocking with vi.*, spies,\n  fake timers, coverage configuration, fixtures, snapshots, and test filtering.\n  Use for Vitest API and configuration questions anywhere in the monorepo; for\n  Studio-specific test strategy and component-test setup, start with\n  studio-testing and studio-mock-api-tests.\nmetadata:\n  author: Anthony Fu\n  version: '2026.1.28'\n  source: Generated from https://github.com/vitest-dev/vitest, scripts located at https://github.com/antfu/skills\n---\n\nVitest is a next-generation testing framework powered by Vite. It provides a Jest-compatible API with native ESM, TypeScript, and JSX support out of the box. Vitest shares the same config, transformers, resolvers, and plugins with your Vite app.\n\n**Key Features:**\n\n- Vite-native: Uses Vite's transformation pipeline for fast HMR-like test updates\n- Jest-compatible: Drop-in replacement for most Jest test suites\n- Smart watch mode: Only reruns affected tests based on module graph\n- Native ESM, TypeScript, JSX support without configuration\n- Multi-threaded workers for parallel test execution\n- Built-in coverage via V8 or Istanbul\n- Snapshot testing, mocking, and spy utilities\n\n> The skill is based on Vitest 3.x, generated at 2026-01-28.\n\n## Core\n\n| Topic         | Description                                                     | Reference                                    |\n| ------------- | --------------------------------------------------------------- | -------------------------------------------- |\n| Configuration | Vitest and Vite config integration, defineConfig usage          | [core-config](references/core-config.md)     |\n| CLI           | Command line interface, commands and options                    | [core-cli](references/core-cli.md)           |\n| Test API      | test/it function, modifiers like skip, only, concurrent         | [core-test-api](references/core-test-api.md) |\n| Describe API  | describe/suite for grouping tests and nested suites             | [core-describe](references/core-describe.md) |\n| Expect API    | Assertions with toBe, toEqual, matchers and asymmetric matchers | [core-expect](references/core-expect.md)     |\n| Hooks         | beforeEach, afterEach, beforeAll, afterAll, aroundEach          | [core-hooks](references/core-hooks.md)       |\n\n## Features\n\n| Topic        | Description                                                    | Reference                                                  |\n| ------------ | -------------------------------------------------------------- | ---------------------------------------------------------- |\n| Mocking      | Mock functions, modules, timers, dates with vi utilities       | [features-mocking](references/features-mocking.md)         |\n| Snapshots    | Snapshot testing with toMatchSnapshot and inline snapshots     | [features-snapshots](references/features-snapshots.md)     |\n| Coverage     | Code coverage with V8 or Istanbul providers                    | [features-coverage](references/features-coverage.md)       |\n| Test Context | Test fixtures, context.expect, test.extend for custom fixtures | [features-context](references/features-context.md)         |\n| Concurrency  | Concurrent tests, parallel execution, sharding                 | [features-concurrency](references/features-concurrency.md) |\n| Filtering    | Filter tests by name, file patterns, tags                      | [features-filtering](references/features-filtering.md)     |\n\n## Advanced\n\n| Topic        | Description                                             | Reference                                                    |\n| ------------ | ------------------------------------------------------- | ------------------------------------------------------------ |\n| Vi Utilities | vi helper: mock, spyOn, fake timers, hoisted, waitFor   | [advanced-vi](references/advanced-vi.md)                     |\n| Environments | Test environments: node, jsdom, happy-dom, custom       | [advanced-environments](references/advanced-environments.md) |\n| Type Testing | Type-level testing with expectTypeOf and assertType     | [advanced-type-testing](references/advanced-type-testing.md) |\n| Projects     | Multi-project workspaces, different configs per project | [advanced-projects](references/advanced-projects.md)         |\n", "skills/vitest/references/advanced-environments.md": "---\nname: test-environments\ndescription: Configure environments like jsdom, happy-dom for browser APIs\n---\n\n# Test Environments\n\n## Available Environments\n\n- `node` (default) - Node.js environment\n- `jsdom` - Browser-like with DOM APIs\n- `happy-dom` - Faster alternative to jsdom\n- `edge-runtime` - Vercel Edge Runtime\n\n## Configuration\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    environment: 'jsdom',\n    \n    // Environment-specific options\n    environmentOptions: {\n      jsdom: {\n        url: 'http://localhost',\n      },\n    },\n  },\n})\n```\n\n## Installing Environment Packages\n\n```bash\n# jsdom\nnpm i -D jsdom\n\n# happy-dom (faster, fewer APIs)\nnpm i -D happy-dom\n```\n\n## Per-File Environment\n\nUse magic comment at top of file:\n\n```ts\n// @vitest-environment jsdom\n\nimport { expect, test } from 'vitest'\n\ntest('DOM test', () => {\n  const div = document.createElement('div')\n  expect(div).toBeInstanceOf(HTMLDivElement)\n})\n```\n\n## jsdom Environment\n\nFull browser environment simulation:\n\n```ts\n// @vitest-environment jsdom\n\ntest('DOM manipulation', () => {\n  document.body.innerHTML = '<div id=\"app\"></div>'\n  \n  const app = document.getElementById('app')\n  app.textContent = 'Hello'\n  \n  expect(app.textContent).toBe('Hello')\n})\n\ntest('window APIs', () => {\n  expect(window.location.href).toBeDefined()\n  expect(localStorage).toBeDefined()\n})\n```\n\n### jsdom Options\n\n```ts\ndefineConfig({\n  test: {\n    environmentOptions: {\n      jsdom: {\n        url: 'http://localhost:3000',\n        html: '<!DOCTYPE html><html><body></body></html>',\n        userAgent: 'custom-agent',\n        resources: 'usable',\n      },\n    },\n  },\n})\n```\n\n## happy-dom Environment\n\nFaster but fewer APIs:\n\n```ts\n// @vitest-environment happy-dom\n\ntest('basic DOM', () => {\n  const el = document.createElement('div')\n  el.className = 'test'\n  expect(el.className).toBe('test')\n})\n```\n\n## Multiple Environments per Project\n\nUse projects for different environments:\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'unit',\n          include: ['tests/unit/**/*.test.ts'],\n          environment: 'node',\n        },\n      },\n      {\n        test: {\n          name: 'dom',\n          include: ['tests/dom/**/*.test.ts'],\n          environment: 'jsdom',\n        },\n      },\n    ],\n  },\n})\n```\n\n## Custom Environment\n\nCreate custom environment package:\n\n```ts\n// vitest-environment-custom/index.ts\nimport type { Environment } from 'vitest/runtime'\n\nexport default <Environment>{\n  name: 'custom',\n  viteEnvironment: 'ssr', // or 'client'\n  \n  setup() {\n    // Setup global state\n    globalThis.myGlobal = 'value'\n    \n    return {\n      teardown() {\n        delete globalThis.myGlobal\n      },\n    }\n  },\n}\n```\n\nUse with:\n\n```ts\ndefineConfig({\n  test: {\n    environment: 'custom',\n  },\n})\n```\n\n## Environment with VM\n\nFor full isolation:\n\n```ts\nexport default <Environment>{\n  name: 'isolated',\n  viteEnvironment: 'ssr',\n  \n  async setupVM() {\n    const vm = await import('node:vm')\n    const context = vm.createContext()\n    \n    return {\n      getVmContext() {\n        return context\n      },\n      teardown() {},\n    }\n  },\n  \n  setup() {\n    return { teardown() {} }\n  },\n}\n```\n\n## Browser Mode (Separate from Environments)\n\nFor real browser testing, use Vitest Browser Mode:\n\n```ts\ndefineConfig({\n  test: {\n    browser: {\n      enabled: true,\n      name: 'chromium', // or 'firefox', 'webkit'\n      provider: 'playwright',\n    },\n  },\n})\n```\n\n## CSS and Assets\n\nIn jsdom/happy-dom, configure CSS handling:\n\n```ts\ndefineConfig({\n  test: {\n    css: true, // Process CSS\n    \n    // Or with options\n    css: {\n      include: /\\.module\\.css$/,\n      modules: {\n        classNameStrategy: 'non-scoped',\n      },\n    },\n  },\n})\n```\n\n## Fixing External Dependencies\n\nIf external deps fail with CSS/asset errors:\n\n```ts\ndefineConfig({\n  test: {\n    server: {\n      deps: {\n        inline: ['problematic-package'],\n      },\n    },\n  },\n})\n```\n\n## Key Points\n\n- Default is `node` - no browser APIs\n- Use `jsdom` for full browser simulation\n- Use `happy-dom` for faster tests with basic DOM\n- Per-file environment via `// @vitest-environment` comment\n- Use projects for multiple environment configurations\n- Browser Mode is for real browser testing, not environment\n\n<!-- \nSource references:\n- https://vitest.dev/guide/environment.html\n-->\n", "skills/vitest/references/advanced-projects.md": "---\nname: projects-workspaces\ndescription: Multi-project configuration for monorepos and different test types\n---\n\n# Projects\n\nRun different test configurations in the same Vitest process.\n\n## Basic Projects Setup\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    projects: [\n      // Glob patterns for config files\n      'packages/*',\n      \n      // Inline config\n      {\n        test: {\n          name: 'unit',\n          include: ['tests/unit/**/*.test.ts'],\n          environment: 'node',\n        },\n      },\n      {\n        test: {\n          name: 'integration',\n          include: ['tests/integration/**/*.test.ts'],\n          environment: 'jsdom',\n        },\n      },\n    ],\n  },\n})\n```\n\n## Monorepo Pattern\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      // Each package has its own vitest.config.ts\n      'packages/core',\n      'packages/cli',\n      'packages/utils',\n    ],\n  },\n})\n```\n\nPackage config:\n\n```ts\n// packages/core/vitest.config.ts\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    name: 'core',\n    include: ['src/**/*.test.ts'],\n    environment: 'node',\n  },\n})\n```\n\n## Different Environments\n\nRun same tests in different environments:\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'happy-dom',\n          root: './shared-tests',\n          environment: 'happy-dom',\n          setupFiles: ['./setup.happy-dom.ts'],\n        },\n      },\n      {\n        test: {\n          name: 'node',\n          root: './shared-tests',\n          environment: 'node',\n          setupFiles: ['./setup.node.ts'],\n        },\n      },\n    ],\n  },\n})\n```\n\n## Browser + Node Projects\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'unit',\n          include: ['tests/unit/**/*.test.ts'],\n          environment: 'node',\n        },\n      },\n      {\n        test: {\n          name: 'browser',\n          include: ['tests/browser/**/*.test.ts'],\n          browser: {\n            enabled: true,\n            name: 'chromium',\n            provider: 'playwright',\n          },\n        },\n      },\n    ],\n  },\n})\n```\n\n## Shared Configuration\n\n```ts\n// vitest.shared.ts\nexport const sharedConfig = {\n  testTimeout: 10000,\n  setupFiles: ['./tests/setup.ts'],\n}\n\n// vitest.config.ts\nimport { sharedConfig } from './vitest.shared'\n\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          ...sharedConfig,\n          name: 'unit',\n          include: ['tests/unit/**/*.test.ts'],\n        },\n      },\n      {\n        test: {\n          ...sharedConfig,\n          name: 'e2e',\n          include: ['tests/e2e/**/*.test.ts'],\n        },\n      },\n    ],\n  },\n})\n```\n\n## Project-Specific Dependencies\n\nEach project can have different dependencies inlined:\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'project-a',\n          server: {\n            deps: {\n              inline: ['package-a'],\n            },\n          },\n        },\n      },\n    ],\n  },\n})\n```\n\n## Running Specific Projects\n\n```bash\n# Run specific project\nvitest --project unit\nvitest --project integration\n\n# Multiple projects\nvitest --project unit --project e2e\n\n# Exclude project\nvitest --project.ignore browser\n```\n\n## Providing Values to Projects\n\nShare values from config to tests:\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'staging',\n          provide: {\n            apiUrl: 'https://staging.api.com',\n            debug: true,\n          },\n        },\n      },\n      {\n        test: {\n          name: 'production',\n          provide: {\n            apiUrl: 'https://api.com',\n            debug: false,\n          },\n        },\n      },\n    ],\n  },\n})\n\n// In tests, use inject\nimport { inject } from 'vitest'\n\ntest('uses correct api', () => {\n  const url = inject('apiUrl')\n  expect(url).toContain('api.com')\n})\n```\n\n## With Fixtures\n\n```ts\nconst test = base.extend({\n  apiUrl: ['/default', { injected: true }],\n})\n\ntest('uses injected url', ({ apiUrl }) => {\n  // apiUrl comes from project's provide config\n})\n```\n\n## Project Isolation\n\nEach project runs in its own thread pool by default:\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'isolated',\n          isolate: true, // Full isolation\n          pool: 'forks',\n        },\n      },\n    ],\n  },\n})\n```\n\n## Global Setup per Project\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'with-db',\n          globalSetup: ['./tests/db-setup.ts'],\n        },\n      },\n    ],\n  },\n})\n```\n\n## Key Points\n\n- Projects run in same Vitest process\n- Each project can have different environment, config\n- Use glob patterns for monorepo packages\n- Run specific projects with `--project` flag\n- Use `provide` to inject config values into tests\n- Projects inherit from root config unless overridden\n\n<!-- \nSource references:\n- https://vitest.dev/guide/projects.html\n-->\n", "skills/vitest/references/advanced-type-testing.md": "---\nname: type-testing\ndescription: Test TypeScript types with expectTypeOf and assertType\n---\n\n# Type Testing\n\nTest TypeScript types without runtime execution.\n\n## Setup\n\nType tests use `.test-d.ts` extension:\n\n```ts\n// math.test-d.ts\nimport { expectTypeOf } from 'vitest'\nimport { add } from './math'\n\ntest('add returns number', () => {\n  expectTypeOf(add).returns.toBeNumber()\n})\n```\n\n## Configuration\n\n```ts\ndefineConfig({\n  test: {\n    typecheck: {\n      enabled: true,\n      \n      // Only type check\n      only: false,\n      \n      // Checker: 'tsc' or 'vue-tsc'\n      checker: 'tsc',\n      \n      // Include patterns\n      include: ['**/*.test-d.ts'],\n      \n      // tsconfig to use\n      tsconfig: './tsconfig.json',\n    },\n  },\n})\n```\n\n## expectTypeOf API\n\n```ts\nimport { expectTypeOf } from 'vitest'\n\n// Basic type checks\nexpectTypeOf<string>().toBeString()\nexpectTypeOf<number>().toBeNumber()\nexpectTypeOf<boolean>().toBeBoolean()\nexpectTypeOf<null>().toBeNull()\nexpectTypeOf<undefined>().toBeUndefined()\nexpectTypeOf<void>().toBeVoid()\nexpectTypeOf<never>().toBeNever()\nexpectTypeOf<any>().toBeAny()\nexpectTypeOf<unknown>().toBeUnknown()\nexpectTypeOf<object>().toBeObject()\nexpectTypeOf<Function>().toBeFunction()\nexpectTypeOf<[]>().toBeArray()\nexpectTypeOf<symbol>().toBeSymbol()\n```\n\n## Value Type Checking\n\n```ts\nconst value = 'hello'\nexpectTypeOf(value).toBeString()\n\nconst obj = { name: 'test', count: 42 }\nexpectTypeOf(obj).toMatchTypeOf<{ name: string }>()\nexpectTypeOf(obj).toHaveProperty('name')\n```\n\n## Function Types\n\n```ts\nfunction greet(name: string): string {\n  return `Hello, ${name}`\n}\n\nexpectTypeOf(greet).toBeFunction()\nexpectTypeOf(greet).parameters.toEqualTypeOf<[string]>()\nexpectTypeOf(greet).returns.toBeString()\n\n// Parameter checking\nexpectTypeOf(greet).parameter(0).toBeString()\n```\n\n## Object Types\n\n```ts\ninterface User {\n  id: number\n  name: string\n  email?: string\n}\n\nexpectTypeOf<User>().toHaveProperty('id')\nexpectTypeOf<User>().toHaveProperty('name').toBeString()\n\n// Check shape\nexpectTypeOf({ id: 1, name: 'test' }).toMatchTypeOf<User>()\n```\n\n## Equality vs Matching\n\n```ts\ninterface A { x: number }\ninterface B { x: number; y: string }\n\n// toMatchTypeOf - subset matching\nexpectTypeOf<B>().toMatchTypeOf<A>()  // B extends A\n\n// toEqualTypeOf - exact match\nexpectTypeOf<A>().not.toEqualTypeOf<B>()  // Not exact match\nexpectTypeOf<A>().toEqualTypeOf<{ x: number }>()  // Exact match\n```\n\n## Branded Types\n\n```ts\ntype UserId = number & { __brand: 'UserId' }\ntype PostId = number & { __brand: 'PostId' }\n\nexpectTypeOf<UserId>().not.toEqualTypeOf<PostId>()\nexpectTypeOf<UserId>().not.toEqualTypeOf<number>()\n```\n\n## Generic Types\n\n```ts\nfunction identity<T>(value: T): T {\n  return value\n}\n\nexpectTypeOf(identity<string>).returns.toBeString()\nexpectTypeOf(identity<number>).returns.toBeNumber()\n```\n\n## Nullable Types\n\n```ts\ntype MaybeString = string | null | undefined\n\nexpectTypeOf<MaybeString>().toBeNullable()\nexpectTypeOf<string>().not.toBeNullable()\n```\n\n## assertType\n\nAssert a value matches a type (no assertion at runtime):\n\n```ts\nimport { assertType } from 'vitest'\n\nfunction getUser(): User | null {\n  return { id: 1, name: 'test' }\n}\n\ntest('returns user', () => {\n  const result = getUser()\n  \n  // @ts-expect-error - should fail type check\n  assertType<string>(result)\n  \n  // Correct type\n  assertType<User | null>(result)\n})\n```\n\n## Using @ts-expect-error\n\nTest that code produces type error:\n\n```ts\ntest('rejects wrong types', () => {\n  function requireString(s: string) {}\n  \n  // @ts-expect-error - number not assignable to string\n  requireString(123)\n})\n```\n\n## Running Type Tests\n\n```bash\n# Run type tests\nvitest typecheck\n\n# Run alongside unit tests\nvitest --typecheck\n\n# Type tests only\nvitest --typecheck.only\n```\n\n## Mixed Test Files\n\nCombine runtime and type tests:\n\n```ts\n// user.test.ts\nimport { describe, expect, expectTypeOf, test } from 'vitest'\nimport { createUser } from './user'\n\ndescribe('createUser', () => {\n  test('runtime: creates user', () => {\n    const user = createUser('John')\n    expect(user.name).toBe('John')\n  })\n\n  test('types: returns User type', () => {\n    expectTypeOf(createUser).returns.toMatchTypeOf<{ name: string }>()\n  })\n})\n```\n\n## Key Points\n\n- Use `.test-d.ts` for type-only tests\n- `expectTypeOf` for type assertions\n- `toMatchTypeOf` for subset matching\n- `toEqualTypeOf` for exact type matching\n- Use `@ts-expect-error` to test type errors\n- Run with `vitest typecheck` or `--typecheck`\n\n<!-- \nSource references:\n- https://vitest.dev/guide/testing-types.html\n- https://vitest.dev/api/expect-typeof.html\n-->\n", "skills/vitest/references/advanced-vi.md": "---\nname: vi-utilities\ndescription: vi helper for mocking, timers, utilities\n---\n\n# Vi Utilities\n\nThe `vi` helper provides mocking and utility functions.\n\n```ts\nimport { vi } from 'vitest'\n```\n\n## Mock Functions\n\n```ts\n// Create mock\nconst fn = vi.fn()\nconst fnWithImpl = vi.fn((x) => x * 2)\n\n// Check if mock\nvi.isMockFunction(fn) // true\n\n// Mock methods\nfn.mockReturnValue(42)\nfn.mockReturnValueOnce(1)\nfn.mockResolvedValue(data)\nfn.mockRejectedValue(error)\nfn.mockImplementation(() => 'result')\nfn.mockImplementationOnce(() => 'once')\n\n// Clear/reset\nfn.mockClear()    // Clear call history\nfn.mockReset()    // Clear history + implementation\nfn.mockRestore()  // Restore original (for spies)\n```\n\n## Spying\n\n```ts\nconst obj = { method: () => 'original' }\n\nconst spy = vi.spyOn(obj, 'method')\nobj.method()\n\nexpect(spy).toHaveBeenCalled()\n\n// Mock implementation\nspy.mockReturnValue('mocked')\n\n// Spy on getter/setter\nvi.spyOn(obj, 'prop', 'get').mockReturnValue('value')\n```\n\n## Module Mocking\n\n```ts\n// Hoisted to top of file\nvi.mock('./module', () => ({\n  fn: vi.fn(),\n}))\n\n// Partial mock\nvi.mock('./module', async (importOriginal) => ({\n  ...(await importOriginal()),\n  specificFn: vi.fn(),\n}))\n\n// Spy mode - keep implementation\nvi.mock('./module', { spy: true })\n\n// Import actual module inside mock\nconst actual = await vi.importActual('./module')\n\n// Import as mock\nconst mocked = await vi.importMock('./module')\n```\n\n## Dynamic Mocking\n\n```ts\n// Not hoisted - use with dynamic imports\nvi.doMock('./config', () => ({ key: 'value' }))\nconst config = await import('./config')\n\n// Unmock\nvi.doUnmock('./config')\nvi.unmock('./module') // Hoisted\n```\n\n## Reset Modules\n\n```ts\n// Clear module cache\nvi.resetModules()\n\n// Wait for dynamic imports\nawait vi.dynamicImportSettled()\n```\n\n## Fake Timers\n\n```ts\nvi.useFakeTimers()\n\nsetTimeout(() => console.log('done'), 1000)\n\n// Advance time\nvi.advanceTimersByTime(1000)\nvi.advanceTimersByTimeAsync(1000)  // For async callbacks\nvi.advanceTimersToNextTimer()\nvi.advanceTimersToNextFrame()      // requestAnimationFrame\n\n// Run all timers\nvi.runAllTimers()\nvi.runAllTimersAsync()\nvi.runOnlyPendingTimers()\n\n// Clear timers\nvi.clearAllTimers()\n\n// Check state\nvi.getTimerCount()\nvi.isFakeTimers()\n\n// Restore\nvi.useRealTimers()\n```\n\n## Mock Date/Time\n\n```ts\nvi.setSystemTime(new Date('2024-01-01'))\nexpect(new Date().getFullYear()).toBe(2024)\n\nvi.getMockedSystemTime()  // Get mocked date\nvi.getRealSystemTime()    // Get real time (ms)\n```\n\n## Global/Env Mocking\n\n```ts\n// Stub global\nvi.stubGlobal('fetch', vi.fn())\nvi.unstubAllGlobals()\n\n// Stub environment\nvi.stubEnv('API_KEY', 'test')\nvi.stubEnv('NODE_ENV', 'test')\nvi.unstubAllEnvs()\n```\n\n## Hoisted Code\n\nRun code before imports:\n\n```ts\nconst mock = vi.hoisted(() => vi.fn())\n\nvi.mock('./module', () => ({\n  fn: mock, // Can reference hoisted variable\n}))\n```\n\n## Waiting Utilities\n\n```ts\n// Wait for callback to succeed\nawait vi.waitFor(async () => {\n  const el = document.querySelector('.loaded')\n  expect(el).toBeTruthy()\n}, { timeout: 5000, interval: 100 })\n\n// Wait for truthy value\nconst element = await vi.waitUntil(\n  () => document.querySelector('.loaded'),\n  { timeout: 5000 }\n)\n```\n\n## Mock Object\n\nMock all methods of an object:\n\n```ts\nconst original = {\n  method: () => 'real',\n  nested: { fn: () => 'nested' },\n}\n\nconst mocked = vi.mockObject(original)\nmocked.method()  // undefined (mocked)\nmocked.method.mockReturnValue('mocked')\n\n// Spy mode\nconst spied = vi.mockObject(original, { spy: true })\nspied.method()  // 'real'\nexpect(spied.method).toHaveBeenCalled()\n```\n\n## Test Configuration\n\n```ts\nvi.setConfig({\n  testTimeout: 10_000,\n  hookTimeout: 10_000,\n})\n\nvi.resetConfig()\n```\n\n## Global Mock Management\n\n```ts\nvi.clearAllMocks()   // Clear all mock call history\nvi.resetAllMocks()   // Reset + clear implementation\nvi.restoreAllMocks() // Restore originals (spies)\n```\n\n## vi.mocked Type Helper\n\nTypeScript helper for mocked values:\n\n```ts\nimport { myFn } from './module'\nvi.mock('./module')\n\n// Type as mock\nvi.mocked(myFn).mockReturnValue('typed')\n\n// Deep mocking\nvi.mocked(myModule, { deep: true })\n\n// Partial mock typing\nvi.mocked(fn, { partial: true }).mockResolvedValue({ ok: true })\n```\n\n## Key Points\n\n- `vi.mock` is hoisted - use `vi.doMock` for dynamic mocking\n- `vi.hoisted` lets you reference variables in mock factories\n- Use `vi.spyOn` to spy on existing methods\n- Fake timers require explicit setup and teardown\n- `vi.waitFor` retries until assertion passes\n\n<!-- \nSource references:\n- https://vitest.dev/api/vi.html\n-->\n", "skills/vitest/references/core-cli.md": "---\nname: vitest-cli\ndescription: Command line interface commands and options\n---\n\n# Command Line Interface\n\n## Commands\n\n### `vitest`\n\nStart Vitest in watch mode (dev) or run mode (CI):\n\n```bash\nvitest                    # Watch mode in dev, run mode in CI\nvitest foobar             # Run tests containing \"foobar\" in path\nvitest basic/foo.test.ts:10  # Run specific test by file and line number\n```\n\n### `vitest run`\n\nRun tests once without watch mode:\n\n```bash\nvitest run\nvitest run --coverage\n```\n\n### `vitest watch`\n\nExplicitly start watch mode:\n\n```bash\nvitest watch\n```\n\n### `vitest related`\n\nRun tests that import specific files (useful with lint-staged):\n\n```bash\nvitest related src/index.ts src/utils.ts --run\n```\n\n### `vitest bench`\n\nRun only benchmark tests:\n\n```bash\nvitest bench\n```\n\n### `vitest list`\n\nList all matching tests without running them:\n\n```bash\nvitest list                    # List test names\nvitest list --json             # Output as JSON\nvitest list --filesOnly        # List only test files\n```\n\n### `vitest init`\n\nInitialize project setup:\n\n```bash\nvitest init browser            # Set up browser testing\n```\n\n## Common Options\n\n```bash\n# Configuration\n--config <path>           # Path to config file\n--project <name>          # Run specific project\n\n# Filtering\n--testNamePattern, -t     # Run tests matching pattern\n--changed                 # Run tests for changed files\n--changed HEAD~1          # Tests for last commit changes\n\n# Reporters\n--reporter <name>         # default, verbose, dot, json, html\n--reporter=html --outputFile=report.html\n\n# Coverage\n--coverage                # Enable coverage\n--coverage.provider v8    # Use v8 provider\n--coverage.reporter text,html\n\n# Execution\n--shard <index>/<count>   # Split tests across machines\n--bail <n>                # Stop after n failures\n--retry <n>               # Retry failed tests n times\n--sequence.shuffle        # Randomize test order\n\n# Watch mode\n--no-watch                # Disable watch mode\n--standalone              # Start without running tests\n\n# Environment\n--environment <env>       # jsdom, happy-dom, node\n--globals                 # Enable global APIs\n\n# Debugging\n--inspect                 # Enable Node inspector\n--inspect-brk             # Break on start\n\n# Output\n--silent                  # Suppress console output\n--no-color                # Disable colors\n```\n\n## Package.json Scripts\n\n```json\n{\n  \"scripts\": {\n    \"test\": \"vitest\",\n    \"test:run\": \"vitest run\",\n    \"test:ui\": \"vitest --ui\",\n    \"coverage\": \"vitest run --coverage\"\n  }\n}\n```\n\n## Sharding for CI\n\nSplit tests across multiple machines:\n\n```bash\n# Machine 1\nvitest run --shard=1/3 --reporter=blob\n\n# Machine 2\nvitest run --shard=2/3 --reporter=blob\n\n# Machine 3\nvitest run --shard=3/3 --reporter=blob\n\n# Merge reports\nvitest --merge-reports --reporter=junit\n```\n\n## Watch Mode Keyboard Shortcuts\n\nIn watch mode, press:\n- `a` - Run all tests\n- `f` - Run only failed tests\n- `u` - Update snapshots\n- `p` - Filter by filename pattern\n- `t` - Filter by test name pattern\n- `q` - Quit\n\n## Key Points\n\n- Watch mode is default in dev, run mode in CI (when `process.env.CI` is set)\n- Use `--run` flag to ensure single run (important for lint-staged)\n- Both camelCase (`--testTimeout`) and kebab-case (`--test-timeout`) work\n- Boolean options can be negated with `--no-` prefix\n\n<!-- \nSource references:\n- https://vitest.dev/guide/cli.html\n-->\n", "skills/vitest/references/core-config.md": "---\nname: vitest-configuration\ndescription: Configure Vitest with vite.config.ts or vitest.config.ts\n---\n\n# Configuration\n\nVitest reads configuration from `vitest.config.ts` or `vite.config.ts`. It shares the same config format as Vite.\n\n## Basic Setup\n\n```ts\n// vitest.config.ts\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    // test options\n  },\n})\n```\n\n## Using with Existing Vite Config\n\nAdd Vitest types reference and use the `test` property:\n\n```ts\n// vite.config.ts\n/// <reference types=\"vitest/config\" />\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    environment: 'jsdom',\n  },\n})\n```\n\n## Merging Configs\n\nIf you have separate config files, use `mergeConfig`:\n\n```ts\n// vitest.config.ts\nimport { defineConfig, mergeConfig } from 'vitest/config'\nimport viteConfig from './vite.config'\n\nexport default mergeConfig(viteConfig, defineConfig({\n  test: {\n    environment: 'jsdom',\n  },\n}))\n```\n\n## Common Options\n\n```ts\ndefineConfig({\n  test: {\n    // Enable global APIs (describe, it, expect) without imports\n    globals: true,\n    \n    // Test environment: 'node', 'jsdom', 'happy-dom'\n    environment: 'node',\n    \n    // Setup files to run before each test file\n    setupFiles: ['./tests/setup.ts'],\n    \n    // Include patterns for test files\n    include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],\n    \n    // Exclude patterns\n    exclude: ['**/node_modules/**', '**/dist/**'],\n    \n    // Test timeout in ms\n    testTimeout: 5000,\n    \n    // Hook timeout in ms\n    hookTimeout: 10000,\n    \n    // Enable watch mode by default\n    watch: true,\n    \n    // Coverage configuration\n    coverage: {\n      provider: 'v8', // or 'istanbul'\n      reporter: ['text', 'html'],\n      include: ['src/**/*.ts'],\n    },\n    \n    // Run tests in isolation (each file in separate process)\n    isolate: true,\n    \n    // Pool for running tests: 'threads', 'forks', 'vmThreads'\n    pool: 'threads',\n    \n    // Number of threads/processes\n    poolOptions: {\n      threads: {\n        maxThreads: 4,\n        minThreads: 1,\n      },\n    },\n    \n    // Automatically clear mocks between tests\n    clearMocks: true,\n    \n    // Restore mocks between tests\n    restoreMocks: true,\n    \n    // Retry failed tests\n    retry: 0,\n    \n    // Stop after first failure\n    bail: 0,\n  },\n})\n```\n\n## Conditional Configuration\n\nUse `mode` or `process.env.VITEST` for test-specific config:\n\n```ts\nexport default defineConfig(({ mode }) => ({\n  plugins: mode === 'test' ? [] : [myPlugin()],\n  test: {\n    // test options\n  },\n}))\n```\n\n## Projects (Monorepos)\n\nRun different configurations in the same Vitest process:\n\n```ts\ndefineConfig({\n  test: {\n    projects: [\n      'packages/*',\n      {\n        test: {\n          name: 'unit',\n          include: ['tests/unit/**/*.test.ts'],\n          environment: 'node',\n        },\n      },\n      {\n        test: {\n          name: 'integration',\n          include: ['tests/integration/**/*.test.ts'],\n          environment: 'jsdom',\n        },\n      },\n    ],\n  },\n})\n```\n\n## Key Points\n\n- Vitest uses Vite's transformation pipeline - same `resolve.alias`, plugins work\n- `vitest.config.ts` takes priority over `vite.config.ts`\n- Use `--config` flag to specify a custom config path\n- `process.env.VITEST` is set to `true` when running tests\n- Test config uses `test` property, rest is Vite config\n\n<!-- \nSource references:\n- https://vitest.dev/guide/#configuring-vitest\n- https://vitest.dev/config/\n-->\n", "skills/vitest/references/core-describe.md": "---\nname: describe-api\ndescription: describe/suite for grouping tests into logical blocks\n---\n\n# Describe API\n\nGroup related tests into suites for organization and shared setup.\n\n## Basic Usage\n\n```ts\nimport { describe, expect, test } from 'vitest'\n\ndescribe('Math', () => {\n  test('adds numbers', () => {\n    expect(1 + 1).toBe(2)\n  })\n\n  test('subtracts numbers', () => {\n    expect(3 - 1).toBe(2)\n  })\n})\n\n// Alias: suite\nimport { suite } from 'vitest'\nsuite('equivalent to describe', () => {})\n```\n\n## Nested Suites\n\n```ts\ndescribe('User', () => {\n  describe('when logged in', () => {\n    test('shows dashboard', () => {})\n    test('can update profile', () => {})\n  })\n\n  describe('when logged out', () => {\n    test('shows login page', () => {})\n  })\n})\n```\n\n## Suite Options\n\n```ts\n// All tests inherit options\ndescribe('slow tests', { timeout: 30_000 }, () => {\n  test('test 1', () => {}) // 30s timeout\n  test('test 2', () => {}) // 30s timeout\n})\n```\n\n## Suite Modifiers\n\n### Skip Suites\n\n```ts\ndescribe.skip('skipped suite', () => {\n  test('wont run', () => {})\n})\n\n// Conditional\ndescribe.skipIf(process.env.CI)('not in CI', () => {})\ndescribe.runIf(!process.env.CI)('only local', () => {})\n```\n\n### Focus Suites\n\n```ts\ndescribe.only('only this suite runs', () => {\n  test('runs', () => {})\n})\n```\n\n### Todo Suites\n\n```ts\ndescribe.todo('implement later')\n```\n\n### Concurrent Suites\n\n```ts\n// All tests run in parallel\ndescribe.concurrent('parallel tests', () => {\n  test('test 1', async ({ expect }) => {})\n  test('test 2', async ({ expect }) => {})\n})\n```\n\n### Sequential in Concurrent\n\n```ts\ndescribe.concurrent('parallel', () => {\n  test('concurrent 1', async () => {})\n  \n  describe.sequential('must be sequential', () => {\n    test('step 1', async () => {})\n    test('step 2', async () => {})\n  })\n})\n```\n\n### Shuffle Tests\n\n```ts\ndescribe.shuffle('random order', () => {\n  test('test 1', () => {})\n  test('test 2', () => {})\n  test('test 3', () => {})\n})\n\n// Or with option\ndescribe('random', { shuffle: true }, () => {})\n```\n\n## Parameterized Suites\n\n### describe.each\n\n```ts\ndescribe.each([\n  { name: 'Chrome', version: 100 },\n  { name: 'Firefox', version: 90 },\n])('$name browser', ({ name, version }) => {\n  test('has version', () => {\n    expect(version).toBeGreaterThan(0)\n  })\n})\n```\n\n### describe.for\n\n```ts\ndescribe.for([\n  ['Chrome', 100],\n  ['Firefox', 90],\n])('%s browser', ([name, version]) => {\n  test('has version', () => {\n    expect(version).toBeGreaterThan(0)\n  })\n})\n```\n\n## Hooks in Suites\n\n```ts\ndescribe('Database', () => {\n  let db\n\n  beforeAll(async () => {\n    db = await createDb()\n  })\n\n  afterAll(async () => {\n    await db.close()\n  })\n\n  beforeEach(async () => {\n    await db.clear()\n  })\n\n  test('insert works', async () => {\n    await db.insert({ name: 'test' })\n    expect(await db.count()).toBe(1)\n  })\n})\n```\n\n## Modifier Combinations\n\nAll modifiers can be chained:\n\n```ts\ndescribe.skip.concurrent('skipped concurrent', () => {})\ndescribe.only.shuffle('only and shuffled', () => {})\ndescribe.concurrent.skip('equivalent', () => {})\n```\n\n## Key Points\n\n- Top-level tests belong to an implicit file suite\n- Nested suites inherit parent's options (timeout, retry, etc.)\n- Hooks are scoped to their suite and nested suites\n- Use `describe.concurrent` with context's `expect` for snapshots\n- Shuffle order depends on `sequence.seed` config\n\n<!-- \nSource references:\n- https://vitest.dev/api/describe.html\n-->\n", "skills/vitest/references/core-expect.md": "---\nname: expect-api\ndescription: Assertions with matchers, asymmetric matchers, and custom matchers\n---\n\n# Expect API\n\nVitest uses Chai assertions with Jest-compatible API.\n\n## Basic Assertions\n\n```ts\nimport { expect, test } from 'vitest'\n\ntest('assertions', () => {\n  // Equality\n  expect(1 + 1).toBe(2)              // Strict equality (===)\n  expect({ a: 1 }).toEqual({ a: 1 }) // Deep equality\n\n  // Truthiness\n  expect(true).toBeTruthy()\n  expect(false).toBeFalsy()\n  expect(null).toBeNull()\n  expect(undefined).toBeUndefined()\n  expect('value').toBeDefined()\n\n  // Numbers\n  expect(10).toBeGreaterThan(5)\n  expect(10).toBeGreaterThanOrEqual(10)\n  expect(5).toBeLessThan(10)\n  expect(0.1 + 0.2).toBeCloseTo(0.3, 5)\n\n  // Strings\n  expect('hello world').toMatch(/world/)\n  expect('hello').toContain('ell')\n\n  // Arrays\n  expect([1, 2, 3]).toContain(2)\n  expect([{ a: 1 }]).toContainEqual({ a: 1 })\n  expect([1, 2, 3]).toHaveLength(3)\n\n  // Objects\n  expect({ a: 1, b: 2 }).toHaveProperty('a')\n  expect({ a: 1, b: 2 }).toHaveProperty('a', 1)\n  expect({ a: { b: 1 } }).toHaveProperty('a.b', 1)\n  expect({ a: 1 }).toMatchObject({ a: 1 })\n\n  // Types\n  expect('string').toBeTypeOf('string')\n  expect(new Date()).toBeInstanceOf(Date)\n})\n```\n\n## Negation\n\n```ts\nexpect(1).not.toBe(2)\nexpect({ a: 1 }).not.toEqual({ a: 2 })\n```\n\n## Error Assertions\n\n```ts\n// Sync errors - wrap in function\nexpect(() => throwError()).toThrow()\nexpect(() => throwError()).toThrow('message')\nexpect(() => throwError()).toThrow(/pattern/)\nexpect(() => throwError()).toThrow(CustomError)\n\n// Async errors - use rejects\nawait expect(asyncThrow()).rejects.toThrow('error')\n```\n\n## Promise Assertions\n\n```ts\n// Resolves\nawait expect(Promise.resolve(1)).resolves.toBe(1)\nawait expect(fetchData()).resolves.toEqual({ data: true })\n\n// Rejects\nawait expect(Promise.reject('error')).rejects.toBe('error')\nawait expect(failingFetch()).rejects.toThrow()\n```\n\n## Spy/Mock Assertions\n\n```ts\nconst fn = vi.fn()\nfn('arg1', 'arg2')\nfn('arg3')\n\nexpect(fn).toHaveBeenCalled()\nexpect(fn).toHaveBeenCalledTimes(2)\nexpect(fn).toHaveBeenCalledWith('arg1', 'arg2')\nexpect(fn).toHaveBeenLastCalledWith('arg3')\nexpect(fn).toHaveBeenNthCalledWith(1, 'arg1', 'arg2')\n\nexpect(fn).toHaveReturned()\nexpect(fn).toHaveReturnedWith(value)\n```\n\n## Asymmetric Matchers\n\nUse inside `toEqual`, `toHaveBeenCalledWith`, etc:\n\n```ts\nexpect({ id: 1, name: 'test' }).toEqual({\n  id: expect.any(Number),\n  name: expect.any(String),\n})\n\nexpect({ a: 1, b: 2, c: 3 }).toEqual(\n  expect.objectContaining({ a: 1 })\n)\n\nexpect([1, 2, 3, 4]).toEqual(\n  expect.arrayContaining([1, 3])\n)\n\nexpect('hello world').toEqual(\n  expect.stringContaining('world')\n)\n\nexpect('hello world').toEqual(\n  expect.stringMatching(/world$/)\n)\n\nexpect({ value: null }).toEqual({\n  value: expect.anything() // Matches anything except null/undefined\n})\n\n// Negate with expect.not\nexpect([1, 2]).toEqual(\n  expect.not.arrayContaining([3])\n)\n```\n\n## Soft Assertions\n\nContinue test after failure:\n\n```ts\nexpect.soft(1).toBe(2) // Marks test failed but continues\nexpect.soft(2).toBe(3) // Also runs\n// All failures reported at end\n```\n\n## Poll Assertions\n\nRetry until passes:\n\n```ts\nawait expect.poll(() => fetchStatus()).toBe('ready')\n\nawait expect.poll(\n  () => document.querySelector('.element'),\n  { interval: 100, timeout: 5000 }\n).toBeTruthy()\n```\n\n## Assertion Count\n\n```ts\ntest('async assertions', async () => {\n  expect.assertions(2) // Exactly 2 assertions must run\n  \n  await doAsync((data) => {\n    expect(data).toBeDefined()\n    expect(data.id).toBe(1)\n  })\n})\n\ntest('at least one', () => {\n  expect.hasAssertions() // At least 1 assertion must run\n})\n```\n\n## Extending Matchers\n\n```ts\nexpect.extend({\n  toBeWithinRange(received, floor, ceiling) {\n    const pass = received >= floor && received <= ceiling\n    return {\n      pass,\n      message: () => \n        `expected ${received} to be within range ${floor} - ${ceiling}`,\n    }\n  },\n})\n\ntest('custom matcher', () => {\n  expect(100).toBeWithinRange(90, 110)\n})\n```\n\n## Snapshot Assertions\n\n```ts\nexpect(data).toMatchSnapshot()\nexpect(data).toMatchInlineSnapshot(`{ \"id\": 1 }`)\nawait expect(result).toMatchFileSnapshot('./expected.json')\n\nexpect(() => throw new Error('fail')).toThrowErrorMatchingSnapshot()\n```\n\n## Key Points\n\n- Use `toBe` for primitives, `toEqual` for objects/arrays\n- `toStrictEqual` checks undefined properties and array sparseness\n- Always `await` async assertions (`resolves`, `rejects`, `poll`)\n- Use context's `expect` in concurrent tests for correct tracking\n- `toThrow` requires wrapping sync code in a function\n\n<!-- \nSource references:\n- https://vitest.dev/api/expect.html\n-->\n", "skills/vitest/references/core-hooks.md": "---\nname: lifecycle-hooks\ndescription: beforeEach, afterEach, beforeAll, afterAll, and around hooks\n---\n\n# Lifecycle Hooks\n\n## Basic Hooks\n\n```ts\nimport { afterAll, afterEach, beforeAll, beforeEach, test } from 'vitest'\n\nbeforeAll(async () => {\n  // Runs once before all tests in file/suite\n  await setupDatabase()\n})\n\nafterAll(async () => {\n  // Runs once after all tests in file/suite\n  await teardownDatabase()\n})\n\nbeforeEach(async () => {\n  // Runs before each test\n  await clearTestData()\n})\n\nafterEach(async () => {\n  // Runs after each test\n  await cleanupMocks()\n})\n```\n\n## Cleanup Return Pattern\n\nReturn cleanup function from `before*` hooks:\n\n```ts\nbeforeAll(async () => {\n  const server = await startServer()\n  \n  // Returned function runs as afterAll\n  return async () => {\n    await server.close()\n  }\n})\n\nbeforeEach(async () => {\n  const connection = await connect()\n  \n  // Runs as afterEach\n  return () => connection.close()\n})\n```\n\n## Scoped Hooks\n\nHooks apply to current suite and nested suites:\n\n```ts\ndescribe('outer', () => {\n  beforeEach(() => console.log('outer before'))\n  \n  test('test 1', () => {}) // outer before → test\n  \n  describe('inner', () => {\n    beforeEach(() => console.log('inner before'))\n    \n    test('test 2', () => {}) // outer before → inner before → test\n  })\n})\n```\n\n## Hook Timeout\n\n```ts\nbeforeAll(async () => {\n  await slowSetup()\n}, 30_000) // 30 second timeout\n```\n\n## Around Hooks\n\nWrap tests with setup/teardown context:\n\n```ts\nimport { aroundEach, test } from 'vitest'\n\n// Wrap each test in database transaction\naroundEach(async (runTest) => {\n  await db.beginTransaction()\n  await runTest() // Must be called!\n  await db.rollback()\n})\n\ntest('insert user', async () => {\n  await db.insert({ name: 'Alice' })\n  // Automatically rolled back after test\n})\n```\n\n### aroundAll\n\nWrap entire suite:\n\n```ts\nimport { aroundAll, test } from 'vitest'\n\naroundAll(async (runSuite) => {\n  console.log('before all tests')\n  await runSuite() // Must be called!\n  console.log('after all tests')\n})\n```\n\n### Multiple Around Hooks\n\nNested like onion layers:\n\n```ts\naroundEach(async (runTest) => {\n  console.log('outer before')\n  await runTest()\n  console.log('outer after')\n})\n\naroundEach(async (runTest) => {\n  console.log('inner before')\n  await runTest()\n  console.log('inner after')\n})\n\n// Order: outer before → inner before → test → inner after → outer after\n```\n\n## Test Hooks\n\nInside test body:\n\n```ts\nimport { onTestFailed, onTestFinished, test } from 'vitest'\n\ntest('with cleanup', () => {\n  const db = connect()\n  \n  // Runs after test finishes (pass or fail)\n  onTestFinished(() => db.close())\n  \n  // Only runs if test fails\n  onTestFailed(({ task }) => {\n    console.log('Failed:', task.result?.errors)\n  })\n  \n  db.query('SELECT * FROM users')\n})\n```\n\n### Reusable Cleanup Pattern\n\n```ts\nfunction useTestDb() {\n  const db = connect()\n  onTestFinished(() => db.close())\n  return db\n}\n\ntest('query users', () => {\n  const db = useTestDb()\n  expect(db.query('SELECT * FROM users')).toBeDefined()\n})\n\ntest('query orders', () => {\n  const db = useTestDb() // Fresh connection, auto-closed\n  expect(db.query('SELECT * FROM orders')).toBeDefined()\n})\n```\n\n## Concurrent Test Hooks\n\nFor concurrent tests, use context's hooks:\n\n```ts\ntest.concurrent('concurrent', ({ onTestFinished }) => {\n  const resource = allocate()\n  onTestFinished(() => resource.release())\n})\n```\n\n## Extended Test Hooks\n\nWith `test.extend`, hooks are type-aware:\n\n```ts\nconst test = base.extend<{ db: Database }>({\n  db: async ({}, use) => {\n    const db = await createDb()\n    await use(db)\n    await db.close()\n  },\n})\n\n// These hooks know about `db` fixture\ntest.beforeEach(({ db }) => {\n  db.seed()\n})\n\ntest.afterEach(({ db }) => {\n  db.clear()\n})\n```\n\n## Hook Execution Order\n\nDefault order (stack):\n1. `beforeAll` (in order)\n2. `beforeEach` (in order)\n3. Test\n4. `afterEach` (reverse order)\n5. `afterAll` (reverse order)\n\nConfigure with `sequence.hooks`:\n\n```ts\ndefineConfig({\n  test: {\n    sequence: {\n      hooks: 'list', // 'stack' (default), 'list', 'parallel'\n    },\n  },\n})\n```\n\n## Key Points\n\n- Hooks are not called during type checking\n- Return cleanup function from `before*` to avoid `after*` duplication\n- `aroundEach`/`aroundAll` must call `runTest()`/`runSuite()`\n- `onTestFinished` always runs, even if test fails\n- Use context hooks for concurrent tests\n\n<!-- \nSource references:\n- https://vitest.dev/api/hooks.html\n-->\n", "skills/vitest/references/core-test-api.md": "---\nname: test-api\ndescription: test/it function for defining tests with modifiers\n---\n\n# Test API\n\n## Basic Test\n\n```ts\nimport { expect, test } from 'vitest'\n\ntest('adds numbers', () => {\n  expect(1 + 1).toBe(2)\n})\n\n// Alias: it\nimport { it } from 'vitest'\n\nit('works the same', () => {\n  expect(true).toBe(true)\n})\n```\n\n## Async Tests\n\n```ts\ntest('async test', async () => {\n  const result = await fetchData()\n  expect(result).toBeDefined()\n})\n\n// Promises are automatically awaited\ntest('returns promise', () => {\n  return fetchData().then(result => {\n    expect(result).toBeDefined()\n  })\n})\n```\n\n## Test Options\n\n```ts\n// Timeout (default: 5000ms)\ntest('slow test', async () => {\n  // ...\n}, 10_000)\n\n// Or with options object\ntest('with options', { timeout: 10_000, retry: 2 }, async () => {\n  // ...\n})\n```\n\n## Test Modifiers\n\n### Skip Tests\n\n```ts\ntest.skip('skipped test', () => {\n  // Won't run\n})\n\n// Conditional skip\ntest.skipIf(process.env.CI)('not in CI', () => {})\ntest.runIf(process.env.CI)('only in CI', () => {})\n\n// Dynamic skip via context\ntest('dynamic skip', ({ skip }) => {\n  skip(someCondition, 'reason')\n  // ...\n})\n```\n\n### Focus Tests\n\n```ts\ntest.only('only this runs', () => {\n  // Other tests in file are skipped\n})\n```\n\n### Todo Tests\n\n```ts\ntest.todo('implement later')\n\ntest.todo('with body', () => {\n  // Not run, shows in report\n})\n```\n\n### Failing Tests\n\n```ts\ntest.fails('expected to fail', () => {\n  expect(1).toBe(2) // Test passes because assertion fails\n})\n```\n\n### Concurrent Tests\n\n```ts\n// Run tests in parallel\ntest.concurrent('test 1', async ({ expect }) => {\n  // Use context.expect for concurrent tests\n  expect(await fetch1()).toBe('result')\n})\n\ntest.concurrent('test 2', async ({ expect }) => {\n  expect(await fetch2()).toBe('result')\n})\n```\n\n### Sequential Tests\n\n```ts\n// Force sequential in concurrent context\ntest.sequential('must run alone', async () => {})\n```\n\n## Parameterized Tests\n\n### test.each\n\n```ts\ntest.each([\n  [1, 1, 2],\n  [1, 2, 3],\n  [2, 1, 3],\n])('add(%i, %i) = %i', (a, b, expected) => {\n  expect(a + b).toBe(expected)\n})\n\n// With objects\ntest.each([\n  { a: 1, b: 1, expected: 2 },\n  { a: 1, b: 2, expected: 3 },\n])('add($a, $b) = $expected', ({ a, b, expected }) => {\n  expect(a + b).toBe(expected)\n})\n\n// Template literal\ntest.each`\n  a    | b    | expected\n  ${1} | ${1} | ${2}\n  ${1} | ${2} | ${3}\n`('add($a, $b) = $expected', ({ a, b, expected }) => {\n  expect(a + b).toBe(expected)\n})\n```\n\n### test.for\n\nPreferred over `.each` - doesn't spread arrays:\n\n```ts\ntest.for([\n  [1, 1, 2],\n  [1, 2, 3],\n])('add(%i, %i) = %i', ([a, b, expected], { expect }) => {\n  // Second arg is TestContext\n  expect(a + b).toBe(expected)\n})\n```\n\n## Test Context\n\nFirst argument provides context utilities:\n\n```ts\ntest('with context', ({ expect, skip, task }) => {\n  console.log(task.name)   // Test name\n  skip(someCondition)      // Skip dynamically\n  expect(1).toBe(1)        // Context-bound expect\n})\n```\n\n## Custom Test with Fixtures\n\n```ts\nimport { test as base } from 'vitest'\n\nconst test = base.extend({\n  db: async ({}, use) => {\n    const db = await createDb()\n    await use(db)\n    await db.close()\n  },\n})\n\ntest('query', async ({ db }) => {\n  const users = await db.query('SELECT * FROM users')\n  expect(users).toBeDefined()\n})\n```\n\n## Retry Configuration\n\n```ts\ntest('flaky test', { retry: 3 }, async () => {\n  // Retries up to 3 times on failure\n})\n\n// Advanced retry options\ntest('with delay', {\n  retry: {\n    count: 3,\n    delay: 1000,\n    condition: /timeout/i, // Only retry on timeout errors\n  },\n}, async () => {})\n```\n\n## Tags\n\n```ts\ntest('database test', { tags: ['db', 'slow'] }, async () => {})\n\n// Run with: vitest --tags db\n```\n\n## Key Points\n\n- Tests with no body are marked as `todo`\n- `test.only` throws in CI unless `allowOnly: true`\n- Use context's `expect` for concurrent tests and snapshots\n- Function name is used as test name if passed as first arg\n\n<!-- \nSource references:\n- https://vitest.dev/api/test.html\n-->\n", "skills/vitest/references/features-concurrency.md": "---\nname: concurrency-parallelism\ndescription: Concurrent tests, parallel execution, and sharding\n---\n\n# Concurrency & Parallelism\n\n## File Parallelism\n\nBy default, Vitest runs test files in parallel across workers:\n\n```ts\ndefineConfig({\n  test: {\n    // Run files in parallel (default: true)\n    fileParallelism: true,\n    \n    // Number of worker threads\n    maxWorkers: 4,\n    minWorkers: 1,\n    \n    // Pool type: 'threads', 'forks', 'vmThreads'\n    pool: 'threads',\n  },\n})\n```\n\n## Concurrent Tests\n\nRun tests within a file in parallel:\n\n```ts\n// Individual concurrent tests\ntest.concurrent('test 1', async ({ expect }) => {\n  expect(await fetch1()).toBe('result')\n})\n\ntest.concurrent('test 2', async ({ expect }) => {\n  expect(await fetch2()).toBe('result')\n})\n\n// All tests in suite concurrent\ndescribe.concurrent('parallel suite', () => {\n  test('test 1', async ({ expect }) => {})\n  test('test 2', async ({ expect }) => {})\n})\n```\n\n**Important:** Use `{ expect }` from context for concurrent tests.\n\n## Sequential in Concurrent Context\n\nForce sequential execution:\n\n```ts\ndescribe.concurrent('mostly parallel', () => {\n  test('parallel 1', async () => {})\n  test('parallel 2', async () => {})\n  \n  test.sequential('must run alone 1', async () => {})\n  test.sequential('must run alone 2', async () => {})\n})\n\n// Or entire suite\ndescribe.sequential('sequential suite', () => {\n  test('first', () => {})\n  test('second', () => {})\n})\n```\n\n## Max Concurrency\n\nLimit concurrent tests:\n\n```ts\ndefineConfig({\n  test: {\n    maxConcurrency: 5, // Max concurrent tests per file\n  },\n})\n```\n\n## Isolation\n\nEach file runs in isolated environment by default:\n\n```ts\ndefineConfig({\n  test: {\n    // Disable isolation for faster runs (less safe)\n    isolate: false,\n  },\n})\n```\n\n## Sharding\n\nSplit tests across machines:\n\n```bash\n# Machine 1\nvitest run --shard=1/3\n\n# Machine 2\nvitest run --shard=2/3\n\n# Machine 3\nvitest run --shard=3/3\n```\n\n### CI Example (GitHub Actions)\n\n```yaml\njobs:\n  test:\n    strategy:\n      matrix:\n        shard: [1, 2, 3]\n    steps:\n      - run: vitest run --shard=${{ matrix.shard }}/3 --reporter=blob\n      \n  merge:\n    needs: test\n    steps:\n      - run: vitest --merge-reports --reporter=junit\n```\n\n### Merge Reports\n\n```bash\n# Each shard outputs blob\nvitest run --shard=1/3 --reporter=blob --coverage\nvitest run --shard=2/3 --reporter=blob --coverage\n\n# Merge all blobs\nvitest --merge-reports --reporter=json --coverage\n```\n\n## Test Sequence\n\nControl test order:\n\n```ts\ndefineConfig({\n  test: {\n    sequence: {\n      // Run tests in random order\n      shuffle: true,\n      \n      // Seed for reproducible shuffle\n      seed: 12345,\n      \n      // Hook execution order\n      hooks: 'stack', // 'stack', 'list', 'parallel'\n      \n      // All tests concurrent by default\n      concurrent: true,\n    },\n  },\n})\n```\n\n## Shuffle Tests\n\nRandomize to catch hidden dependencies:\n\n```ts\n// Via CLI\nvitest --sequence.shuffle\n\n// Per suite\ndescribe.shuffle('random order', () => {\n  test('test 1', () => {})\n  test('test 2', () => {})\n  test('test 3', () => {})\n})\n```\n\n## Pool Options\n\n### Threads (Default)\n\n```ts\ndefineConfig({\n  test: {\n    pool: 'threads',\n    poolOptions: {\n      threads: {\n        maxThreads: 8,\n        minThreads: 2,\n        isolate: true,\n      },\n    },\n  },\n})\n```\n\n### Forks\n\nBetter isolation, slower:\n\n```ts\ndefineConfig({\n  test: {\n    pool: 'forks',\n    poolOptions: {\n      forks: {\n        maxForks: 4,\n        isolate: true,\n      },\n    },\n  },\n})\n```\n\n### VM Threads\n\nFull VM isolation per file:\n\n```ts\ndefineConfig({\n  test: {\n    pool: 'vmThreads',\n  },\n})\n```\n\n## Bail on Failure\n\nStop after first failure:\n\n```bash\nvitest --bail 1    # Stop after 1 failure\nvitest --bail      # Stop on first failure (same as --bail 1)\n```\n\n## Key Points\n\n- Files run in parallel by default\n- Use `.concurrent` for parallel tests within file\n- Always use context's `expect` in concurrent tests\n- Sharding splits tests across CI machines\n- Use `--merge-reports` to combine sharded results\n- Shuffle tests to find hidden dependencies\n\n<!-- \nSource references:\n- https://vitest.dev/guide/features.html#running-tests-concurrently\n- https://vitest.dev/guide/improving-performance.html\n-->\n", "skills/vitest/references/features-context.md": "---\nname: test-context-fixtures\ndescription: Test context, custom fixtures with test.extend\n---\n\n# Test Context & Fixtures\n\n## Built-in Context\n\nEvery test receives context as first argument:\n\n```ts\ntest('context', ({ task, expect, skip }) => {\n  console.log(task.name)  // Test name\n  expect(1).toBe(1)       // Context-bound expect\n  skip()                  // Skip test dynamically\n})\n```\n\n### Context Properties\n\n- `task` - Test metadata (name, file, etc.)\n- `expect` - Expect bound to this test (important for concurrent tests)\n- `skip(condition?, message?)` - Skip the test\n- `onTestFinished(fn)` - Cleanup after test\n- `onTestFailed(fn)` - Run on failure only\n\n## Custom Fixtures with test.extend\n\nCreate reusable test utilities:\n\n```ts\nimport { test as base } from 'vitest'\n\n// Define fixture types\ninterface Fixtures {\n  db: Database\n  user: User\n}\n\n// Create extended test\nexport const test = base.extend<Fixtures>({\n  // Fixture with setup/teardown\n  db: async ({}, use) => {\n    const db = await createDatabase()\n    await use(db)           // Provide to test\n    await db.close()        // Cleanup\n  },\n  \n  // Fixture depending on another fixture\n  user: async ({ db }, use) => {\n    const user = await db.createUser({ name: 'Test' })\n    await use(user)\n    await db.deleteUser(user.id)\n  },\n})\n```\n\nUsing fixtures:\n\n```ts\ntest('query user', async ({ db, user }) => {\n  const found = await db.findUser(user.id)\n  expect(found).toEqual(user)\n})\n```\n\n## Fixture Initialization\n\nFixtures only initialize when accessed:\n\n```ts\nconst test = base.extend({\n  expensive: async ({}, use) => {\n    console.log('initializing')  // Only runs if test uses it\n    await use('value')\n  },\n})\n\ntest('no fixture', () => {})           // expensive not called\ntest('uses fixture', ({ expensive }) => {}) // expensive called\n```\n\n## Auto Fixtures\n\nRun fixture for every test:\n\n```ts\nconst test = base.extend({\n  setup: [\n    async ({}, use) => {\n      await globalSetup()\n      await use()\n      await globalTeardown()\n    },\n    { auto: true }  // Always run\n  ],\n})\n```\n\n## Scoped Fixtures\n\n### File Scope\n\nInitialize once per file:\n\n```ts\nconst test = base.extend({\n  connection: [\n    async ({}, use) => {\n      const conn = await connect()\n      await use(conn)\n      await conn.close()\n    },\n    { scope: 'file' }\n  ],\n})\n```\n\n### Worker Scope\n\nInitialize once per worker:\n\n```ts\nconst test = base.extend({\n  sharedResource: [\n    async ({}, use) => {\n      await use(globalResource)\n    },\n    { scope: 'worker' }\n  ],\n})\n```\n\n## Injected Fixtures (from Config)\n\nOverride fixtures per project:\n\n```ts\n// test file\nconst test = base.extend({\n  apiUrl: ['/default', { injected: true }],\n})\n\n// vitest.config.ts\ndefineConfig({\n  test: {\n    projects: [\n      {\n        test: {\n          name: 'prod',\n          provide: { apiUrl: 'https://api.prod.com' },\n        },\n      },\n    ],\n  },\n})\n```\n\n## Scoped Values per Suite\n\nOverride fixture for specific suite:\n\n```ts\nconst test = base.extend({\n  environment: 'development',\n})\n\ndescribe('production tests', () => {\n  test.scoped({ environment: 'production' })\n  \n  test('uses production', ({ environment }) => {\n    expect(environment).toBe('production')\n  })\n})\n\ntest('uses default', ({ environment }) => {\n  expect(environment).toBe('development')\n})\n```\n\n## Extended Test Hooks\n\nType-aware hooks with fixtures:\n\n```ts\nconst test = base.extend<{ db: Database }>({\n  db: async ({}, use) => {\n    const db = await createDb()\n    await use(db)\n    await db.close()\n  },\n})\n\n// Hooks know about fixtures\ntest.beforeEach(({ db }) => {\n  db.seed()\n})\n\ntest.afterEach(({ db }) => {\n  db.clear()\n})\n```\n\n## Composing Fixtures\n\nExtend from another extended test:\n\n```ts\n// base-test.ts\nexport const test = base.extend<{ db: Database }>({\n  db: async ({}, use) => { /* ... */ },\n})\n\n// admin-test.ts\nimport { test as dbTest } from './base-test'\n\nexport const test = dbTest.extend<{ admin: User }>({\n  admin: async ({ db }, use) => {\n    const admin = await db.createAdmin()\n    await use(admin)\n  },\n})\n```\n\n## Key Points\n\n- Use `{ }` destructuring to access fixtures\n- Fixtures are lazy - only initialize when accessed\n- Return cleanup function from fixtures\n- Use `{ auto: true }` for setup fixtures\n- Use `{ scope: 'file' }` for expensive shared resources\n- Fixtures compose - extend from extended tests\n\n<!-- \nSource references:\n- https://vitest.dev/guide/test-context.html\n-->\n", "skills/vitest/references/features-coverage.md": "---\nname: code-coverage\ndescription: Code coverage with V8 or Istanbul providers\n---\n\n# Code Coverage\n\n## Setup\n\n```bash\n# Run tests with coverage\nvitest run --coverage\n```\n\n## Configuration\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    coverage: {\n      // Provider: 'v8' (default, faster) or 'istanbul' (more compatible)\n      provider: 'v8',\n      \n      // Enable coverage\n      enabled: true,\n      \n      // Reporters\n      reporter: ['text', 'json', 'html'],\n      \n      // Files to include\n      include: ['src/**/*.{ts,tsx}'],\n      \n      // Files to exclude\n      exclude: [\n        'node_modules/',\n        'tests/',\n        '**/*.d.ts',\n        '**/*.test.ts',\n      ],\n      \n      // Report uncovered files\n      all: true,\n      \n      // Thresholds\n      thresholds: {\n        lines: 80,\n        functions: 80,\n        branches: 80,\n        statements: 80,\n      },\n    },\n  },\n})\n```\n\n## Providers\n\n### V8 (Default)\n\n```bash\nnpm i -D @vitest/coverage-v8\n```\n\n- Faster, no pre-instrumentation\n- Uses V8's native coverage\n- Recommended for most projects\n\n### Istanbul\n\n```bash\nnpm i -D @vitest/coverage-istanbul\n```\n\n- Pre-instruments code\n- Works in any JS runtime\n- More overhead but widely compatible\n\n## Reporters\n\n```ts\ncoverage: {\n  reporter: [\n    'text',           // Terminal output\n    'text-summary',   // Summary only\n    'json',           // JSON file\n    'html',           // HTML report\n    'lcov',           // For CI tools\n    'cobertura',      // XML format\n  ],\n  reportsDirectory: './coverage',\n}\n```\n\n## Thresholds\n\nFail tests if coverage is below threshold:\n\n```ts\ncoverage: {\n  thresholds: {\n    // Global thresholds\n    lines: 80,\n    functions: 75,\n    branches: 70,\n    statements: 80,\n    \n    // Per-file thresholds\n    perFile: true,\n    \n    // Auto-update thresholds (for gradual improvement)\n    autoUpdate: true,\n  },\n}\n```\n\n## Ignoring Code\n\n### V8\n\n```ts\n/* v8 ignore next -- @preserve */\nfunction ignored() {\n  return 'not covered'\n}\n\n/* v8 ignore start -- @preserve */\n// All code here ignored\n/* v8 ignore stop -- @preserve */\n```\n\n### Istanbul\n\n```ts\n/* istanbul ignore next -- @preserve */\nfunction ignored() {}\n\n/* istanbul ignore if -- @preserve */\nif (condition) {\n  // ignored\n}\n```\n\nNote: `@preserve` keeps comments through esbuild.\n\n## Package.json Scripts\n\n```json\n{\n  \"scripts\": {\n    \"test\": \"vitest\",\n    \"test:coverage\": \"vitest run --coverage\",\n    \"test:coverage:watch\": \"vitest --coverage\"\n  }\n}\n```\n\n## Vitest UI Coverage\n\nEnable HTML coverage in Vitest UI:\n\n```ts\ncoverage: {\n  enabled: true,\n  reporter: ['text', 'html'],\n}\n```\n\nRun with `vitest --ui` to view coverage visually.\n\n## CI Integration\n\n```yaml\n# GitHub Actions\n- name: Run tests with coverage\n  run: npm run test:coverage\n\n- name: Upload coverage to Codecov\n  uses: codecov/codecov-action@v3\n  with:\n    files: ./coverage/lcov.info\n```\n\n## Coverage with Sharding\n\nMerge coverage from sharded runs:\n\n```bash\nvitest run --shard=1/3 --coverage --reporter=blob\nvitest run --shard=2/3 --coverage --reporter=blob\nvitest run --shard=3/3 --coverage --reporter=blob\n\nvitest --merge-reports --coverage --reporter=json\n```\n\n## Key Points\n\n- V8 is faster, Istanbul is more compatible\n- Use `--coverage` flag or `coverage.enabled: true`\n- Include `all: true` to see uncovered files\n- Set thresholds to enforce minimum coverage\n- Use `@preserve` comment to keep ignore hints\n\n<!-- \nSource references:\n- https://vitest.dev/guide/coverage.html\n-->\n", "skills/vitest/references/features-filtering.md": "---\nname: test-filtering\ndescription: Filter tests by name, file patterns, and tags\n---\n\n# Test Filtering\n\n## CLI Filtering\n\n### By File Path\n\n```bash\n# Run files containing \"user\"\nvitest user\n\n# Multiple patterns\nvitest user auth\n\n# Specific file\nvitest src/user.test.ts\n\n# By line number\nvitest src/user.test.ts:25\n```\n\n### By Test Name\n\n```bash\n# Tests matching pattern\nvitest -t \"login\"\nvitest --testNamePattern \"should.*work\"\n\n# Regex patterns\nvitest -t \"/user|auth/\"\n```\n\n## Changed Files\n\n```bash\n# Uncommitted changes\nvitest --changed\n\n# Since specific commit\nvitest --changed HEAD~1\nvitest --changed abc123\n\n# Since branch\nvitest --changed origin/main\n```\n\n## Related Files\n\nRun tests that import specific files:\n\n```bash\nvitest related src/utils.ts src/api.ts --run\n```\n\nUseful with lint-staged:\n\n```js\n// .lintstagedrc.js\nexport default {\n  '*.{ts,tsx}': 'vitest related --run',\n}\n```\n\n## Focus Tests (.only)\n\n```ts\ntest.only('only this runs', () => {})\n\ndescribe.only('only this suite', () => {\n  test('runs', () => {})\n})\n```\n\nIn CI, `.only` throws error unless configured:\n\n```ts\ndefineConfig({\n  test: {\n    allowOnly: true, // Allow .only in CI\n  },\n})\n```\n\n## Skip Tests\n\n```ts\ntest.skip('skipped', () => {})\n\n// Conditional\ntest.skipIf(process.env.CI)('not in CI', () => {})\ntest.runIf(!process.env.CI)('local only', () => {})\n\n// Dynamic skip\ntest('dynamic', ({ skip }) => {\n  skip(someCondition, 'reason')\n})\n```\n\n## Tags\n\nFilter by custom tags:\n\n```ts\ntest('database test', { tags: ['db'] }, () => {})\ntest('slow test', { tags: ['slow', 'integration'] }, () => {})\n```\n\nRun tagged tests:\n\n```bash\nvitest --tags db\nvitest --tags \"db,slow\"      # OR\nvitest --tags db --tags slow # OR\n```\n\nConfigure allowed tags:\n\n```ts\ndefineConfig({\n  test: {\n    tags: ['db', 'slow', 'integration'],\n    strictTags: true, // Fail on unknown tags\n  },\n})\n```\n\n## Include/Exclude Patterns\n\n```ts\ndefineConfig({\n  test: {\n    // Test file patterns\n    include: ['**/*.{test,spec}.{ts,tsx}'],\n    \n    // Exclude patterns\n    exclude: [\n      '**/node_modules/**',\n      '**/e2e/**',\n      '**/*.skip.test.ts',\n    ],\n    \n    // Include source for in-source testing\n    includeSource: ['src/**/*.ts'],\n  },\n})\n```\n\n## Watch Mode Filtering\n\nIn watch mode, press:\n- `p` - Filter by filename pattern\n- `t` - Filter by test name pattern\n- `a` - Run all tests\n- `f` - Run only failed tests\n\n## Projects Filtering\n\nRun specific project:\n\n```bash\nvitest --project unit\nvitest --project integration --project e2e\n```\n\n## Environment-based Filtering\n\n```ts\nconst isDev = process.env.NODE_ENV === 'development'\nconst isCI = process.env.CI\n\ndescribe.skipIf(isCI)('local only tests', () => {})\ndescribe.runIf(isDev)('dev tests', () => {})\n```\n\n## Combining Filters\n\n```bash\n# File pattern + test name + changed\nvitest user -t \"login\" --changed\n\n# Related files + run mode\nvitest related src/auth.ts --run\n```\n\n## List Tests Without Running\n\n```bash\nvitest list                 # Show all test names\nvitest list -t \"user\"       # Filter by name\nvitest list --filesOnly     # Show only file paths\nvitest list --json          # JSON output\n```\n\n## Key Points\n\n- Use `-t` for test name pattern filtering\n- `--changed` runs only tests affected by changes\n- `--related` runs tests importing specific files\n- Tags provide semantic test grouping\n- Use `.only` for debugging, but configure CI to reject it\n- Watch mode has interactive filtering\n\n<!-- \nSource references:\n- https://vitest.dev/guide/filtering.html\n- https://vitest.dev/guide/cli.html\n-->\n", "skills/vitest/references/features-mocking.md": "---\nname: mocking\ndescription: Mock functions, modules, timers, and dates with vi utilities\n---\n\n# Mocking\n\n## Mock Functions\n\n```ts\nimport { expect, vi } from 'vitest'\n\n// Create mock function\nconst fn = vi.fn()\nfn('hello')\n\nexpect(fn).toHaveBeenCalled()\nexpect(fn).toHaveBeenCalledWith('hello')\n\n// With implementation\nconst add = vi.fn((a, b) => a + b)\nexpect(add(1, 2)).toBe(3)\n\n// Mock return values\nfn.mockReturnValue(42)\nfn.mockReturnValueOnce(1).mockReturnValueOnce(2)\nfn.mockResolvedValue({ data: true })\nfn.mockRejectedValue(new Error('fail'))\n\n// Mock implementation\nfn.mockImplementation((x) => x * 2)\nfn.mockImplementationOnce(() => 'first call')\n```\n\n## Spying on Objects\n\n```ts\nconst cart = {\n  getTotal: () => 100,\n}\n\nconst spy = vi.spyOn(cart, 'getTotal')\ncart.getTotal()\n\nexpect(spy).toHaveBeenCalled()\n\n// Mock implementation\nspy.mockReturnValue(200)\nexpect(cart.getTotal()).toBe(200)\n\n// Restore original\nspy.mockRestore()\n```\n\n## Module Mocking\n\n```ts\n// vi.mock is hoisted to top of file\nvi.mock('./api', () => ({\n  fetchUser: vi.fn(() => ({ id: 1, name: 'Mock' })),\n}))\n\nimport { fetchUser } from './api'\n\ntest('mocked module', () => {\n  expect(fetchUser()).toEqual({ id: 1, name: 'Mock' })\n})\n```\n\n### Partial Mock\n\n```ts\nvi.mock('./utils', async (importOriginal) => {\n  const actual = await importOriginal()\n  return {\n    ...actual,\n    specificFunction: vi.fn(),\n  }\n})\n```\n\n### Auto-mock with Spy\n\n```ts\n// Keep implementation but spy on calls\nvi.mock('./calculator', { spy: true })\n\nimport { add } from './calculator'\n\ntest('spy on module', () => {\n  const result = add(1, 2) // Real implementation\n  expect(result).toBe(3)\n  expect(add).toHaveBeenCalledWith(1, 2)\n})\n```\n\n### Manual Mocks (__mocks__)\n\n```\nsrc/\n  __mocks__/\n    axios.ts      # Mocks 'axios'\n  api/\n    __mocks__/\n      client.ts   # Mocks './client'\n    client.ts\n```\n\n```ts\n// Just call vi.mock with no factory\nvi.mock('axios')\nvi.mock('./api/client')\n```\n\n## Dynamic Mocking (vi.doMock)\n\nNot hoisted - use for dynamic imports:\n\n```ts\ntest('dynamic mock', async () => {\n  vi.doMock('./config', () => ({\n    apiUrl: 'http://test.local',\n  }))\n  \n  const { apiUrl } = await import('./config')\n  expect(apiUrl).toBe('http://test.local')\n  \n  vi.doUnmock('./config')\n})\n```\n\n## Mock Timers\n\n```ts\nimport { afterEach, beforeEach, vi } from 'vitest'\n\nbeforeEach(() => {\n  vi.useFakeTimers()\n})\n\nafterEach(() => {\n  vi.useRealTimers()\n})\n\ntest('timers', () => {\n  const fn = vi.fn()\n  setTimeout(fn, 1000)\n  \n  expect(fn).not.toHaveBeenCalled()\n  \n  vi.advanceTimersByTime(1000)\n  expect(fn).toHaveBeenCalled()\n})\n\n// Other timer methods\nvi.runAllTimers()           // Run all pending timers\nvi.runOnlyPendingTimers()   // Run only currently pending\nvi.advanceTimersToNextTimer() // Advance to next timer\n```\n\n### Async Timer Methods\n\n```ts\ntest('async timers', async () => {\n  vi.useFakeTimers()\n  \n  let resolved = false\n  setTimeout(() => Promise.resolve().then(() => { resolved = true }), 100)\n  \n  await vi.advanceTimersByTimeAsync(100)\n  expect(resolved).toBe(true)\n})\n```\n\n## Mock Dates\n\n```ts\nvi.setSystemTime(new Date('2024-01-01'))\nexpect(new Date().getFullYear()).toBe(2024)\n\nvi.useRealTimers() // Restore\n```\n\n## Mock Globals\n\n```ts\nvi.stubGlobal('fetch', vi.fn(() => \n  Promise.resolve({ json: () => ({ data: 'mock' }) })\n))\n\n// Restore\nvi.unstubAllGlobals()\n```\n\n## Mock Environment Variables\n\n```ts\nvi.stubEnv('API_KEY', 'test-key')\nexpect(import.meta.env.API_KEY).toBe('test-key')\n\n// Restore\nvi.unstubAllEnvs()\n```\n\n## Clearing Mocks\n\n```ts\nconst fn = vi.fn()\nfn()\n\nfn.mockClear()       // Clear call history\nfn.mockReset()       // Clear history + implementation\nfn.mockRestore()     // Restore original (for spies)\n\n// Global\nvi.clearAllMocks()\nvi.resetAllMocks()\nvi.restoreAllMocks()\n```\n\n## Config Auto-Reset\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    clearMocks: true,    // Clear before each test\n    mockReset: true,     // Reset before each test\n    restoreMocks: true,  // Restore after each test\n    unstubEnvs: true,    // Restore env vars\n    unstubGlobals: true, // Restore globals\n  },\n})\n```\n\n## Hoisted Variables for Mocks\n\n```ts\nconst mockFn = vi.hoisted(() => vi.fn())\n\nvi.mock('./module', () => ({\n  getData: mockFn,\n}))\n\nimport { getData } from './module'\n\ntest('hoisted mock', () => {\n  mockFn.mockReturnValue('test')\n  expect(getData()).toBe('test')\n})\n```\n\n## Key Points\n\n- `vi.mock` is hoisted - called before imports\n- Use `vi.doMock` for dynamic, non-hoisted mocking\n- Always restore mocks to avoid test pollution\n- Use `{ spy: true }` to keep implementation but track calls\n- `vi.hoisted` lets you reference variables in mock factories\n\n<!-- \nSource references:\n- https://vitest.dev/guide/mocking.html\n- https://vitest.dev/api/vi.html\n-->\n", "skills/vitest/references/features-snapshots.md": "---\nname: snapshot-testing\ndescription: Snapshot testing with file, inline, and file snapshots\n---\n\n# Snapshot Testing\n\nSnapshot tests capture output and compare against stored references.\n\n## Basic Snapshot\n\n```ts\nimport { expect, test } from 'vitest'\n\ntest('snapshot', () => {\n  const result = generateOutput()\n  expect(result).toMatchSnapshot()\n})\n```\n\nFirst run creates `.snap` file:\n\n```js\n// __snapshots__/test.spec.ts.snap\nexports['snapshot 1'] = `\n{\n  \"id\": 1,\n  \"name\": \"test\"\n}\n`\n```\n\n## Inline Snapshots\n\nStored directly in test file:\n\n```ts\ntest('inline snapshot', () => {\n  const data = { foo: 'bar' }\n  expect(data).toMatchInlineSnapshot()\n})\n```\n\nVitest updates the test file:\n\n```ts\ntest('inline snapshot', () => {\n  const data = { foo: 'bar' }\n  expect(data).toMatchInlineSnapshot(`\n    {\n      \"foo\": \"bar\",\n    }\n  `)\n})\n```\n\n## File Snapshots\n\nCompare against explicit file:\n\n```ts\ntest('render html', async () => {\n  const html = renderComponent()\n  await expect(html).toMatchFileSnapshot('./expected/component.html')\n})\n```\n\n## Snapshot Hints\n\nAdd descriptive hints:\n\n```ts\ntest('multiple snapshots', () => {\n  expect(header).toMatchSnapshot('header')\n  expect(body).toMatchSnapshot('body content')\n  expect(footer).toMatchSnapshot('footer')\n})\n```\n\n## Object Shape Matching\n\nMatch partial structure:\n\n```ts\ntest('shape snapshot', () => {\n  const data = { \n    id: Math.random(), \n    created: new Date(),\n    name: 'test' \n  }\n  \n  expect(data).toMatchSnapshot({\n    id: expect.any(Number),\n    created: expect.any(Date),\n  })\n})\n```\n\n## Error Snapshots\n\n```ts\ntest('error message', () => {\n  expect(() => {\n    throw new Error('Something went wrong')\n  }).toThrowErrorMatchingSnapshot()\n})\n\ntest('inline error', () => {\n  expect(() => {\n    throw new Error('Bad input')\n  }).toThrowErrorMatchingInlineSnapshot(`[Error: Bad input]`)\n})\n```\n\n## Updating Snapshots\n\n```bash\n# Update all snapshots\nvitest -u\nvitest --update\n\n# In watch mode, press 'u' to update failed snapshots\n```\n\n## Custom Serializers\n\nAdd custom snapshot formatting:\n\n```ts\nexpect.addSnapshotSerializer({\n  test(val) {\n    return val && typeof val.toJSON === 'function'\n  },\n  serialize(val, config, indentation, depth, refs, printer) {\n    return printer(val.toJSON(), config, indentation, depth, refs)\n  },\n})\n```\n\nOr via config:\n\n```ts\n// vitest.config.ts\ndefineConfig({\n  test: {\n    snapshotSerializers: ['./my-serializer.ts'],\n  },\n})\n```\n\n## Snapshot Format Options\n\n```ts\ndefineConfig({\n  test: {\n    snapshotFormat: {\n      printBasicPrototype: false, // Don't print Array/Object prototypes\n      escapeString: false,\n    },\n  },\n})\n```\n\n## Concurrent Test Snapshots\n\nUse context's expect:\n\n```ts\ntest.concurrent('concurrent 1', async ({ expect }) => {\n  expect(await getData()).toMatchSnapshot()\n})\n\ntest.concurrent('concurrent 2', async ({ expect }) => {\n  expect(await getOther()).toMatchSnapshot()\n})\n```\n\n## Snapshot File Location\n\nDefault: `__snapshots__/<test-file>.snap`\n\nCustomize:\n\n```ts\ndefineConfig({\n  test: {\n    resolveSnapshotPath: (testPath, snapExtension) => {\n      return testPath.replace('__tests__', '__snapshots__') + snapExtension\n    },\n  },\n})\n```\n\n## Key Points\n\n- Commit snapshot files to version control\n- Review snapshot changes in code review\n- Use hints for multiple snapshots in one test\n- Use `toMatchFileSnapshot` for large outputs (HTML, JSON)\n- Inline snapshots auto-update in test file\n- Use context's `expect` for concurrent tests\n\n<!-- \nSource references:\n- https://vitest.dev/guide/snapshot.html\n- https://vitest.dev/api/expect.html#tomatchsnapshot\n-->\n", "skills/write-the-docs/SKILL.md": "---\nname: write-the-docs\ndescription: >-\n  Draft new or updated Supabase docs content for a feature or launch,\n  grounded in product intent (Linear when available), a read of the actual\n  code, and the docs style guide. Use when asked to write\n  docs for a new feature, a product launch, or a Linear ticket that needs\n  net-new content rather than a bug fix. Not for implementing existing docs\n  bug reports. Not for restructuring\n  existing pages — use edit-the-docs for that.\n---\n\n# Write the docs\n\nDrafts net-new Supabase docs content (or product-grounded rewrites) for a feature or launch. Distinct from [`edit-the-docs`](../edit-the-docs/SKILL.md), which restructures and tightens pages that already exist without gathering net-new product intent. This skill is for the case where the content doesn't exist yet (or must be rewritten from intent + code), grounded in four inputs rather than guessed.\n\n## Core rules\n\n1. **Gather before drafting.** Never draft from a ticket title alone. Pull all four inputs below first; a thin gather phase produces a draft that's wrong about how the feature actually works.\n2. **Separate confirmed behavior from product intent from inference.** Code tells you what the feature does today. Linear/PRD/PRFAQ (or prior Frame/Shape output) tells you what it's meant to do and how it should be positioned. Anything you had to guess, flag explicitly rather than stating it as fact.\n3. **Follow the [style guide](../../../apps/docs/style-guide/README.md) for writing conventions, including voice, terminology, formatting, page structure, and elements. Never follow it for content accuracy.** It is a style reference, not a source of truth: rule 2's Linear+code read is what governs what the page actually says. Don't invent voice or structure rules. When the guide and Google's developer documentation style guide both come up short, say so in the handoff rather than copying whatever the nearest page happens to do.\n4. **Reuse, don't duplicate.** Use [`ask-the-docs`](../ask-the-docs/SKILL.md) for docs-app architecture and [`pm-the-docs`](../pm-the-docs/SKILL.md) for placement decisions rather than re-deriving that knowledge here.\n5. **Know what you're actually drafting.** Not everything that looks like \"docs for a feature\" is a hand-written page — see the content-type gate below before you start writing. If the ask is restructure, reorder, connective text, or clarity on an existing page (no new product story), use [`edit-the-docs`](../edit-the-docs/SKILL.md) instead.\n\n## Phase 1 — Gather (read-only)\n\nFour inputs, read in this sequence (sequence, not priority; Linear remains the product-intent source and code remains the behavior source per rule 2 and Phase 1 step 3):\n\n1. **Style guide — voice/terminology reference.** Read [`style-guide/README.md`](../../../apps/docs/style-guide/README.md) and follow the step that matches what you're drafting. The guide's closing section says what to consult when it's silent; follow that rather than matching a neighbouring page.\n2. **Linear — the ticket and its product context.** Linear is an internal Supabase tool: preferred when available, not required for open-source contributors. When a Linear issue is available, pull it, then its parent project/initiative description too (PRD, PRFAQ, RFC, or initiative narrative) and any PM comments. Product framing/positioning language usually lives one level up from the ticket, in the parent project or initiative description rather than the ticket body. Distinguish scope the ticket actually commits to from aspirational language in the PRD. If there is no Linear issue and no prior Frame/Shape product-intent output, stop drafting: ask internal authors for a Linear URL, otherwise hand off to [`pm-the-docs`](../pm-the-docs/SKILL.md) (Frame and Shape). Resume only after product intent exists — never invent positioning, and never run Frame/Shape inside this Draft skill.\n3. **Code.** Read the actual implementation before writing a single behavior claim — the PRD describes intent, the code describes what shipped. Check the Linear issue/project first for a linked `supabase/supabase` PR — its diff and description are the most precise \"what actually shipped\" source, more precise than a general codebase read. If no PR is linked, locate the feature directly in `supabase/supabase` (or the product's own repo), and apply [`ask-the-docs`](../ask-the-docs/SKILL.md)'s reuse/minimalism lens: understand what exists before describing it. When behavior spans services (CLI, Auth, migrations, platform, …), follow [`pm-the-docs`](../pm-the-docs/SKILL.md) → [universe-lookup](../pm-the-docs/reference/universe-lookup.md) **capability gate** (universe when accessible, else OSS public search / linked repos — not `ask-the-docs`). If code and PRD disagree, the code wins for behavior claims — flag the mismatch rather than silently picking one.\n4. **Whatever else the author supplies.** Screenshots, example projects, related pages, Slack threads, a specific voice sample. Screenshots are for more than general context — use them to verify the _exact_ button/menu/field labels before writing instructional steps that reference them; a mismatched UI label is one of the easiest, most avoidable errors in a draft. Ask for these when the feature's user-facing shape is still unclear after 1–3, rather than guessing.\n\nWhen the draft adds to or rewrites an existing page, also read the whole page, each page it links to, and other pages under `apps/docs/content/` on the same topic. Note facts the draft must not repeat, and nearby text that the draft would make untrue, such as \"the steps above\".\n\nSummarize all four back to the requester before drafting: what's confirmed, what's product intent vs. shipped behavior, what's still a gap. Stop and ask if a real gap would change the draft's structure or scope.\n\n## Phase 1.5 — Content-type gate\n\nBefore drafting, classify what's actually being asked for against the real content types (see [`ask-the-docs`](../ask-the-docs/SKILL.md)'s `app-map.md` \"Content types\" table, and [reference/content-type-gate.md](reference/content-type-gate.md) here):\n\n- **Guide / tutorial** — hand-written MDX under `content/guides/`. This is what this skill drafts.\n- **Troubleshooting**: not in `apps/docs`. Troubleshooting articles live in `/kb`, fetched into `apps/kb/src/content/troubleshooting/` from a private repo at build time, and they don't take direct contributions. See `apps/kb/README.md`.\n- **Knowledge base (`/kb`)**: plain Markdown under `apps/kb/src/content/` for content where the answer depends on the user's stack: comparisons, migration guides, buy-vs-build, applied how-tos. Also in scope, but follow `apps/kb/AGENTS.md`, not the `apps/docs` MDX conventions. Product facts stay in `/docs`; the `/kb` article links to them. See [reference/content-type-gate.md](reference/content-type-gate.md#what-goes-in-docs-and-what-goes-in-kb).\n- **Reference** — generated from `spec/` (OpenAPI, SDK YAML, CLI config) → `features/docs/generated/**`. **Not hand-authored via the standard MDX path.** If the ask is actually reference-type content (a new API endpoint, config option, or SDK method that needs a reference entry), stop drafting MDX — it would diverge from or get silently overwritten by the generator. Instead point to the spec/codegen pipeline (`apps/docs/spec/`, `apps/docs/generator/`; see `ask-the-docs`'s `management-api-reference.md` for the OpenAPI-specific flow) and say so explicitly rather than producing a page that looks done but isn't the real fix.\n\nWhen in doubt, ask `ask-the-docs` (Reference or Federated) or `pm-the-docs` (`/docs` vs `/kb`) rather than guessing — this classification is the one call in this skill most likely to be wrong if made from outside knowledge of the app.\n\n## Phase 1.6 — Template gate\n\nBefore drafting, pick the page's template and confirm it with the requester.\n\n1. Match the page's purpose, reader question, and Information Type to a row in [Choose a template](../../../apps/docs/style-guide/03-page-structure.md#choose-a-template). Load only that template file.\n2. Tell the requester which template you chose, why, and the headings it requires. Wait for a yes or a different choice. If the requester is unavailable, go ahead with the template you recommend and record the choice in the handoff. If the page spans two templates, say so and propose a split.\n3. If no row fits, say so and ask. Don't invent a structure.\n4. Draft from the template's headings, and run its checklist in Phase 2.5.\n\nFor `/kb`, this gate applies to guides (`apps/kb/src/content/guides/`). Skip it for FAQs (`apps/kb/src/content/faqs/`): an FAQ answers its question in the first sentence of the body, as `apps/kb/AGENTS.md` defines.\n\n## Phase 2 — Draft\n\n- For `apps/docs` pages, follow `apps/docs` MDX conventions (component usage, frontmatter, code sample wiring). See [`ask-the-docs`](../ask-the-docs/SKILL.md) for the pipeline details rather than re-deriving them. For `/kb` content, follow `apps/kb/AGENTS.md` instead: plain GitHub-flavored Markdown, no components, and frontmatter with `title`, `description`, and `topics`.\n- Place the page using existing IA precedent; for a placement call that isn't obvious, consult [`pm-the-docs`](../pm-the-docs/SKILL.md) (Shape) rather than guessing a nav slot.\n- **Wire it into navigation, not just onto disk.** Placement (which section) and nav enablement (whether it actually shows up) are separate — confirm the current nav-registration mechanism via `ask-the-docs` rather than assuming a page is discoverable just because the file exists in the right folder.\n- Ground every behavior claim in Phase 1's code read (the linked PR when there is one); ground every \"why this matters\" framing in Linear/PM context or prior Frame/Shape output; mark inferred material inline (e.g. an HTML comment or a flagged line in the handoff summary) so a reviewer can find it fast.\n- **Write timeless documentation, cut redundancy, and prefer a paragraph to a single-item list.** See [timeless documentation](../../../apps/docs/style-guide/03-page-structure.md#write-timeless-documentation), [brevity](../../../apps/docs/style-guide/01-voice-and-tone.md#brevity), and [lists](../../../apps/docs/style-guide/02-elements.md#lists).\n- **Strip internal business context before the final draft.** HTML comments flagging PRD intent, roadmap speculation, internal ticket discussions, or \"gap-fill\" notes must be removed from MDX before handoff. Open-source docs shouldn't expose internal planning. Flag assumptions and open questions for reviewers in the PR description instead, not in the shipped content.\n- Search [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md) when introducing or reviewing technical terms, UI actions, abbreviations, and potentially ambiguous language during drafting. Use the two-pass protocol in [Use with an AI agent](../../../apps/docs/style-guide/WORD_LIST.md#use-with-an-ai-agent) rather than reading the file end to end.\n- Reuse repeated content through `apps/docs/content/_partials/` instead of copying it. For nav wiring, partials, and file placement, see [`ask-the-docs`](../ask-the-docs/SKILL.md)'s `app-map.md` and `federated-docs.md`.\n\n## Phase 2.5 — Review checklist\n\nBefore handing off, confirm:\n\n- [ ] Style guide followed, or the gap named explicitly in the handoff\n- [ ] Every behavior claim traces to the code read (ideally the linked PR), not just the PRD, checked claim by claim in the [accuracy pass](#accuracy-pass)\n- [ ] Every \"why it matters\" / positioning line traces to Linear/PM context or prior Frame/Shape output, not invented\n- [ ] Inferred or assumed material is flagged, not stated as fact\n- [ ] Content type confirmed as Guide or `/kb` (not Reference that belongs in generated output, and not Troubleshooting, which takes no direct contributions)\n- [ ] Nav placement and nav enablement both wired, not just the placement\n- [ ] Internal links resolve; first-use of new terms/acronyms is defined\n- [ ] Offered [`test-the-docs`](../test-the-docs/SKILL.md) for runnable snippets (CLI, SQL, client code, or example apps)\n- [ ] Future promises minimized where possible (timeless documentation principle)\n- [ ] No unnecessary redundancy (same point restated multiple ways)\n- [ ] Single-item lists avoided unless there's a specific reason\n- [ ] Internal gap-fill and business context comments removed from MDX (keep only in PR description if needed for review)\n\n### Compliance checklist\n\nBefore handoff, run both passes from [Use with an AI agent](../../../apps/docs/style-guide/WORD_LIST.md#use-with-an-ai-agent): read [Phrase groups](../../../apps/docs/style-guide/WORD_LIST.md#phrase-groups) for the literal term lists, then `grep '^### ' WORD_LIST.md` and read only the entries matching words on the page. Cover terms you didn't introduce, not just the ones you searched while drafting. Then check the draft against each numbered file in the [style guide](../../../apps/docs/style-guide/README.md).\n\n- [ ] Parentheses used only for acronyms or `(Optional)`, not prose asides\n- [ ] Bold, italics, and code used only for their distinct purposes (UI labels, must-not-miss terms), not for visual emphasis alone\n- [ ] No dash-based asides where a direct sentence reads better\n- [ ] Terminology matches [`WORD_LIST.md`](../../../apps/docs/style-guide/WORD_LIST.md) (including any terms flagged as imprecise, not just spelling/capitalization)\n- [ ] Voice, tense, and brevity follow [`01-voice-and-tone.md`](../../../apps/docs/style-guide/01-voice-and-tone.md)\n- [ ] Document type, section grouping, and chunking follow [`03-page-structure.md`](../../../apps/docs/style-guide/03-page-structure.md)\n- [ ] The page follows the template named in [Choose a template](../../../apps/docs/style-guide/03-page-structure.md#choose-a-template) (`/kb` FAQs are exempt; they answer the question in the first sentence)\n- [ ] Admonitions, headings, links, and other components follow [`02-elements.md`](../../../apps/docs/style-guide/02-elements.md)\n\n### Accuracy pass\n\nRun this after the compliance checklist, as a separate pass. A clean style review does not show that the page is true. Run it in a fresh subagent that gets only the draft and the pinned version, so it checks the code and not the drafting agent's summary.\n\n1. List every behavior claim in the draft: what the feature accepts, rejects, returns, or requires. Include what each command or script the page tells readers to run changes, beyond its stated purpose.\n2. For each claim, open the source lines again at a pinned version: the commit your branch is based on, or the release tag when the code lives in another repo. Do not check against your notes or an earlier summary of the code.\n3. Compare the claim with every branch in those lines, including early returns, special cases, and fallbacks. If the code has an exception that the sentence leaves out, add the exception or narrow the sentence.\n4. Treat _any_, _all_, _always_, _only_, and _never_ as claims about every case. Keep them only when the code or a test covers every case.\n5. Put the file, line range, and version for each claim in the handoff, so a reviewer can check it.\n\nWhen brevity and accuracy conflict, keep the sentence short and complete. Do not drop an exception to make a sentence read better.\n\n## Phase 2.6 — Moved or deleted pages (conditional)\n\nOnly apply this phase when the draft renames, moves, or deletes an existing page, so its URL changes or disappears. Skip it for new pages and for edits that keep the URL.\n\n- [ ] Every old URL that stops resolving gets a redirect. Follow [`apps/docs/lib/redirects/README.md`](../../../apps/docs/lib/redirects/README.md):\n  - One-to-one mappings go in `static-redirects.json`. Entries with params, splats, or conditions go in `dynamic-redirects.js`.\n  - Use full public paths that start with `/docs`.\n  - Don't add `.md` variants by hand for `/docs/guides/` entries. The generator adds them.\n- [ ] Deleted pages with no replacement get a redirect to the closest live page, and the choice goes in the \"needs review\" section of the PR description.\n- [ ] Internal links, nav entries, and partials that point at the old URL are updated, so the redirect is only a fallback for external links.\n- [ ] Run `pnpm -C apps/docs run redirects:generate` and confirm the new entry appears in the generated output.\n\n## Phase 3 — Handoff\n\nThis skill stops at a reviewable draft. It does not open worktrees or PRs itself:\n\n- **Offer** [`test-the-docs`](../test-the-docs/SKILL.md) when the draft includes runnable procedural snippets. Ask before starting verification. Gate prerequisites **per artifact class** (Docker Compose stack profile for DB/API artifacts; examples profile / Node in-runner for `example-app`). If declined, or a required prerequisite for that class is missing, record `deferred` for those artifacts only and continue. When accepted, attach the verification report to the PR body / self-review note.\n- Before opening the PR, run [`review-the-docs`](../review-the-docs/SKILL.md) local self-review (build, classify, and read the change as a reader), including `pnpm build:guides-markdown` where applicable and the anchor checks in [reference/drafting-mechanics.md](reference/drafting-mechanics.md).\n- When the PR is opened, carry the Phase 1/2 flagged-assumptions list into the PR description (for example, a \"needs review\" section) so a reviewer sees it, not just as an inline comment buried in the draft.\n- If the feature is UI-driven and the PR will need screenshots or GIFs, say so in the handoff rather than capturing evidence here.\n\n## Additional resources\n\n- Style: [`style-guide/README.md`](../../../apps/docs/style-guide/README.md) routes to the file for each level\n- Repo mechanics (nav wiring, partials, reference pipeline): [`apps/docs/CONTRIBUTING.md`](../../../apps/docs/CONTRIBUTING.md)\n- Drafting mechanics: [reference/drafting-mechanics.md](reference/drafting-mechanics.md)\n- Content-type gate detail: [reference/content-type-gate.md](reference/content-type-gate.md)\n- Existing-page restructure/clarity: [`edit-the-docs`](../edit-the-docs/SKILL.md)\n- \"Write the docs\" checklist (Draft stage): [`pm-the-docs`](../pm-the-docs/SKILL.md)'s [reference/write-the-docs-checklist.md](../pm-the-docs/reference/write-the-docs-checklist.md)\n- Cross-repo product lookup: [`pm-the-docs`](../pm-the-docs/SKILL.md) → [universe-lookup](../pm-the-docs/reference/universe-lookup.md)\n- Runnable verification: [`test-the-docs`](../test-the-docs/SKILL.md)\n- Docs-app architecture and nav mechanics: [`ask-the-docs`](../ask-the-docs/SKILL.md)\n", "skills/write-the-docs/reference/content-type-gate.md": "# Content-type gate\n\nBefore drafting anything, classify the request against the real content types. `ask-the-docs`'s `app-map.md` \"Content types\" table covers `apps/docs`; for `/kb`, see `apps/kb/AGENTS.md`.\n\n| Type | Location | Hand-authored by this skill? |\n|---|---|---|\n| **Guide / tutorial** | `content/guides/` | Yes — hand-written MDX, goal-oriented. This is the default case. |\n| **Troubleshooting** | `/kb/troubleshooting/`, fetched into `apps/kb/src/content/troubleshooting/` from a private repo | No. Troubleshooting articles go through an internal process, not direct contributions. See `apps/kb/README.md`. |\n| **Reference** | Generated from `spec/` (OpenAPI, SDK YAML, CLI config) → `features/docs/generated/**` | **No.** Reference pages do not use the standard MDX path — see `ask-the-docs`'s `docs-app-direction.md` for why, and `management-api-reference.md` for the OpenAPI-specific spec → codegen → reference-page flow. |\n| **Federated** | External repos, pulled at build time | No — out of scope for this skill; see `ask-the-docs`'s `federated-docs.md`. |\n| **Knowledge base (`/kb`)** | `apps/kb/src/content/guides/` and `apps/kb/src/content/faqs/` | Yes, but not as `apps/docs` MDX. Use `/kb` when the answer depends on the user's stack, scale, or alternatives: comparisons, migration guides, buy-vs-build, applied how-tos. Plain GitHub-flavored Markdown with no components; frontmatter needs `title`, `description`, and `topics`. See `apps/kb/AGENTS.md`. |\n\n## What goes in `/docs` and what goes in `/kb`\n\n`/docs` holds product facts: concepts, configuration, API and SDK usage, getting started. Supabase alone sets the answer. `/kb` holds content where the answer depends on the user's situation. Keep product facts (API signatures, config values, limits, pricing) in `/docs` only, and link to them from `/kb`. A launch can need both: a `/docs` guide for the feature, and a `/kb` comparison or migration guide. Fixes for specific problems, such as what one error message means, are troubleshooting articles in `/kb`, and the `/docs` page links to them.\n\n## What to do when the ask is actually Reference-type\n\nA common trap: a ticket says \"document the new `X` config option\" or \"add docs for the new API endpoint,\" which sounds like a normal doc-writing ask but is actually a spec change. If so:\n\n1. Don't hand-draft an MDX reference page — it will diverge from or get silently overwritten by the next `generate-reference-markdown.ts` run.\n2. Identify the correct spec source (`apps/docs/spec/` — OpenAPI, SDKSpec, ConfigSpec, or CLISpec depending on the surface).\n3. Say explicitly in the handoff that the real fix is a spec/codegen change, not a docs PR from this skill, and point to `ask-the-docs` for the specific spec-editing workflow.\n\n## When it's genuinely ambiguous\n\nSome features span both — e.g. a new API endpoint (Reference) that also needs a task-oriented guide showing how to use it (Guide). In that case, split the work: flag the Reference-type piece per above, and draft only the Guide-type piece here.\n", "skills/write-the-docs/reference/drafting-mechanics.md": "# Drafting mechanics\n\nMechanics that come up during drafting but aren't worth duplicating from the\nstyle guide or `ask-the-docs`. For style rules, see\n[`apps/docs/style-guide/`](../../../../apps/docs/style-guide/README.md). For nav\nwiring, partials, and file placement, see `ask-the-docs`'s `app-map.md` and\n`federated-docs.md`.\n\n## Link paths\n\n- Use `/docs/...` paths for pages in Supabase docs.\n- Use site-root paths such as `/dashboard` for pages outside docs.\n- Use descriptive link text and sparse admonitions with the appropriate severity.\n\n## Anchor stability\n\nAnchor IDs are generated from heading text at render time, and nothing in CI\nchecks that `#anchor` links still resolve. Before renaming, removing, or\nsubstantially rewording a heading, run:\n\n```bash\ngrep -rn \"#<old-anchor-slug>\" apps/docs/content\n```\n\nUpdate every in-page and cross-file match. If a heading needs a stable anchor\nindependent of its wording, pin it with a custom anchor, for example\n`## Some heading [#some-heading]`.\n\n## Lint and format\n\nFrom `apps/docs`:\n\n```bash\npnpm build:guides-markdown\n```\n\n`pnpm build:guides-markdown` only applies to guides, explainers, and tutorials.\n\nFrom the repository root, run `pnpm format` to apply oxfmt to changed MDX\nfiles. This enforces repo-wide formatting rules.\n\nCheck terminology against [`WORD_LIST.md`](../../../../apps/docs/style-guide/WORD_LIST.md)\nyourself. Treat its replacements as suggestions when context matters: rewrite the\nsentence instead of applying one that changes its technical meaning.\n"}}
