@neon/skills 0.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ # Full-Text Search with BM25 Ranking
2
+
3
+ Use `lakebase_text` for BM25 relevance ranking with PostgreSQL's standard `tsvector` type. The `lakebase_bm25` index adds corpus-aware ranking and top-K pushdown.
4
+
5
+ Lakebase Search requires Postgres 16 or later. Enable the extension before creating the index:
6
+
7
+ ```sql
8
+ CREATE EXTENSION IF NOT EXISTS lakebase_text;
9
+ ```
10
+
11
+ `lakebase_text` has no extension dependency. It relies on a preloaded library that Neon enables by default; if the project customized its preloaded-library list, confirm the library remains enabled.
12
+
13
+ ## Prepare and Index Text
14
+
15
+ Prefer a stored generated `tsvector` when search text comes from stable table columns:
16
+
17
+ ```sql
18
+ CREATE TABLE documents (
19
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
20
+ title text NOT NULL,
21
+ body text NOT NULL,
22
+ body_tsv tsvector GENERATED ALWAYS AS
23
+ (to_tsvector('english', body)) STORED
24
+ );
25
+ ```
26
+
27
+ Create the index after the initial corpus has been inserted so build-time corpus statistics are meaningful. BM25 scoring is tuned by two storage parameters set at index-build time:
28
+
29
+ - `k1` controls term-frequency saturation (default `1.2`, range `1.2`–`2.0`): higher values let repeated terms keep adding relevance.
30
+
31
+ - `b` controls document-length normalization (default `0.75`, range `0.0`–`1.0`): higher values penalize longer documents more.
32
+
33
+ Both can only be set in the `WITH` clause, and updating them rebuilds the index:
34
+
35
+ ```sql
36
+ CREATE INDEX documents_body_bm25 ON documents
37
+ USING lakebase_bm25 (body_tsv)
38
+ WITH (k1 = 1.2, b = 0.75);
39
+ ```
40
+
41
+ After a large bulk load, run `VACUUM` to refresh the statistics used by BM25 scoring.
42
+
43
+ ## Query and Interpret Scores
44
+
45
+ `to_bm25query` binds the query `tsvector` to the BM25 index whose corpus statistics should be used. The `<@>` operator returns a negative BM25 score, so lower (more negative) values are more relevant and must sort ascending:
46
+
47
+ ```sql
48
+ SELECT
49
+ id,
50
+ title,
51
+ body_tsv <@> to_bm25query(
52
+ to_tsvector('english', $1),
53
+ 'documents_body_bm25'::regclass
54
+ ) AS score
55
+ FROM documents
56
+ ORDER BY score
57
+ LIMIT $2;
58
+ ```
59
+
60
+ Use the same text-search configuration for document and query vectors. Select a language-specific or custom configuration that matches the corpus.
61
+
62
+ ## Set the Candidate Limit
63
+
64
+ `lakebase_bm25.default_limit` controls how many rows the index returns before PostgreSQL applies the SQL `LIMIT`. Its default is `1000`; setting it close to the requested top-K avoids unnecessary scoring.
65
+
66
+ ## Use Prefilter Selectively
67
+
68
+ Enable prefilter when a `WHERE` condition is strict or unpredictable and cheap to evaluate. It lets the index prune rows before BM25 scoring. A loose or expensive filter can be slower with prefilter enabled.
69
+
70
+ ```sql
71
+ BEGIN;
72
+ SET LOCAL lakebase_bm25.default_limit = 20;
73
+ SET LOCAL lakebase_bm25.prefilter = on;
74
+
75
+ SELECT
76
+ id,
77
+ title,
78
+ body_tsv <@> to_bm25query(
79
+ to_tsvector('english', $1),
80
+ 'documents_body_bm25'::regclass
81
+ ) AS score
82
+ FROM documents
83
+ WHERE id % 1000 = 0
84
+ ORDER BY score
85
+ LIMIT $2;
86
+ COMMIT;
87
+ ```
88
+
89
+ ## Set Parameters at Build Time or Per Query
90
+
91
+ Several BM25 parameters can be set in two places. As an index storage parameter in the `CREATE INDEX` `WITH` clause, a value is fed into the index as its build-time default. As a session GUC via `SET` (or `SET LOCAL`), it applies per query and takes precedence over the stored default when both are present.
92
+
93
+ - `default_limit` and `prefilter` exist in both forms: set an index default that fits the common case, then override it per query with a GUC without rebuilding.
94
+ - `k1` (default `1.2`) and `b` (default `0.75`) are storage parameters only. There is no GUC for them.
95
+ - `enable_scan` (default `on`) is a GUC only.
96
+
97
+ The examples use `SET LOCAL` so each override is scoped to its own transaction, which is required behind a connection pool or stateless driver.
98
+
99
+ Source: [`lakebase_text` documentation](https://neon.com/docs/extensions/lakebase-text).
@@ -0,0 +1,90 @@
1
+ # Hybrid Search
2
+
3
+ Use hybrid search when either semantic similarity or exact vocabulary can identify a relevant document. Lakebase Search does not provide a built-in hybrid function: run vector and BM25 retrieval separately, then combine their results with a fusion strategy suited to the workload.
4
+
5
+ Lakebase Search requires Postgres 16 or later. Hybrid search uses both extensions:
6
+
7
+ ```sql
8
+ CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
9
+ CREATE EXTENSION IF NOT EXISTS lakebase_text;
10
+ ```
11
+
12
+ `lakebase_vector` installs `pgvector` through `CASCADE`; `lakebase_text` has no extension dependency. Both rely on preloaded libraries that Neon enables by default. If the project customized its preloaded-library list, confirm both libraries remain enabled.
13
+
14
+ Prepare a table with both vector and text-search columns:
15
+
16
+ ```sql
17
+ CREATE TABLE documents (
18
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
19
+ title text NOT NULL,
20
+ body text NOT NULL,
21
+ embedding vector(1536),
22
+ body_tsv tsvector GENERATED ALWAYS AS
23
+ (to_tsvector('english', body)) STORED
24
+ );
25
+ ```
26
+
27
+ Replace `1536` with the embedding model's dimension. Use the same model and preprocessing for stored-document and query embeddings, and choose a PostgreSQL text-search configuration appropriate for the corpus.
28
+
29
+ Create and validate each retriever independently before combining them. Follow [Vector search](vector-search.md) and [Full-text search](full-text-search.md) for their indexes, query operators, and tuning.
30
+
31
+ Reciprocal Rank Fusion (RRF) is the approach in the Lakebase Search get-started guide and a useful default because it combines ranks instead of incomparable raw distances and scores. It is not the only option: weighted rank fusion, normalized score fusion, or a reranker may fit applications with different relevance signals.
32
+
33
+ ## RRF Example
34
+
35
+ For rank `r` and constant `k`, each retriever contributes `1 / (k + r)`. The documented starting point uses 40 candidates per retriever and `k = 60`; tune both for the corpus and workload.
36
+
37
+ Bind the query embedding as `$1`, query text as `$2`, and final result count as `$3`:
38
+
39
+ ```sql
40
+ WITH vector_ranked AS (
41
+ SELECT id, RANK() OVER (ORDER BY distance) AS rank
42
+ FROM (
43
+ SELECT id, embedding <=> $1::vector AS distance
44
+ FROM documents
45
+ ORDER BY distance
46
+ FETCH FIRST 40 ROWS WITH TIES
47
+ ) AS vector_candidates
48
+ ),
49
+ keyword_ranked AS (
50
+ SELECT id, RANK() OVER (ORDER BY score) AS rank
51
+ FROM (
52
+ SELECT
53
+ id,
54
+ body_tsv <@> to_bm25query(
55
+ to_tsvector('english', $2),
56
+ 'documents_body_bm25'::regclass
57
+ ) AS score
58
+ FROM documents
59
+ ORDER BY score
60
+ FETCH FIRST 40 ROWS WITH TIES
61
+ ) AS keyword_candidates
62
+ )
63
+ SELECT
64
+ d.id,
65
+ d.title,
66
+ COALESCE(1.0 / (60 + v.rank), 0) +
67
+ COALESCE(1.0 / (60 + k.rank), 0) AS rrf_score
68
+ FROM documents AS d
69
+ LEFT JOIN vector_ranked AS v ON v.id = d.id
70
+ LEFT JOIN keyword_ranked AS k ON k.id = d.id
71
+ WHERE v.id IS NOT NULL OR k.id IS NOT NULL
72
+ ORDER BY rrf_score DESC, d.id
73
+ LIMIT $3;
74
+ ```
75
+
76
+ `RANK()` gives tied retrieval scores the same rank. Sort by `rrf_score` descending and use the stable ID as a final tie-breaker.
77
+
78
+ `FETCH FIRST ... ROWS WITH TIES` keeps every candidate tied at the cutoff, so `RANK()` receives the complete boundary tie group. The candidate set can therefore exceed 40 rows. `lakebase_bm25.default_limit` defaults to `1000`; increase it only when the BM25 candidate set needs to exceed that value.
79
+
80
+ ## Adapt the Hybrid Search
81
+
82
+ - Retrieve more candidates from each source than the final result count; otherwise one retriever can dominate before fusion has enough overlap. Keep `lakebase_bm25.default_limit` above the BM25 candidate target and allow room for boundary ties.
83
+ - Keep each retriever's operator and index configuration correct independently before tuning RRF.
84
+ - Tune candidate counts and the RRF constant with judged or behavioral relevance data, plus latency measurements.
85
+ - Add weights only when product evidence shows one retriever should contribute more. Weight the reciprocal-rank contributions, not the raw vector distance and negative BM25 score.
86
+ - Apply the same access-control and tenant filters to both candidate CTEs. If BM25 filters are strict and cheap, evaluate whether `lakebase_bm25.prefilter` improves the filtered query.
87
+
88
+ Source: [Lakebase Search get-started guide][lakebase-search-guide].
89
+
90
+ [lakebase-search-guide]: https://neon.com/docs/ai/lakebase-search-get-started#combine-results-with-hybrid-search
@@ -0,0 +1,137 @@
1
+ # Semantic Vector Search
2
+
3
+ Use `lakebase_vector` for approximate nearest-neighbor retrieval over embeddings. It retains pgvector's vector types, distance operators, and query syntax; the index access method is `lakebase_ann`.
4
+
5
+ ## Contents
6
+
7
+ - [Create the extension](#create-the-extension) — enable `lakebase_vector` and its `pgvector` dependency
8
+ - [Prepare embeddings](#prepare-embeddings) — define the vector column and keep embedding dimensions consistent
9
+ - [Build the index](#build-the-index) — match the distance metric, operator class, and query operator
10
+ - [Tune the index](#tune-the-index) — configure index-build options and concurrent index management
11
+ - [Query](#query) — rank by vector distance or filter by a similarity radius
12
+ - [Tune search](#tune-search) — inspect the index and tune recall against latency
13
+ - [Use prefilter selectively](#use-prefilter-selectively) — apply selective filters before ANN scoring
14
+
15
+ ## Create the Extension
16
+
17
+ Lakebase Search requires Postgres 16 or later. Enable the extension before creating vector columns or indexes:
18
+
19
+ ```sql
20
+ CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
21
+ ```
22
+
23
+ `lakebase_vector` installs `pgvector` through `CASCADE`. It relies on a preloaded library that Neon enables by default; if the project customized its preloaded-library list, confirm the library remains enabled.
24
+
25
+ ## Prepare Embeddings
26
+
27
+ Use any embedding provider whose vector dimensions and distance metric match the schema and index:
28
+
29
+ ```sql
30
+ CREATE TABLE documents (
31
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
32
+ title text NOT NULL,
33
+ body text NOT NULL,
34
+ embedding vector(1536)
35
+ );
36
+ ```
37
+
38
+ Replace `1536` with the embedding model's dimension. Generate stored-document and query embeddings with the same model and preprocessing. Keep embedding generation outside SQL unless the architecture already provides an in-database embedding function.
39
+
40
+ ## Build the Index
41
+
42
+ Choose the operator class and query operator as a matched pair:
43
+
44
+ | Metric | Common use | Operator class | Distance operator |
45
+ | --- | --- | --- | --- |
46
+ | Cosine | Most text embeddings | `vector_cosine_ops` | `<=>` |
47
+ | L2 / Euclidean | Absolute distance matters; vectors do not need normalization | `vector_l2_ops` | `<->` |
48
+ | Inner product | Unit-normalized vectors; matches cosine for unit vectors | `vector_ip_ops` | `<#>` |
49
+
50
+ ```sql
51
+ CREATE INDEX documents_embedding_ann ON documents
52
+ USING lakebase_ann (embedding vector_cosine_ops);
53
+ ```
54
+
55
+ ## Tune the Index
56
+
57
+ The default index options suit most workloads:
58
+
59
+ - `build_mode = 'standard'` balances recall and index build time. Use `quality` for better recall when a longer build is acceptable.
60
+ - `lists = 'auto'` chooses the IVF partition layout from the number of indexed vectors. Choose between `auto` and a manual value case by case: test both on the target dataset and use the value that better meets recall and performance targets.
61
+
62
+ To prioritize recall over index build time:
63
+
64
+ ```sql
65
+ CREATE INDEX documents_embedding_ann_quality ON documents
66
+ USING lakebase_ann (embedding vector_cosine_ops)
67
+ WITH (build_mode = 'quality');
68
+ ```
69
+
70
+ To override the automatic partition layout instead:
71
+
72
+ ```sql
73
+ CREATE INDEX documents_embedding_ann_lists ON documents
74
+ USING lakebase_ann (embedding vector_cosine_ops)
75
+ WITH (lists = '1024');
76
+ ```
77
+
78
+ For a large table, use `CREATE INDEX CONCURRENTLY` to avoid locking out writes while creating the index. For a frequently changing table, periodically use `REINDEX INDEX CONCURRENTLY` to rebuild the index with minimal write locking.
79
+
80
+ ## Query
81
+
82
+ Generate the query embedding with the same model and preprocessing used for stored documents, then bind it as a parameter:
83
+
84
+ ```sql
85
+ SELECT id, title, embedding <=> $1::vector AS distance
86
+ FROM documents
87
+ ORDER BY distance
88
+ LIMIT $2;
89
+ ```
90
+
91
+ Distance sorts ascending: a smaller value is a closer match. Keep the query operator consistent with the index operator class.
92
+
93
+ To filter by a similarity radius, use the matching boolean range operator in `WHERE` and the distance operator in `ORDER BY`:
94
+
95
+ ```sql
96
+ SELECT id, title
97
+ FROM documents
98
+ WHERE embedding <<=>> sphere($1::vector, 0.5)
99
+ ORDER BY embedding <=> $1::vector
100
+ LIMIT $2;
101
+ ```
102
+
103
+ The cosine range operator `<<=>>` returns a boolean; do not use it as the ranking expression.
104
+
105
+ ## Tune Search
106
+
107
+ Inspect the index before overriding defaults:
108
+
109
+ ```sql
110
+ SELECT lakebase_ann_index_info('documents_embedding_ann');
111
+ ```
112
+
113
+ This reports `lists`, `default_probes`, and `default_epsilon`. Small datasets use exact flat search before IVF lists are built. In that state, `lists` and `default_probes` are empty. Leave `lakebase_ann.probes` set to its default of `'auto'`; `lakebase_ann.epsilon` still controls full-precision reranking during flat search.
114
+
115
+ For an IVF index, `lakebase_ann.probes` controls how many partitions are searched at each level. Higher values generally improve recall at the cost of speed. Its default is `'auto'`. When `lists` is not empty, the shape of `probes` must match the shape of `lists`: use one value for a one-level index or two comma-separated values for a two-level index. At each level, the `probes` value must be no larger than the corresponding `lists` value. A mismatched or out-of-range value causes an error.
116
+
117
+ `lakebase_ann.epsilon` controls how many candidates are reranked using full-precision distances. Higher values rerank more candidates and take longer. Its default is `'auto'`, which works well for most workloads.
118
+
119
+ ### Use Prefilter Selectively
120
+
121
+ By default, PostgreSQL applies non-vector filters after the ANN index returns candidate rows. Enable prefilter when a filter is cheap to evaluate and removes most rows. Leave it off for loose or expensive filters.
122
+
123
+ ```sql
124
+ BEGIN;
125
+ SET LOCAL lakebase_ann.prefilter = on;
126
+
127
+ SELECT id, title
128
+ FROM documents
129
+ WHERE id % 100 = 0
130
+ ORDER BY embedding <=> $1::vector
131
+ LIMIT $2;
132
+ COMMIT;
133
+ ```
134
+
135
+ Start with `probes` and `epsilon` set to `'auto'`. Benchmark manual probe values against representative query embeddings and choose the smallest values that satisfy recall and tail-latency targets. Keep session settings and the query in the same transaction when using a connection pool or stateless driver.
136
+
137
+ Source: [`lakebase_vector` documentation](https://neon.com/docs/extensions/lakebase-vector).
@@ -0,0 +1,292 @@
1
+ ---
2
+ name: neon-postgres-branches
3
+ description: >-
4
+ Choose and create the right Neon branch type for testing and development.
5
+ Use when users ask about Neon branching, migration testing with real data,
6
+ isolated test environments, schema-only branch workflows for sensitive data,
7
+ resetting a branch from its parent, branch expiration and CI/CD branch
8
+ lifecycles, or branch creation via Neon CLI or Neon MCP. Triggers include
9
+ "Neon branch", "test migrations safely", "branch production data",
10
+ "schema-only branch", "reset branch", "branch per PR" and
11
+ "sensitive data testing".
12
+ metadata:
13
+ parent: neon
14
+ source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres-branches
15
+ ---
16
+
17
+ **FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
18
+
19
+ If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
20
+
21
+ ```bash
22
+ npx skills add neondatabase/agent-skills --skill neon
23
+ ```
24
+
25
+ # Lakebase Postgres Branching
26
+
27
+ **Outcome:** a created Neon branch — or a clear, actionable next step if creation cannot proceed. Choose the correct branch type, then execute branch creation with the CLI (or MCP where the CLI isn't usable).
28
+
29
+ - **Normal branch** for realistic migration and query testing with real data.
30
+ - **Schema-only branch (Beta)** for sensitive data workflows where structure is needed without copying rows.
31
+
32
+ ## Branch Type Decision
33
+
34
+ Use this decision rule first:
35
+
36
+ 1. If the user wants to test complex migrations, performance, or behavior against production-like data, choose a **normal branch**.
37
+ 2. If the user needs to avoid copying sensitive data, choose a **schema-only branch**.
38
+
39
+ If the request is ambiguous, ask one clarifying question:
40
+ "Do you need realistic data for testing, or only schema structure because the data is sensitive?"
41
+
42
+ ## Tool Selection: CLI or MCP
43
+
44
+ Support both the Neon CLI and the Neon MCP server, but **default to the CLI**. Use MCP only when the CLI is unavailable or blocked in your environment, cannot be authenticated, or the user explicitly asks for MCP.
45
+
46
+ - CLI link: https://neon.com/docs/cli/quickstart.md
47
+ - MCP link: https://neon.com/docs/ai/neon-mcp-server.md
48
+
49
+ ### Selection order
50
+
51
+ 1. Check the CLI first:
52
+ - Run `neon --version` to confirm the CLI is installed.
53
+ - Run `neon projects list` to confirm auth/context.
54
+ 2. If the CLI is missing, direct installation via quickstart.
55
+ 3. If the CLI is installed but not authenticated, guide the user through `neon auth` (or API key auth), then continue.
56
+ 4. Switch to MCP when the CLI cannot be used — no CLI access in the environment, execution blocked, or authentication not possible — or when the user explicitly asks for MCP. Confirm Neon MCP tools are available and authenticated (for example, listing projects works), then follow the MCP branch flow below.
57
+ 5. If neither path is successful, use the Neon REST API:
58
+ - https://neon.com/docs/guides/branching-neon-api.md
59
+
60
+ ### MCP branch flow
61
+
62
+ 1. Choose normal vs schema-only based on data sensitivity and migration-testing goals.
63
+ 2. Use branch tools (for example, `create_branch`) to create the branch.
64
+ 3. Validate with read tools (for example, `describe_branch`).
65
+ 4. For migration workflows, prefer branch-based migration flows before applying to main.
66
+
67
+ ## Create a Normal Branch (Preferred for Real-Data Migration Testing)
68
+
69
+ Use this when the user needs realistic testing conditions.
70
+ Real production-like data can expose edge cases your seed or data migration scripts miss, which helps catch migration issues before going live.
71
+
72
+ Link: https://neon.com/docs/introduction/branching.md
73
+
74
+ ### Steps
75
+
76
+ 1. Settle the tool path first (see [Selection order](#selection-order)): verify the CLI with `neon --version`, and fall back to MCP only if the CLI isn't usable.
77
+ 2. Ensure project context is set (`neon set-context --project-id <your-project-id>`) or include `--project-id` on commands.
78
+ 3. Create the branch:
79
+
80
+ ```bash
81
+ neon branches create \
82
+ --name <branch-name> \
83
+ --parent <parent-branch-id-or-name> \
84
+ --expires-at 2026-12-15T18:02:16Z
85
+ ```
86
+
87
+ 4. Optionally fetch a connection string for the new branch:
88
+
89
+ ```bash
90
+ neon connection-string <branch-name>
91
+ ```
92
+
93
+ ## Create a Schema-Only Branch (Beta, Sensitive Data)
94
+
95
+ Use this when users must not copy production rows into the test branch.
96
+
97
+ Link: https://neon.com/docs/guides/branching-schema-only.md
98
+
99
+ ### Steps
100
+
101
+ 1. Settle the tool path first (see [Selection order](#selection-order)): verify the CLI with `neon --version`, and fall back to MCP only if the CLI isn't usable.
102
+ 2. Create the schema-only branch:
103
+
104
+ ```bash
105
+ neon branches create \
106
+ --name <schema-only-branch-name> \
107
+ --parent <parent-branch-id-or-name> \
108
+ --schema-only \
109
+ --expires-at 2026-12-15T18:02:16Z
110
+ ```
111
+
112
+ If multiple projects exist, include `--project-id`:
113
+
114
+ ```bash
115
+ neon branches create \
116
+ --name <schema-only-branch-name> \
117
+ --parent <parent-branch-id-or-name> \
118
+ --schema-only \
119
+ --project-id <your-project-id> \
120
+ --expires-at 2026-12-15T18:02:16Z
121
+ ```
122
+
123
+ ### Beta Support Guidance (Mandatory)
124
+
125
+ Schema-only branching is in Beta. If users report unexpected behavior, errors, or missing capabilities:
126
+
127
+ 1. Ask them to share feedback in the Neon Console:
128
+ - https://console.neon.tech/app/projects?modal=feedback
129
+ 2. Recommend opening a support conversation in the Neon Discord:
130
+ - https://discord.gg/92vNTzKDGp
131
+
132
+ ## Reset from Parent
133
+
134
+ Use this when a child branch has drifted and the user wants a clean refresh from the parent branch's latest schema and data.
135
+
136
+ Link: https://neon.com/docs/guides/reset-from-parent.md
137
+
138
+ ### What it does
139
+
140
+ - Fully replaces the child branch schema and data with the parent's latest state.
141
+ - Does not merge; local changes on the child branch are lost.
142
+ - Keeps the same connection details, but active connections are briefly interrupted during reset.
143
+
144
+ ### When to recommend it
145
+
146
+ - Development or staging branch is too far behind production.
147
+ - User wants to start a new feature from a clean parent-aligned state.
148
+ - Team wants to refresh staging from production for consistent testing baselines.
149
+
150
+ ### Hard constraints and blockers
151
+
152
+ - Only child branches can be reset (root branches and schema-only root branches cannot be reset from parent).
153
+ - If the target branch has children, reset is blocked until those child branches are removed.
154
+ - After a parent branch is restored from snapshot, reset-from-parent may be unavailable for up to 24 hours.
155
+ - Reset-from-parent always uses the current parent state; use Instant restore for point-in-time recovery needs.
156
+
157
+ ### CLI usage
158
+
159
+ ```bash
160
+ neon branches reset <id|name> --parent --preserve-under-name <backup-branch-name>
161
+ ```
162
+
163
+ If project context is not already set, include the project ID:
164
+
165
+ ```bash
166
+ neon branches reset <id|name> --parent --preserve-under-name <backup-branch-name> --project-id <project-id>
167
+ ```
168
+
169
+ `--preserve-under-name` keeps the pre-reset state as a backup branch for rollback, but adds one extra branch to clean up later.
170
+
171
+ Optional context setup to avoid repeating `--project-id`:
172
+
173
+ ```bash
174
+ neon set-context --project-id <project-id>
175
+ ```
176
+
177
+ ### Console and API usage
178
+
179
+ - **Console:** Open the target child branch, then select **Reset from parent** from **Actions**.
180
+ - **API:** Use the restore endpoint for the branch and set `source_branch_id` to the parent branch ID.
181
+
182
+ ## Notes and Caveats
183
+
184
+ - Schema-only branches are for structure-only cloning and sensitive/compliant data controls.
185
+ - Schema-only branches are independent root branches (no parent branch and no shared history), so reset-from-parent does not apply.
186
+ - For migration testing that depends on real-world row shapes, volumes, and edge cases, prefer normal branches.
187
+ - Root branch allowances and per-branch storage limits can cap how many schema-only branches users can create.
188
+ - If a user is unsure, default recommendation is:
189
+ - **Normal branch** for migration validation.
190
+ - **Schema-only branch** for compliance and privacy constraints.
191
+
192
+ ## Useful Workflow Patterns
193
+
194
+ If the user asks for process recommendations (not just a single command), suggest these:
195
+
196
+ - **One branch per PR:** Create branch when PR opens, delete when merged/closed, keep migration tests isolated.
197
+ - **One branch per test run:** Create branch at pipeline start, run migrations/tests, delete at end for deterministic CI.
198
+ - **One branch per developer:** Isolated dev environments with production-like shape; avoid team collisions on shared test data.
199
+ - **PII-aware branching:** If production has sensitive data, derive dev/PR branches from an anonymized branch or use schema-only branches.
200
+ - **Ephemeral lifecycle hygiene:** Set branch expiration and automate cleanup so old branches do not accumulate avoidable storage/history cost.
201
+
202
+ ### Post-creation environment update prompt
203
+
204
+ After branch creation, ask whether the user wants to update local environment credentials to point at the new branch.
205
+
206
+ - Ask: "Do you want me to update your `.env` `DATABASE_URL` to this new branch connection string?"
207
+ - If yes, write the new branch connection string to the requested env file/key.
208
+ - If no, leave credentials unchanged and share the connection string for manual use.
209
+ - Never overwrite an existing env key without explicit confirmation.
210
+
211
+ ## Neon Infrastructure as Code (`neon.ts`)
212
+
213
+ Beyond creating branches imperatively (CLI / MCP / API above), you can **program what configuration new branches receive** declaratively in `neon.ts` — Neon's infrastructure-as-code file (see the `neon` skill for the full reference). The `branch` property is a function of the branch being evaluated that returns its settings, so every branch born from your project gets a consistent lifecycle and compute profile without per-branch flags.
214
+
215
+ ```bash
216
+ npm i @neon/config
217
+ ```
218
+
219
+ ```typescript
220
+ // neon.ts
221
+ import { defineConfig } from "@neon/config/v1";
222
+
223
+ export default defineConfig({
224
+ branch: (branch) => {
225
+ if (branch.exists) return {}; // never reconcile existing branches
226
+ if (branch.isDefault) return { protected: true };
227
+ if (branch.name.startsWith("preview/") || branch.name.startsWith("dev")) {
228
+ return {
229
+ parent: "main",
230
+ ttl: "7d", // ephemeral: auto-expire 7 days after creation (max 30d)
231
+ postgres: {
232
+ computeSettings: {
233
+ autoscalingLimitMinCu: 0.25, // scale to zero
234
+ autoscalingLimitMaxCu: 1, // keep throwaway branches cheap
235
+ suspendTimeout: "5m",
236
+ },
237
+ },
238
+ };
239
+ }
240
+ return {};
241
+ },
242
+ });
243
+ ```
244
+
245
+ The closure receives a read-only descriptor of the target branch — `name`, `exists`, `isDefault`, `parentId`, and more — and returns the tuning to apply: `parent`, `ttl` (auto-expiry), `protected`, and `postgres.computeSettings`. This is the declarative complement to the **Ephemeral lifecycle hygiene** and per-PR / per-test patterns above: instead of remembering `--expires-at` on every `neon branches create`, the TTL and compute profile live in version control and apply to every matching branch.
246
+
247
+ Because `neon checkout` applies this policy when it **creates** a branch, a fresh `preview/*` or `dev-*` branch comes up already expiring and scaled-to-zero. Checking out an _existing_ branch doesn't reconcile it — run `neon deploy` (alias for `neon config apply`) to apply changes to a branch that already exists.
248
+
249
+ ## Branching in CI/CD
250
+
251
+ Common CI/CD use cases for Neon branches:
252
+
253
+ - **Per-PR preview deployments:** Branch on PR open, deploy the preview against it, delete on close. Each PR gets an isolated database branch. Injecting the branch's `DATABASE_URL` into the deployed app is hosting-provider-specific — see [preview-branches-with-cloudflare](https://github.com/neondatabase/preview-branches-with-cloudflare), [preview-branches-with-vercel](https://github.com/neondatabase/preview-branches-with-vercel), or [preview-branches-with-fly](https://github.com/neondatabase/preview-branches-with-fly) for tested patterns.
254
+ - **Migration testing in CI:** Run risky schema changes against a branch with production-like data before merge.
255
+ - **Schema diff visibility:** Use the [schema-diff GitHub Action](https://github.com/marketplace/actions/neon-schema-diff-github-action) to auto-comment a DB-layer diff on the PR.
256
+
257
+ ## Examples
258
+
259
+ ### Example 1: Migration testing with realistic data
260
+
261
+ **User input:** "I need to test a risky migration against production-like data."
262
+
263
+ **Agent output shape:**
264
+
265
+ 1. Recommend a normal branch and explain why.
266
+ 2. Share docs link: https://neon.com/docs/introduction/branching
267
+ 3. Check the tool path first (CLI with `neon --version`; MCP only if the CLI isn't usable).
268
+ 4. Provide commands:
269
+ - `neon branches create --name migration-test --parent main --expires-at 2026-12-15T18:02:16Z`
270
+ - `neon connection-string migration-test`
271
+
272
+ ### Example 2: Sensitive data development workflow
273
+
274
+ **User input:** "We cannot copy production data because of compliance."
275
+
276
+ **Agent output shape:**
277
+
278
+ 1. Recommend schema-only branch and explain why.
279
+ 2. Share docs link: https://neon.com/docs/guides/branching-schema-only
280
+ 3. Check the tool path first (CLI with `neon --version`; MCP only if the CLI isn't usable).
281
+ 4. Provide command:
282
+ - `neon branches create --name compliance-dev --parent main --schema-only --project-id <your-project-id> --expires-at 2026-12-15T18:02:16Z`
283
+ 5. Mention Beta support path:
284
+ - https://console.neon.tech/app/projects?modal=feedback
285
+ - https://discord.gg/92vNTzKDGp
286
+
287
+ ## Further Reading
288
+
289
+ - https://neon.com/docs/guides/branch-expiration.md
290
+ - https://neon.com/docs/guides/neon-github-integration.md
291
+ - https://neon.com/docs/ai/neon-mcp-server.md
292
+ - https://neon.com/branching