@vibecloudtr/cli 0.0.0-stage → 0.0.1

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.
package/README.md CHANGED
@@ -1,3 +1,1377 @@
1
- # Temporary Holding Version
1
+ # cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Developer-facing tools for the vibecloud platform.
4
+
5
+ | Binary | What it does |
6
+ | --------- | ------------------------------------------------------- |
7
+ | `cmd/cli` | The `vibe` CLI — talks to the control-plane GraphQL API |
8
+
9
+ Split out of `base/` on 2026-08-11 — `base` is documentation only. The MCP
10
+ server moved out on 2026-08-14 (commit `f86568e`); it lives in `../mcp`.
11
+
12
+ Shared packages live in the sibling `api/` repo and are imported from there, so
13
+ this repo expects the workspace layout CI uses: `api/` beside `cli/`. Today that
14
+ is `api/pkg/errcodes` (the error-code registry) and `api/apiversion` (the API
15
+ group, so the emitted `App` manifest cannot drift from the CRD).
16
+
17
+ make build test lint check
18
+
19
+ Design docs and the decision log are in `../base/docs`.
20
+
21
+ ## Releasing to npm — the checklist
22
+
23
+ 🔴 **`@vibecloudtr/cli` is not on npm yet (checked 2026-09-13: 404).** Every page of
24
+ the site, `llms.txt` and the three agent files instruct `npx @vibecloudtr/cli …`, so
25
+ the first publish is the single most-repeated promise on the site becoming true.
26
+ Publishing is done by hand from the owner's machine with an npm access token. There
27
+ is no CI release workflow and no provenance attestation: npm only issues provenance
28
+ for public source repositories, and this one is private.
29
+
30
+ 1. **npm side, once.** Create the `vibecloudtr` organisation on npmjs.com and a
31
+ granular access token scoped to publish `@vibecloudtr/*`. Public packages under
32
+ an org are free. Store the token in your user-level `~/.npmrc`, never in the
33
+ repo's:
34
+
35
+ npm config set //registry.npmjs.org/:_authToken <token>
36
+
37
+ 2. **Version, every release.** Releases start at `0.0.1`. Nothing past `1.0.0` is
38
+ published before launch; `scripts/check-package.mjs` refuses it.
39
+
40
+ npm version <x.y.z> --no-git-tag-version # commit "Release x.y.z"
41
+ git tag v<x.y.z>
42
+
43
+ 3. **Exercise the packed tarball** once against a live control plane (`npm pack` →
44
+ `npx ./vibecloudtr-cli-*.tgz login` → `project create` → `deploy start` on the
45
+ local slice). Nothing automated does this.
46
+ 4. **Publish.** From `cli/`:
47
+
48
+ npm pack --dry-run # eyeball the file list: dist/, commands.json, README, ENVIRONMENT, LICENSE
49
+ npm publish
50
+
51
+ `prepublishOnly` runs `make check` and `scripts/check-package.mjs` first and
52
+ aborts the publish if either fails. `npm publish` tags the version `latest`,
53
+ which is what `npx @vibecloudtr/cli` resolves to for everyone.
54
+ 5. **Verify, from any machine:**
55
+
56
+ npm view @vibecloudtr/cli version dist-tags
57
+ npx --yes @vibecloudtr/cli@latest --version
58
+ curl -s https://vibecloud.tr/docs.md | grep -c vibecloudtr/cli # the docs already point at it
59
+
60
+ 6. **Afterwards.** `../mcp/REGISTRY.md` lists the MCP registry submissions that
61
+ were prepared but not sent; an installable CLI is their precondition.
62
+
63
+ ## Talking to the control plane
64
+
65
+ Every command below is a client of the GraphQL API (decisions 31/54; dec. 17
66
+ makes the CLI a consumer of that surface, not a second API). The contract is
67
+ `../api/docs/api/schema.graphql` and `../base/docs/api-contract.md`.
68
+
69
+ VIBECLOUD_API full GraphQL URL, path included. Default https://api.vibecloud.tr/query
70
+ VIBECLOUD_ORG default organisation slug, so --org can be omitted
71
+ VIBECLOUD_OAUTH_CLIENT_ID registered OAuth client id (login only; defaults to vibe-cli)
72
+ VIBECLOUD_OAUTH_RESOURCE the audience the token must carry (login only; defaults to the public API when VIBECLOUD_API is unset)
73
+
74
+ ⚠ The path is **`/query`**, not `/graphql`. The API mounts gqlgen on `/query` and
75
+ nothing on `/graphql`, and the web console posts to `/query` too. In dev the
76
+ playground handler sits on `"/"` and catches everything else, so `POST /graphql`
77
+ answers **HTTP 200 with a page of HTML** — not a status any error path inspects,
78
+ so a client pointed there reports an unparseable response rather than a bad URL.
79
+
80
+ 🔴 **`VIBECLOUD_API` must be `https://`, and that is checked at startup.** Every
81
+ command sends `Authorization: Bearer <token>` to it, and login fetches the OAuth
82
+ discovery document from its origin — so a cleartext value exposed the credential
83
+ on the first call _and_ let whoever controlled the network name the
84
+ `token_endpoint` the authorization code and refresh token were posted to. The
85
+ only exception is **literal loopback** (`http://127.0.0.1`, `http://[::1]`),
86
+ which never reaches a network; `http://localhost` is deliberately excluded
87
+ because it resolves through DNS. The same check runs on the
88
+ `authorization_endpoint` and `token_endpoint` the discovery document names, and
89
+ on the `token_url` stored in the credential file.
90
+
91
+ A project is named by its **slug**, because that is what a human types. The
92
+ GraphQL `ID` is opaque and must not be parsed (`api-contract.md` §3), so a slug
93
+ is resolved through `projectBySlug` — one extra round trip and no string surgery.
94
+
95
+ ## What the CLI tells the API about itself
96
+
97
+ Every request — the API calls and the OAuth login, refresh and device-poll
98
+ requests — carries `User-Agent: vibecloud-cli/<version> (<agent>)`, where
99
+ `<agent>` is the editor the CLI detected around it — `claude-code`, `cursor`,
100
+ `vscode`, `windsurf` — or `none`; the same fingerprint rule `vibe init` uses to
101
+ pick an editor. The API collapses it to a closed family and uses it for one
102
+ thing: which kind of client brought an account to its first deploy
103
+ (VIBEC-326). That is the CLI's only telemetry: a header on requests it was
104
+ making anyway, no separate send, no OS or machine name in it, and nothing to
105
+ opt out of. It is disclosed in the aydınlatma metni with the rest of the
106
+ visitor/console analytics.
107
+
108
+ ## `VIBECLOUD_OUTPUT=json` — the machine surface
109
+
110
+ Every command prints **exactly one JSON document on stdout**, and nothing else.
111
+ The error text still goes to stderr and the exit code is unchanged.
112
+
113
+ $ VIBECLOUD_OUTPUT=json vibe project list | jq -c '{ok, command}'
114
+ {"ok":true,"command":"project list"}
115
+
116
+ $ VIBECLOUD_OUTPUT=json vibe deploy force | jq -c '.error.missing | length'
117
+ 2
118
+
119
+ `{"ok": …, "command": …, "data": …}` on success; `{"ok": false, "command": …,
120
+ "error": {"code", "message", "action", "fix", "details", "missing", "alternative"}}` on a failure
121
+ or a refusal. A refusal is a real answer with `ok: false`, and its prerequisites
122
+ are an array rather than a paragraph. `fix` (VIBEC-324) is what to do next as
123
+ the API stated it — `extensions.fix` verbatim, or the vendored registry's for
124
+ the same code when a server predates the field: `vibe login`,
125
+ `retry after details.retryAfter`, `settle the invoice at https://vibecloud.tr/billing`.
126
+ `details` is the object the fix refers to — `{"retryAfter": 60}` under
127
+ RATE_LIMITED, `{"traceId": …}` under INTERNAL — verbatim from the API and
128
+ absent when it sent none.
129
+ Human mode prints the same text as the **last line**, `fix: …`, with the
130
+ details as ` key: value` lines above it, so an agent that reads only the tail
131
+ gets the command. `fix` accompanies failures the **API** answered or
132
+ reported; a refusal the CLI makes on its own (a missing `--project`, an unset
133
+ `VIBECLOUD_API`) borrows a code but carries no `fix` — the registry's fix for
134
+ that code is the API's remedy, not this one, and `message`/`missing` are the
135
+ remedy here. A registry fix naming a `details.*` key is withheld when the
136
+ error carries no such key. `action` remains the Turkish sentence a
137
+ person reads; the two differ on purpose. Absent (JSON) / not printed (human)
138
+ when the code has no customer action. **No token or config value is ever in a
139
+ document** — `vibe config set` reports variable names only, and `vibe login`
140
+ reports the account and expiry, never the bearer.
141
+
142
+ 🔴 **This was broken across the whole surface until 2026-08-15**, in a way every
143
+ check that looked for the artefact passed: the mode was read, threaded into every
144
+ command, documented in `ENVIRONMENT.md` — and `Output.Print`'s machine branch was
145
+ `fmt.Printf("%+v")` on an already-formatted string, which is the human output
146
+ byte for byte. `VIBECLOUD_OUTPUT=json vibe project list` printed a box-drawing
147
+ table; `vibe logs` and `vibe token create` printed something `jq` rejects (exit
148
+ 5). See `ENVIRONMENT.md` for the captured output and the guard that now enforces
149
+ it (`internal/cli/machineoutput_test.go`, which drives every dispatchable command
150
+ and checks its own table against the dispatch switch).
151
+
152
+ ## `vibe init` — the paste-this-to-your-AI command (VIBEC-321)
153
+
154
+ One command from a cloned repository to a live `*.vibeapp.tr` URL:
155
+
156
+ npx @vibecloudtr/cli init --package LUNA
157
+
158
+ It runs, in order, the commands a person would type — `login`, `project create`, `app create`,
159
+ `mcp install` and `deploy start` — through the same functions those commands
160
+ use, then follows the app until it is `LIVE` (`--wait`, default 900 s) and
161
+ prints the URL. Every step is reused, never redone: an existing project or app
162
+ is kept, and a stored credential is used as is.
163
+
164
+ **With no credential it is a device login** (`--yes` or not), and the
165
+ browser is opened on the device link with the package and the project in its
166
+ query (`/device?user_code=…&plan=luna&project=crm`; the link is printed too,
167
+ for a machine with no desktop). The person may have no account yet: the
168
+ console's `/device` leads through sign-up, address verification and the
169
+ invoice profile, carrying the link as the return path, then to the approval
170
+ screen. Approving there for a project lands on `/device/approved`, which waits
171
+ for this process to create the project and sends the same tab to its checkout
172
+ (a 14-day trial or a first charge). The CLI meanwhile polls the token
173
+ endpoint, then the project's phase, and carries on the moment the subscription
174
+ has started. The device code lives 30 minutes, long enough for the sign-up.
175
+
176
+ What it derives, and the flag that overrides each: the project slug from
177
+ `package.json`'s `name` (scope stripped) or the directory name (`--project`);
178
+ the repository from `git remote get-url origin`, an SSH remote rewritten to
179
+ its HTTPS form — a remote that does not rewrite to `https://` (an SSH alias, a
180
+ non-default port) is refused rather than attached, because the server accepts
181
+ any string and the build would fail later on a repository it cannot clone
182
+ (`--repo`); the editor from the environment the editor leaves
183
+ behind — `CLAUDECODE` → claude-code, `CURSOR_TRACE_ID` → cursor,
184
+ `TERM_PROGRAM=vscode` → vscode, with Cursor and Windsurf told apart by the
185
+ askpass helper's path (`--editor`). An editor it cannot recognise is
186
+ reported and skipped, never guessed: a wrong guess writes a config file nobody
187
+ asked for. An editor config it cannot write (a settings file with
188
+ comments, a foreign entry under our key) is likewise reported and skipped.
189
+ `--no-mcp` and `--no-deploy` skip those steps.
190
+
191
+ An App exists for every project; what `init` attaches is its **source**
192
+ (`sourceRepo` null means connected to nothing), so a project that already has
193
+ one is never re-attached. The deploy is followed by identity, not by phase
194
+ alone: right after `deployApp` an app that was LIVE still reads LIVE for the
195
+ previous revision, so `init` settles on a terminal phase only once the phase
196
+ changed or the deploy id / revision did. A build that FAILED is one error
197
+ document (`BUILD_FAILED`, with the registry fix) and exit 1.
198
+
199
+ 🔴 **A new project needs `--package` (LUNA, TERRA, SOL) and there is no
200
+ default.** The packages are priced differently and there is no free tier, so
201
+ a defaulted package would be a billing decision taken on the customer's
202
+ behalf. The prompt block on the website names it in the customer's own
203
+ copy-paste, which is where that decision belongs.
204
+
205
+ **A new project is built once its subscription has started** (dec. 216): in a
206
+ self-serve organization `project create` leaves it `AWAITING_PAYMENT`, and
207
+ `init` prints the console's checkout link (and opens it, when no login ran in
208
+ this process: after a device login the approving tab is already headed there)
209
+ and waits there — up to 30 minutes,
210
+ reading the project's phase every 5 s — then goes on to `app create` once the
211
+ subscription (a first charge, or the trial with the card vaulted) has released
212
+ it (VIBEC-547). A project found still held on a re-run is waited on the same
213
+ way: its link comes from `Project.checkoutUrl`, so no command is sent to a
214
+ project no cell has. A wait that runs out is exit 1 with `PAYMENT_REQUIRED` and
215
+ the link in `details.checkoutUrl`; once the subscription has started, the same
216
+ command picks up where it stopped. A project whose subscription never starts
217
+ is released 48 hours after its creation. An enterprise organization is invoiced
218
+ instead and never waits.
219
+
220
+ Under `VIBECLOUD_OUTPUT=json` the sub-steps write into a private buffer and
221
+ `init` emits **one** document with a block per step — `login`, `project`,
222
+ `app`, `mcp`, `deploy` — each saying whether it ran, what it created and,
223
+ when skipped, why; `deploy.live` is true only when the app reached `LIVE`
224
+ inside the wait. A wait that runs out is not a failure: the document says the
225
+ phase the app was in, and the exit code stays 0. The subscription wait is the
226
+ exception — nothing after it ran, so running out of it is the `PAYMENT_REQUIRED`
227
+ error document and exit 1. Its lines, like the device code, go to stderr in
228
+ human form: stdout carries only the one document.
229
+
230
+ ## `VIBECLOUD_TOKEN` — no login at all (VIBEC-336)
231
+
232
+ A token from `vibe token create`, exported, makes every command work with no
233
+ login round-trip — CI, a container:
234
+
235
+ VIBECLOUD_TOKEN=vibe_pat_… npx @vibecloudtr/cli project create --name crm --package LUNA
236
+
237
+ When `VIBECLOUD_TOKEN` is set it is the whole credential: the stored one is
238
+ not read, nothing is refreshed, and the API's `UNAUTHENTICATED` (with the fix
239
+ `vibe login`) is the answer once it has expired or been revoked. Anything that is not a
240
+ `vibe_pat_` value is refused at startup rather than sent. While the variable is
241
+ set it outranks everything: `vibe login` stores a credential that is ignored
242
+ until you `unset VIBECLOUD_TOKEN`, and `vibe logout` revokes and deletes the
243
+ stored credential but leaves the variable's token valid (it says so). See ENVIRONMENT.md.
244
+
245
+ ## `vibe login`
246
+
247
+ `vibe login` performs the **OAuth 2.1 authorization-code flow with PKCE (S256)
248
+ over an RFC 8252 loopback redirect**, then renews from the refresh token as
249
+ commands need it. It binds an ephemeral port on `127.0.0.1`, prints (and tries to
250
+ open) an authorization URL, and waits for the callback.
251
+
252
+ **Why that flow, read off the server rather than a doc:**
253
+
254
+ - `oauth.Metadata` advertises `authorization_code`, `refresh_token` and — where
255
+ the deployment enables it — the RFC 8628 device grant (VIBEC-322, below).
256
+ OAuth 2.1 removed implicit and password, and there is no client-credentials
257
+ grant, so neither was ever an option.
258
+ - PKCE is mandatory and **S256 only**, and `token_endpoint_auth_methods_supported`
259
+ is `["none"]` — a public client, which is what a CLI is.
260
+ - `oauth.Server.ValidateRedirectURI` waives the **port** for a client registered
261
+ `Native` and nothing else: `http`, host `127.0.0.1` or `::1` (never
262
+ `localhost`, which DNS can point elsewhere), and the **path** must still match
263
+ a registered one. That is what makes an ephemeral loopback listener workable.
264
+
265
+ ### `vibe login --device` — no browser on this machine
266
+
267
+ An AI agent driving the CLI in a terminal, a container or an SSH session has no
268
+ browser to open and no loopback the person could reach, so the code flow above
269
+ cannot complete. `--device` is the RFC 8628 device authorization grant:
270
+
271
+ 1. `POST /oauth/device_authorization` (client_id, scope, resource) returns a
272
+ `device_code` this process keeps and a `user_code` it prints, with the
273
+ address to open — the web app's `/device`.
274
+ 2. The person opens that address in **any** browser where they are signed in
275
+ to the console (a phone will do), types the code, reads which client wants
276
+ which scopes, and approves. The API's `/oauth/device` page accepts a
277
+ browser session only — never a bearer token — and binds the approving POST
278
+ to that session, the organisation on screen and the code with an HMAC.
279
+ 3. The CLI polls `/oauth/token` with
280
+ `grant_type=urn:ietf:params:oauth:grant-type:device_code` at the server's
281
+ `interval` (5 s). `authorization_pending` keeps polling; `slow_down` adds
282
+ five seconds to the interval and never retries early; `access_denied` and
283
+ `expired_token` stop with a reason. The client gives up at the server's
284
+ `expires_in` (30 min) or its own 30-minute ceiling, whichever is sooner.
285
+
286
+ The credential that comes back is the same shape as the browser flow's, stored
287
+ in the same file, renewed by the same refresh path. ⚠ **The device_code is never
288
+ printed** — only the user code and the address are, which is exactly what an
289
+ agent should relay to its human. A deployment that does not advertise
290
+ `device_authorization_endpoint` (`OAUTH_DEVICE_VERIFICATION_URI` unset on the
291
+ API) is refused by name before any request is made.
292
+
293
+ **Why not the console session.** `/auth/login` returns a `__Host-vc_session`
294
+ cookie and `authenticate` does read it — from the Cookie header. Deliberately not
295
+ used: it would make the CLI collect the account password, put a long-lived
296
+ console credential on disk, and hand the CLI the `browser` credential kind, which
297
+ is the one thing `@dangerous` accepts. Dec. 81 says a non-interactive credential
298
+ must not reach those mutations, so borrowing a cookie would **defeat** that gate
299
+ rather than satisfy it.
300
+
301
+ **Why a PAT is not minted either.** `createToken` carries `@dangerous`, so the
302
+ CLI cannot create one — only the console can. A `vibe_pat_` value pasted into
303
+ `~/.vibecloud/token` still works, and the loader accepts that bare form
304
+ deliberately.
305
+
306
+ ### 🔴 One value the server publishes nowhere, so it is still required
307
+
308
+ VIBECLOUD_OAUTH_RESOURCE or --resource # required
309
+ VIBECLOUD_OAUTH_CLIENT_ID or --client-id # defaults to `vibe-cli`
310
+
311
+ - **client_id — defaulted to `vibe-cli`, in every environment including prod.**
312
+ A `client_id` is this program's public name, not a deployment secret and not a
313
+ per-deployment value, so one default belongs in the binary and every deployment
314
+ registers the same entry. ⚠ **`vibe-cli` must therefore be in the deployment's
315
+ `OAUTH_CLIENTS`** — only `local/scripts/api.sh` has it today. A deployment
316
+ without it answers `invalid_client`, which the preflight below catches before a
317
+ browser opens and reports by name; that is a louder failure than "client_id not
318
+ set", and it names the fix instead of sending someone to look up a value only
319
+ the deployment's operator knows. There is still no dynamic client registration
320
+ — deliberately; the package comment in `api/internal/oauth/server.go` notes the
321
+ 2026-07-28 MCP revision deprecates DCR in favour of CIMD — so registration stays
322
+ out of band.
323
+ - **resource — defaulted to `https://api.vibecloud.tr` when `VIBECLOUD_API` is
324
+ unset (VIBEC-322), and NOT defaulted for any other deployment.** The public
325
+ API's audience is its own origin and is the one value this binary can know;
326
+ everything below is about the custom-deployment case, where `vibe login` is
327
+ still not zero-config.
328
+ The issued token carries exactly this value as its `aud`, and `authenticate`
329
+ compares it against the deployment's explicit `OAUTH_API_RESOURCE` (since the
330
+ 2026-08-15 API/MCP audience split — previously the positional
331
+ `OAUTH_RESOURCES[0]`); a token audienced anywhere else is treated as **no
332
+ credential at all**. `oauth.Server.Metadata` advertises
333
+ `resource_indicators_supported: true` and **no identifiers**, and the API serves
334
+ no RFC 9728 protected-resource metadata for itself, so there is nowhere to read
335
+ it from. 🔴 **Deriving it is actively unsafe now that a deployment has two
336
+ distinct audiences**: `<issuer>/mcp` is the MCP server's resource, not the
337
+ API's — exporting that here mints a token GraphQL refuses outright. For the
338
+ local slice the correct value is the issuer itself,
339
+ `https://local.vibecloud.tr:8443` (no `/mcp`). **The fix is upstream in
340
+ `api/`**: serve `/.well-known/oauth-protected-resource`. Until then this one is
341
+ exported by hand.
342
+
343
+ Scopes _are_ discovered — the metadata's `scopes_supported` — but that is the
344
+ **deployment's** vocabulary, not the **client's** registration, and
345
+ `oauth.Server.ValidateScopes` bounds the request by the latter. A client
346
+ registered for a subset is refused with `invalid_scope` (measured: a client
347
+ registered for `mcp:tools` alone answered `scope "mcp:db" is not permitted for
348
+ this client`), so `--scope` / `VIBECLOUD_OAUTH_SCOPES` exists to narrow it. It is
349
+ optional; empty means "ask for what the server advertises".
350
+
351
+ ### The client must be registered `Native: true`, on a `/callback` path
352
+
353
+ The request is sent **once from the CLI before the browser opens**, to find out
354
+ whether the server will accept its shape. 🔴 Without that, the commonest
355
+ first-run failure is invisible: `handleAuthorize` answers an unknown `client_id`
356
+ or an unregistered `redirect_uri` with an HTTP **400 JSON body** rather than a
357
+ redirect — deliberately, since it has no validated URI to bounce an error to —
358
+ and that answer goes to the _browser_, so the loopback listener waits for a
359
+ callback that never comes. Measured on 2026-08-15: an unregistered `client_id`
360
+ left `vibe login` on "giris bekleniyor..." for the full five minutes. It now
361
+ fails in under a second, naming the client and `OAUTH_CLIENTS`.
362
+
363
+ The preflight is side-effect free: with no session cookie the endpoint cannot
364
+ attribute the request to anyone, so it never issues a code.
365
+
366
+ Two registration mistakes and what they look like, both measured against a live
367
+ API:
368
+
369
+ | Registration | Answer |
370
+ | --------------------------------------- | ----------------------------------------------------------------------- |
371
+ | `client_id` absent from `OAUTH_CLIENTS` | `invalid_client: unknown client_id` |
372
+ | registered but `Native: false` | `invalid_request: redirect_uri does not exactly match a registered URI` |
373
+
374
+ The port is waived for a native client; the **path is not**. Register a loopback
375
+ URI whose path is `/callback` (the port in the registration is ignored).
376
+
377
+ ### What is stored, and where — ⚠ a cross-repo contract
378
+
379
+ `~/.vibecloud/token` — **the same path**, because renaming it would sign out
380
+ every existing user silently. Written atomically at mode **0600**:
381
+ `os.WriteFile`'s permission argument applies only when it _creates_ the file, so
382
+ writing over a pre-existing 0644 token file left it world-readable.
383
+
384
+ **Two forms are read; one is written.** Anything whose first non-space byte is
385
+ `{` is the JSON document below. Anything else is taken as an opaque bearer value,
386
+ trimmed — that is a `vibe_pat_` PAT pasted from the console, and it is also what
387
+ a hand-injected access token looks like. The discrimination is on the first byte,
388
+ never on a prefix guess about the token itself.
389
+
390
+ ```json
391
+ {
392
+ "access_token": "eyJhbGciOiJFZERTQSJ9....", // required; Bearer value
393
+ "refresh_token": "…", // omitted for the opaque form
394
+ "expires_at": "2026-08-15T00:36:40+03:00", // RFC 3339; access-token expiry
395
+ "token_url": "https://…/oauth/token", // where to run the refresh grant
396
+ "client_id": "vibe-cli", // presented on the refresh grant
397
+ "issuer": "https://…", // the AS that minted it
398
+ "scopes": ["mcp:tools", "mcp:db"] // as granted, not as requested
399
+ }
400
+ ```
401
+
402
+ **A reader that only presents a credential** needs `access_token` and should
403
+ treat `expires_at` as advisory. **A reader that also renews** must run the refresh
404
+ grant against `token_url` with `client_id`, and must **persist the rotated
405
+ `refresh_token`** — `oauth.Server.RefreshAccessToken` consumes the one it is
406
+ presented, so a reader that renews without writing back leaves the next process
407
+ holding a spent token. `expires_at` absent (or zero) means _no client-side
408
+ expiry_: that is the opaque form, where only the API decides when the credential
409
+ dies.
410
+
411
+ Access tokens live **15 minutes** (`oauth.AccessTokenTTL`), so renewal is the
412
+ common path, not an edge case — and refresh tokens **rotate**, so the new one is
413
+ persisted before the command runs. A renewal that is not written back makes a
414
+ login last exactly one command.
415
+
416
+ ⚠ `token_url` is checked against the same **https-or-literal-loopback** rule as
417
+ `VIBECLOUD_API` before a refresh token is posted to it. The file is a contract
418
+ other tools write, and a `token_url` naming an `http://` host would have had every
419
+ renewal hand a live credential to it in the clear.
420
+
421
+ ⚠ **The mode is checked on READ too, not only on write, and the DIRECTORY with
422
+ it.** `Save` always ends at 0600 and tightens `~/.vibecloud` to 0700, so a
423
+ credential this CLI produced is safe — but the bare form above is documented as
424
+ something a person pastes in, and `echo … > ~/.vibecloud/token` under the usual
425
+ umask creates it **0644**: a live bearer token every account on the machine can
426
+ read. A 0600 file in a group-writable directory is worse still, because it can be
427
+ **replaced** and the next command presents somebody else's credential. `Load`
428
+ narrows both and **names what it narrowed** on the next command rather than
429
+ repairing it in silence, because doing it now does not undo however long it sat
430
+ there.
431
+
432
+ ### `vibe logout` ends the session on the server, then deletes the file
433
+
434
+ A `vibe login` credential carries a refresh token that stays valid for 400 days
435
+ from its last use (`oauth.RefreshTokenTTL`; rotation renews it on every use, so a
436
+ CLI in use never has to log in again). `vibe logout` therefore revokes it first,
437
+ at the authorization server that **minted** it (RFC 7009: the `revocation_endpoint`
438
+ of the discovery document found from the credential's own `token_url`, never from
439
+ `VIBECLOUD_API`, which may be another deployment that answers 200 for a token it
440
+ never issued), then **removes** the file:
441
+
442
+ - the **refresh token** stops working immediately, on every machine holding a copy;
443
+ - the **access token** lives out the rest of its 15 minutes
444
+ (`oauth.AccessTokenTTL`): it is a signed JWT and cannot be revoked.
445
+
446
+ 🔴 **A failed revoke keeps the file.** It holds the only copy of the token a retry
447
+ can end, so the command exits non-zero, `deleted` and `serverSessionEnded` are
448
+ `false`, and running `vibe logout` again once the API answers finishes the job.
449
+ `vibe logout --local` deletes the file without contacting the server, for someone
450
+ who accepts that a copy stays live; a password reset ends every refresh token the
451
+ account holds (`handleResetPassword` calls `RevokeRefreshForSubject` with the
452
+ user id). A token another `vibe` process rotated in while logout ran is revoked
453
+ too, with one window left open: a process that has already exchanged the old
454
+ token but not yet written the new one can write it back after logout deleted
455
+ the file (and logout then reports `serverSessionEnded: true`); stop other `vibe`
456
+ processes before logging out on a shared machine. A credential that has a
457
+ refresh token but lacks the fields to revoke it is refused, like an unreadable
458
+ one, unless `--local`. A PAT (`vibe_pat_…`) is not revoked here: the command
459
+ deletes it from this machine and says to revoke it from the console's access-key
460
+ list (a password reset does not revoke access keys).
461
+
462
+ ### What login prints about your organisation, and why it is two lines
463
+
464
+ `vibe login` reports the org the **credential is bound to** (the token's `org_id`
465
+ claim, which is what `handleAuthorize` actually bound) separately from the orgs
466
+ the **account belongs to** (`Query.orgs`). 🔴 They are different questions:
467
+ `queryResolver.Orgs` returns every org the _user_ is a member of, not the token's
468
+ scope (found by the mcp lane, `api-contract.md` §4.4). Printing only the second
469
+ would tell a multi-org customer their credential covers organisations it was
470
+ never minted for.
471
+
472
+ ### 🔴 `--org` cannot select a tenancy, and every command now says so the same way
473
+
474
+ A token is minted for **one** organisation — `handleAuthorize` reads it from the
475
+ signed-in human's session and takes none from the caller, a `vibe_pat_` PAT
476
+ carries the tenancy it was created in, and `authenticate` puts that value in
477
+ `id.OrgID` for every request. So `--org` is **checked, never honoured**: the CLI
478
+ acts in the credential's organisation and **refuses**, naming both, when asked
479
+ for another. That holds for `vibe login` (which exits non-zero rather than
480
+ printing a note) and for every command that takes an org — they all resolve
481
+ through one function, `commands.resolveOrg`, and
482
+ `commands/orgscope_test.go` fails the build if a new one does not.
483
+
484
+ `vibe org` marks which row the credential is bound to. Unmarked, the list read
485
+ as a menu of organisations the CLI could work in; on a multi-org account only
486
+ one row of it is true.
487
+
488
+ ⚠ **This is a message, not a boundary — the boundary is the server's, and one
489
+ part of it is missing upstream.** Where the CLI touches the API the server draws
490
+ the line itself: `Query.org(id:)` and `Query.projectBySlug(orgId:)` both compare
491
+ the argument against `scopeOf(ctx)` and return null when it differs. So a
492
+ mismatched `--org` was already refused — as `organizasyon bulunamadi` /
493
+ `proje bulunamadi`, which blames a membership that is fine. The refusal replaces
494
+ that with the truth. 🔴 The hole is `orgs { projects }` in a single document:
495
+ `queryResolver.Orgs` hands back an `Org` for every org the **user** belongs to,
496
+ and `orgResolver.Projects`/`Invoices` then read `obj.ID` rather than the scope
497
+ (`api-contract.md` §4.4). No command composes that traversal and none may — a
498
+ client-side filter over a server that would have answered is not a boundary, so
499
+ the fix is upstream and `TestNoCommandTraversesQueryOrgsIntoOrgScopedCollections`
500
+ keeps the CLI out of it meanwhile.
501
+
502
+ ⚠ A PAT carries no binding this process can read, so with one of those `--org`
503
+ behaves as it always did: it selects, and the server still refuses a mismatch —
504
+ the CLI just cannot name which org it should have been.
505
+
506
+ ### `vibe login` does not widen what the CLI may do
507
+
508
+ The credential is an OAuth access token, which `authenticate` classifies as
509
+ `CredentialKind: "oauth"` with no session. `@dangerous` is an **allowlist**
510
+ requiring `"browser"` plus a satisfied step-up, so `project delete`, `restore`,
511
+ `token create`, `team invite` and `team remove` keep refusing — verified against
512
+ the running API with a genuine token, not assumed.
513
+
514
+ ### What the commands do, and what they refuse
515
+
516
+ | Command | Reads / writes |
517
+ | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
518
+ | `vibe org`, `vibe team list` | `Query.orgs`, `Org.members` |
519
+ | `vibe project list\|status\|create\|resize` | `Org.projects`, `projectBySlug`, `createProject`, `changePackage` |
520
+ | `vibe usage` | `Org.projects`, `Project.usage`, `Project.caps` — org-scoped egress and build minutes printed once, nullable dimensions as `olculmedi` and never as 0 |
521
+ | `vibe app list\|create\|config` | `Project.apps`, `createApp`, `setAppOutputMode` — every nullable field printed as its own "not yet" sentence; `firstLiveAt` is read, never derived from `phase`. `--output-mode static\|standalone` and `--output-dir <dir>` (static only) on `create` and `config` (VIBEC-478); omitted flags are not sent, so the server defaults apply (new app `STANDALONE`, directory `dist`). `config` reports acceptance only: if the app has been built before, the cell rebuilds the current commit with the new mode and the running version serves until that build is live; if it has never been built, nothing is rebuilt and the next `vibe deploy start` uses the new mode. Both cases are printed, since the API cannot tell which applies. An unreported mode prints as `bildirilmedi`, never as standalone |
522
+ | `vibe db connect\|introspect\|security\|migrate` | `Project.endpoints.db`, `Project.schema`, `Project.rlsAdvisor`, `applyMigration` |
523
+ | `vibe deploy start\|cancel\|rollback` | `deployApp`, `cancelBuild`, `rollbackApp`, `App.rollbackTargets` |
524
+ | `vibe domain add\|verify\|list\|release` | `addDomain` (with `--app`, or the project's only app; prints the DCV CNAME **and** the routing record — CNAME to `<app>.vibeapp.tr` for a subdomain, A to the cell's apps address for an apex, VIBEC-373), `verifyDomain`, `Project.domains` (`routingRecord` per row), `removeDomain` |
525
+ | `vibe branch create\|list\|extend\|delete` | `createBranch`, `Project.branches`, `extendBranch`, `deleteBranch` — a preview branch (VIBEC-72): its own database (shared pair on Luna/Terra/Sol, isolated instance on Pro), keys and `<slug>--<name>.api` hostname, TTL 3 d default / 5 d max from creation; `--mode clone` copies production rows and needs the org owner's toggle. `--branch <name>` on `deploy start`, `db migrate` and `db connect` targets it |
526
+ | `vibe config set\|secret\|list\|unset` | `setAppConfig`, `App.config` — `config secret --scope BUILD\|RUNTIME` says where the secret is read: `BUILD` mounts it for `next build` only (a `DATABASE_URL` a prerendered page queries at build time, a Sentry token for sourcemap upload) and turns off cache mounts for that build; `RUNTIME` gives it to the running app only. Without `--scope` nothing is sent and the API's documented default applies: `RUNTIME`. Any other value is refused before the secret is read. `config set --value-from projectEndpoint:api\|projectSecret:anonKey` writes a platform-derived source instead of a literal (VIBEC-469); exactly one of `--value`, `--file`, `--value-from` |
527
+ | `vibe backups` | `Project.backups`, `Project.caps` |
528
+ | `vibe token list\|revoke` | `Query.tokens`, `revokeToken` |
529
+
530
+ **Two classes of refusal, both exiting non-zero with the reason named.** Neither
531
+ is an unknown-flag error: someone who types the command deserves to learn why.
532
+
533
+ - **The credential cannot clear the gate.** `vibe project delete`,
534
+ `vibe restore`, `vibe token create`, `vibe team invite`, `vibe team remove`.
535
+ These mutations carry `@dangerous`, which `api/internal/server/directives.go`
536
+ enforces as an allowlist requiring an interactive console session with a
537
+ satisfied step-up. `authenticate` accepts three credentials — the
538
+ `__Host-vc_session` **cookie**, an OAuth access token, and a `vibe_pat_` PAT —
539
+ and only the cookie is a session, never read from an `Authorization` header. So
540
+ no token this CLI can hold clears it, structurally (dec. 81). **Still true now
541
+ that `vibe login` is real**: measured against the running API on 2026-08-14
542
+ with a genuine access token from the flow, every one of these answered
543
+ `CREDENTIAL_KIND_FORBIDDEN`. Closing the gap would mean the CLI holding a real
544
+ session _and_ being able to answer a step-up challenge — and holding a session
545
+ cookie is deliberately not what login does, because that would defeat the gate.
546
+ - **The API has no field for it.** `vibe deploy force`: there is no cache-invalidating
547
+ field in `DeployAppInput`.
548
+ - **Logs are read, not refused.** `vibe logs` reads an app's runtime logs through
549
+ `App.logs` (VIBEC-492), and `vibe deploy logs` a build's stored output through
550
+ `downloadBuildLog` (VIBEC-535) — both refused here, saying the schema had no log
551
+ field, while those fields served them. `downloadBuildLog` is closed to the
552
+ `vibe login` token and open to a `VIBECLOUD_TOKEN` access key, and the command
553
+ says so when it is refused. Live streaming is deliberately absent
554
+ (`api-contract.md` §7), and tenant request logs are Law 5651 access-log material
555
+ that `cell/cmd/router` keeps in a hash chain — surfacing them is a compliance
556
+ decision rather than a missing resolver.
557
+
558
+ ### 🔴 The CLI must never print a value it was not given
559
+
560
+ Five command files used to fabricate: backup dates for a project with no backup,
561
+ a constant DNS challenge value, `SEC_001`/`SEC_002` advisor codes that exist
562
+ nowhere in this platform, a `vb_tok_`-prefixed "token", and a scripted successful
563
+ deployment. A fabricated value is worse than a stub — a stub is honest, while a
564
+ plausible specific wrong answer is one a customer acts on before doing something
565
+ destructive.
566
+
567
+ `src/cli/nofabrication.test.ts` is the guard. It parses every non-test source
568
+ with the TypeScript compiler API and fails if any **string literal** contains one
569
+ of the removed values, or one of the removed **claims** (`"yeni revizyon
570
+ yayinda"`, `"geri yukleme basarili"`, `"migration uygulandi"`, …). A second test
571
+ asserts every command file either queries the API or refuses, because there is no
572
+ third honest option. It inspects literals rather than file text so the repaired
573
+ functions can keep quoting what they removed.
574
+
575
+ 🔴 It is not a transliteration of the Go original, and the difference is the
576
+ point. Go has no string interpolation, so `ast.BasicLit` was the whole surface; in
577
+ TypeScript `` `derleme tamam (${n}s)` `` puts its text in TemplateHead/Middle/Tail
578
+ nodes, none of which is a StringLiteral. A direct port would have passed over
579
+ every fabricated message the port happened to rewrite as a template — which is
580
+ most of them. All four node kinds are walked, and a test pins that.
581
+
582
+ ### Verifying against a live API
583
+
584
+ `go test ./...` covers the wire format, the refusals and the rendering against an
585
+ `httptest` server speaking the API's shapes, with no network and no docker. That
586
+ is not the same as having talked to the API, so do this by hand:
587
+
588
+ # 1. Bring up Postgres 17, Kafka and the control-plane API on :8443
589
+ cd ../local && bash scripts/postgres.sh up && bash scripts/kafka.sh up && bash scripts/api.sh up
590
+
591
+ # 2. Seed the dev fixtures (needs DEV_FIXTURES=1, which scripts/api.sh sets)
592
+ curl -sk -X POST https://127.0.0.1:8443/dev/fixtures -d '{}' -H 'Content-Type: application/json'
593
+
594
+ # 3. The whole login round trip, from a clean HOME with no hand-injected token
595
+ bash scripts/verify-login.sh
596
+
597
+ # 4. Or drive individual commands by hand, with a throwaway HOME so your real
598
+ # credential is untouched. `vibe login` obtains the credential itself now.
599
+ export HOME=/tmp/vibe-e2e VIBECLOUD_API=https://127.0.0.1:8443/query
600
+ export SSL_CERT_FILE="$(mkcert -CAROOT)/rootCA.pem" # the API serves mkcert TLS
601
+ # the API's own resource — NOT the MCP server's `/mcp` resource, which GraphQL refuses
602
+ export VIBECLOUD_OAUTH_RESOURCE=https://local.vibecloud.tr:8443
603
+ mkdir -p $HOME
604
+ vibe login # open the printed URL in a browser signed in to the console
605
+
606
+ vibe org
607
+ vibe project status --project musteri-crm
608
+ vibe backups --project musteri-crm
609
+ vibe db security --project musteri-crm
610
+ vibe config list --project musteri-crm
611
+ vibe token create # must refuse, exit 1
612
+
613
+ ⚠ **No `VIBECLOUD_OAUTH_CLIENT_ID` above.** The CLI logs in as `vibe-cli`, which
614
+ `local/scripts/api.sh` registers. 🔴 The API reads `OAUTH_CLIENTS` **at boot**, so
615
+ a slice started before that entry was added does not know the client and answers
616
+ `invalid_client` — restart it (`cd ../local && bash scripts/api.sh down && bash
617
+ scripts/api.sh up`) rather than exporting a different client id.
618
+
619
+ ⚠ The console sign-in has to be on the **issuer's** origin, which is not
620
+ necessarily the CLI's. The local slice issues `https://local.vibecloud.tr:8443`
621
+ while `VIBECLOUD_API` points at `https://127.0.0.1:8443`, and
622
+ `__Host-vc_session` is bound to the host that set it.
623
+
624
+ `scripts/verify-login.sh` is the scripted form of all of that: it runs
625
+ `vibe login` against the live API from a clean `HOME` **with no client id
626
+ exported**, plays the browser (console sign-in, then the authorization request,
627
+ following the redirect to the CLI's loopback listener), and then asserts that the
628
+ request carried the compiled-in client id, the credential file's mode, that the
629
+ API returns real data, that `--org` is checked and not honoured, that
630
+ `@dangerous` still refuses, that an expired access token renews and the rotation
631
+ reaches disk, and that logout clears it and states what survives. It is **not** in
632
+ `make check` — it needs a live API, and it **skips loudly** rather than passing
633
+ when one is absent.
634
+
635
+ **Five negative controls run after it**, because everything above passing proves
636
+ only that the happy path works:
637
+
638
+ | # | Control | What it would otherwise hide |
639
+ | --- | -------------------------------------------------------- | ------------------------------------------------------------------------------------- |
640
+ | 1 | an unregistered `--client-id` | the preflight, without which login waits five minutes for a callback that never comes |
641
+ | 2 | `VIBECLOUD_API=http://…` | a bearer token sent in the clear |
642
+ | 3 | a 0644 credential file in a 0777 directory | a secret every account on the machine can read — or replace — used without a word |
643
+ | 4 | a resource the AS mints for and the API refuses | login reporting success while storing a credential no command can use |
644
+ | 5 | `--org` naming a real membership that is not the binding | a command running in the wrong tenancy |
645
+
646
+ Controls 4 and 5 need setup this script does not do for you: `VERIFY_REFUSED_RESOURCE`
647
+ naming a resource the deployment mints for but the API refuses — the local
648
+ slice's own `OAUTH_MCP_RESOURCE` now qualifies, since the 2026-08-15 audience
649
+ split gave it two resources instead of one — and an account in two
650
+ organisations (`VERIFY_OTHER_ORG`). They **skip loudly** without them.
651
+
652
+ What was exercised this way on 2026-08-14, against the seeded `acme` org: every
653
+ read above returned live data; `config set` wrote a value that `config list` read
654
+ back; `config secret` wrote through stdin and the value came back unreadable;
655
+ `domain add` returned a freshly minted challenge (a different value per domain);
656
+ and a deliberately secret-shaped `ENV` value was **refused by the API** with
657
+ `SECRET_IN_PLAINTEXT_ENV` on the operation, which the command reported as a
658
+ failure with exit 1.
659
+
660
+ ⚠ Not covered by the local slice: nothing consumes the bus, so any operation that
661
+ crosses into a cell stays `QUEUED`. `db migrate` therefore reports "still queued,
662
+ not confirmed" and exits non-zero — which is the intended answer, not a bug.
663
+
664
+ What was exercised on **2026-08-15**, against an isolated API on `:8543` (its own
665
+ database, `OAUTH_CLIENTS` copied verbatim from `local/scripts/api.sh`, a second
666
+ `OAUTH_RESOURCES` entry, and a second organisation with the demo account as a
667
+ member — the shared slice was left untouched):
668
+
669
+ - `vibe login` from a clean `HOME` with **nothing but `VIBECLOUD_API` and
670
+ `VIBECLOUD_OAUTH_RESOURCE`** exported. The authorization request carried
671
+ `client_id=vibe-cli` and the flow completed.
672
+ - All five negative controls above, each failing as it must.
673
+ - The multi-org case end to end: login bound the credential to `acme` and listed
674
+ both memberships; `vibe org` marked the bound row; `vibe project list` with no
675
+ `--org` used the binding instead of asking (the previous behaviour **refused**
676
+ here — "birden fazla organizasyona uyesiniz"); `--org ikinci-firma` was refused
677
+ naming both; `vibe login --org ikinci-firma` exited 1.
678
+ - ⚠ Two upstream facts measured with a real access token, both in `api/`, both
679
+ reported and neither worked around here:
680
+ `orgs { projects }` returned the **other** organisation's project count while
681
+ `org(id: <other>)` correctly returned `null` — the §4.4 bypass, confirmed; and
682
+ with `DEV_FIXTURES=1`, `Query.viewer` returns a **seeded** viewer (`id: v_1`,
683
+ `canPerformDangerousActions: true`) to any authenticated caller, so the login
684
+ banner's `hesap:` line under fixtures shows the fixture's address rather than
685
+ the credential's.
686
+
687
+ ## `vibe migrate vercel` (#74)
688
+
689
+ Migrates an existing Vercel-hosted Next.js project onto our standalone stack,
690
+ or a plain Vite SPA onto the static output mode (VIBEC-478): a `vite` dependency,
691
+ a root `index.html` and none of the framework markers (TanStack Start, SvelteKit,
692
+ Astro, Nuxt, React Router framework mode, …). The migrator does not plan those; the
693
+ build refuses SvelteKit, Astro, Nuxt and the rest, and builds TanStack Start and React
694
+ Router framework mode in `standalone` (or `static` in SPA mode / with `ssr: false`) —
695
+ create their App with `vibe app create`. For a Vite SPA the App proposal carries
696
+ `outputMode: static` and `vercel.json`'s `outputDirectory` as `outputDir`, no
697
+ `next.config` is touched, and `api/` functions, middleware and `vercel.json`
698
+ routing rules are reported as what stops working (the static origin serves files
699
+ and falls back to `index.html`, nothing else).
700
+ Local only — it reads the checkout and writes files in it; it deploys nothing.
701
+
702
+ vibe migrate vercel --scan --dir ./proje [--report rapor.md]
703
+ vibe migrate vercel --apply --dir ./proje --app <ad> --project <kimlik>
704
+
705
+ `--scan` classifies every Vercel-specific thing it finds as **mapped /
706
+ rewritten / manual / unsupported** and changes nothing. `--apply` performs the
707
+ rewrites, writes `vibecloud.app.yaml` (an `App` proposal for review) and
708
+ `MIGRATION-REPORT.md` — or refuses, naming every blocker.
709
+
710
+ What it deliberately does **not** touch:
711
+
712
+ - `cacheHandler`, `cacheMaxMemorySize`, `deploymentId` — the builder generates a
713
+ wrapper that forces these (`base/docs/build-deploy-contract.md` §6), and a
714
+ tenant-set `cacheHandler` is rejected with `BUILD_CONFIG_CONFLICT`. They are
715
+ reported as platform-managed.
716
+ - `vercel.json` routing rules — translated into a ready-to-paste `next.config`
717
+ snippet in the report, because splicing async functions into an arbitrary
718
+ JavaScript module cannot be done safely by text edit.
719
+ - Environment **values** — never read into the report, the manifest or the
720
+ machine output. Names, sources and a classification only.
721
+
722
+ It refuses (rather than half-migrating) on: a monorepo, a tenant `cacheHandler`,
723
+ `output: 'export'` or a non-literal `output`, `target: 'serverless'`, two
724
+ `next.config` files, a missing lockfile, a `service_role`-shaped value under a
725
+ `NEXT_PUBLIC_` name (`SECRET_WOULD_BE_PUBLIC`), the legacy `vercel.json`
726
+ `routes` array, and the config-size bounds (64 entries / 4 KiB / 64 KiB).
727
+
728
+ ### Verifying a migration end to end
729
+
730
+ `go test ./...` covers the scan, the refusals and the rewrites, and hands every
731
+ rewritten JavaScript config to `node --check`. It does **not** run `next build`
732
+ (that needs the npm registry, so it is not a deterministic unit test). To check
733
+ the whole path by hand:
734
+
735
+ cp -r ../starters/nextjs-basic /tmp/e2e && cd /tmp/e2e
736
+ # remove `output: 'standalone'` from next.config.ts to get a Vercel-shaped project
737
+ npm install && vibe migrate vercel --apply --dir . --app a --project p
738
+ npm run build && node .next/standalone/server.js
739
+
740
+ The build must produce `.next/standalone/server.js` and that server must serve
741
+ the app. Deploying it on a cell is out of this command's scope.
742
+
743
+ ### The hosted half: `--vercel-project` (VIBEC-346)
744
+
745
+ Everything above reads a checkout. With `--vercel-project <name or id>` the command
746
+ also reads the **hosted** Vercel project through Vercel's REST API with your own token
747
+ (`VERCEL_TOKEN`, by environment — never a flag; `--team-id team_…` for a team
748
+ project) and recreates it on the platform:
749
+
750
+ VERCEL_TOKEN=… vibe migrate vercel --scan --vercel-project acme-crm --project <slug> [--dir ./proje]
751
+ VERCEL_TOKEN=… vibe migrate vercel --apply --vercel-project acme-crm --project <slug> [--dir ./proje] [--repo <git url>] [--branch main]
752
+
753
+ Here `--project` is the **target** vibecloud project (slug), as in every other
754
+ importer; the local-only form above keeps its `--project <App.spec.projectRef.name>`
755
+ meaning. `--scan` prints the plan and changes nothing. `--apply` prints the same
756
+ plan, then:
757
+
758
+ 1. **Refuses a target project that already has an App** (one App per project), or a
759
+ framework the platform cannot build; `--config-only` writes only the variables
760
+ into an App you connected yourself.
761
+ 2. **Runs the checkout half first** when `--dir` is given — the next.config rewrites,
762
+ the runtime audit (edge runtime, `@vercel/blob`, …) and `vercel.json` →
763
+ `next.config` — so a blocker in the repo refuses before any App exists. Routing
764
+ rules (`rewrites`, `redirects`, `headers`) stay in next.config by decision: the
765
+ router has no rule surface and is not getting one for this.
766
+ 3. **Creates the App** from the repository Vercel is linked to (GitHub; `--repo`
767
+ overrides it, and an unlinked project needs it), on the production branch. When
768
+ `--dir` shows a plain Vite SPA the App is created `STATIC` (with `outputDirectory`
769
+ as its directory); otherwise no mode is sent and the server's `STANDALONE` applies.
770
+ 4. **Writes the production variables**, classified by the same rules the checkout
771
+ half applies to `.env` files: `NEXT_PUBLIC_*` and plain values as `ENV`, secrets
772
+ as `SECRET` (write-only). Dropped, with the reason printed: Vercel's system
773
+ variables, the Supabase names the platform provides itself
774
+ (`NEXT_PUBLIC_SUPABASE_URL`, anon key, `DATABASE_URL`), and a `service_role`
775
+ key anywhere — never written. Vercel does not disclose `sensitive` variables:
776
+ they are listed by name and the summary prints the `vibe config secret` line for
777
+ each. Preview/development-only variables are reported, not carried.
778
+ 5. **Prints the cutover**: each custom domain with its `vibe domain add` command
779
+ (DNS is never changed for you; a redirect-only domain is called out), and
780
+ `vibe deploy` as the next step.
781
+
782
+ The plan also reports a monorepo root directory, customised build/install commands
783
+ (the platform runs package.json scripts, not the Vercel panel's command), the Node
784
+ version, and an unsupported framework preset (Next.js builds natively; the static
785
+ presets — Vite, Astro, Hugo, … — take the static path).
786
+
787
+ ⚠ Vercel's response shapes are read from its documentation, not measured against a
788
+ live account: the live run in this repo drives a fake Vercel (`VIBECLOUD_VERCEL_API`).
789
+ Vercel Postgres is Neon underneath — move its data with `vibe migrate neon`.
790
+
791
+ ## `vibe migrate netlify` (VIBEC-348)
792
+
793
+ The Vercel hosted half's shape over Netlify. The command reads the site through
794
+ Netlify's REST API with your own personal access token (`NETLIFY_AUTH_TOKEN`, by
795
+ environment — never a flag) and does two things, in this order:
796
+
797
+ NETLIFY_AUTH_TOKEN=… vibe migrate netlify --scan --site <site id or name.netlify.app> --project <slug> [--dir ./proje]
798
+ NETLIFY_AUTH_TOKEN=… vibe migrate netlify --apply --site <site id or name.netlify.app> --project <slug> [--dir ./proje] [--repo <git url>] [--branch main]
799
+ vibe migrate netlify --scan --dir ./proje
800
+
801
+ `--scan` prints the plan and changes nothing.
802
+
803
+ **Offline scan (VIBEC-462).** `--scan --dir` without `--site` reads the checkout
804
+ alone: no `NETLIFY_AUTH_TOKEN`, no vibe session, no network. It reads
805
+ `netlify.toml`, `_redirects`, `_headers`, the Functions and Edge Functions
806
+ directories and Netlify Forms. With no site there is no UI functions directory
807
+ or base, so only `netlify.toml` places the directories. The plan lists what it
808
+ could not check under `KONTROL EDILMEYENLER` (in JSON: `plan.unchecked`, one
809
+ entry per part — `repository`, `build-settings`, `environment`, `domains`):
810
+ the linked repository, the build settings from the Netlify UI, the UI's
811
+ environment variables and the custom domains. `siteName` and `app.branch` are
812
+ `null`. `--apply` always needs `--site`, and is refused without it before
813
+ anything is read. `--apply` prints the same plan, then:
814
+
815
+ 1. **Refuses a target project that already has an App** (one App per project);
816
+ `--config-only` writes only the variables into an App you connected yourself.
817
+ 2. **Creates the App** from the repository the site is linked to (GitHub; `--repo`
818
+ overrides it, an unlinked site needs it), on the site's production branch.
819
+ 3. **Writes the production variables** — the `production` context, else `all` —
820
+ classified by the same rules the checkout half applies to `.env` files:
821
+ `NEXT_PUBLIC_*` and plain values as `ENV`, secrets as `SECRET` (write-only).
822
+ Dropped, with the reason printed: Netlify's own variables (`NETLIFY*`, `CONTEXT`,
823
+ `DEPLOY_URL`, `URL`, `BUILD_ID`, `NODE_VERSION`, …), the Supabase names the
824
+ platform provides itself, and a `service_role` key anywhere — never written.
825
+ A variable Netlify marks secret is not disclosed: it is named and the summary
826
+ prints the `vibe config secret` line for each. Deploy-preview / branch-deploy /
827
+ dev-only variables are reported, not carried.
828
+ 4. **Prints the cutover**: each custom domain and alias with its `vibe domain add`
829
+ command (DNS is never changed for you), and `vibe deploy` as the next step.
830
+
831
+ **Routing rules.** With `--dir` pointing at a checkout, `netlify.toml`
832
+ (`[[redirects]]`, `[[headers]]`, `[build]`, `[build.environment]`, `[[plugins]]`),
833
+ `_redirects` and `_headers` (in the checkout root or `public/`) are read and
834
+ translated into the **same Next.js rule model the Vercel importer uses**
835
+ (`host/nextrouting.ts` — one model, two parsers) and printed as a next.config
836
+ snippet for you to paste. Routing stays in the app by decision: the router has no
837
+ rule surface. What translates: `301/302/307/308` → `redirects()` (exact status
838
+ kept), `200` → `rewrites()` (a proxy to another origin is flagged for the egress
839
+ allowlist), `_headers` → `headers()`, trailing `/*` splats → `:splat*`, query
840
+ parameters → `has` conditions. What does not, each named in the plan: `Country` /
841
+ `Language` / `Role` / `Cookie` conditions, mid-path `*`, custom `404`/`410`
842
+ (Next's not-found page does that), any other status. Non-`!` (shadowing) rules are
843
+ reported once: Next redirects always run first, which is Netlify's `force`.
844
+
845
+ The plan also reports the Next plugin (not needed on the platform), other build
846
+ plugins, each Function (→ route handlers) and Edge Function (unsupported), a
847
+ monorepo `base`, a customised build command and the Node version. Functions are
848
+ read from the directory Netlify uses: `[functions] directory`, then `[build]
849
+ functions`, then the UI's functions directory, then `netlify/functions`; Edge
850
+ Functions from `[build] edge_functions`, then `netlify/edge-functions`. Each is
851
+ relative to the base directory, a leading `/` included, as on Netlify. A
852
+ directory whose real path is outside the checkout stops the scan; a symlink that
853
+ stays inside it is followed.
854
+
855
+ ⚠ Netlify's response shapes are read from its documentation, not measured against a
856
+ live account: the live run in this repo drives a fake Netlify (`VIBECLOUD_NETLIFY_API`).
857
+
858
+ ## `vibe migrate cloudflare` (VIBEC-351)
859
+
860
+ The same hosted half over **Cloudflare Pages**. The command reads the project
861
+ through Cloudflare's REST API with your own API token (`CLOUDFLARE_API_TOKEN`, by
862
+ environment — never a flag) and the account id (`--account`, else
863
+ `CLOUDFLARE_ACCOUNT_ID`; an identifier, not a credential):
864
+
865
+ CLOUDFLARE_API_TOKEN=… vibe migrate cloudflare --scan --pages-project <ad> --project <slug> [--dir ./proje]
866
+ CLOUDFLARE_API_TOKEN=… vibe migrate cloudflare --apply --pages-project <ad> --project <slug> [--dir ./proje] [--repo <git url>] [--branch main]
867
+ vibe migrate cloudflare --scan --dir ./proje
868
+
869
+ `--scan` prints the plan and changes nothing.
870
+
871
+ **Offline scan (VIBEC-463).** `--scan --dir` without `--pages-project` reads the
872
+ checkout alone: no `CLOUDFLARE_API_TOKEN`, no account id, no vibe session, no
873
+ network. It parses the wrangler configuration (`wrangler.toml`, `wrangler.json`
874
+ or `wrangler.jsonc`; two of them is refused rather than guessed between) and
875
+ reads `_redirects`, `_headers` and `_routes.json` from the build output
876
+ directory the file names (the top-level `pages_build_output_dir`, the only one
877
+ wrangler reads), then the root, `public/` and `static/`, plus `functions/`,
878
+ `_worker.js` and `package.json`. A routing file, or the output directory, whose
879
+ real path leaves the checkout through a symlink is refused. The production and
880
+ preview environments are resolved the way wrangler and Cloudflare's Pages docs
881
+ resolve them: only `[env.production]` and `[env.preview]` exist, and the top
882
+ level applies to an environment only when its block is absent. `vars` and the
883
+ bindings are non-inheritable: an environment block that exists has exactly the
884
+ vars and bindings it declares, even when it sets nothing but
885
+ `compatibility_date`. A block that redeclares some of them but leaves others at
886
+ the top level fails Cloudflare's deploy validation; the plan names it and the
887
+ keys it left out as unverified, and reads none of that environment's variables
888
+ or bindings. Bindings are named with the same replacements as the
889
+ hosted scan, with the preview resource and the file's `preview_id` /
890
+ `preview_database_id` / `preview_bucket_name` alongside. A wrangler file
891
+ without a top-level `pages_build_output_dir` is, per Cloudflare, for local development
892
+ only: its bindings and variables are named in an unverified finding, not read
893
+ as the project's. The plan lists what it could not check under
894
+ `KONTROL EDILMEYENLER` (in JSON: `plan.unchecked` — `repository`,
895
+ `build-settings`, `environment` (the dashboard's secrets, or every variable
896
+ when there is no Pages wrangler file or its production environment is
897
+ invalid), `bindings` (only in those two cases; the summary line then says
898
+ `okunmadi`, never `yok`), `domains`).
899
+ `projectName` and `app.branch` are `null`. Flags that only mean something to
900
+ the hosted scan (`--account`, `--project`, `--org`, `--repo`, `--branch`,
901
+ `--config-only`) are refused, not ignored. `--apply` always needs
902
+ `--pages-project`, and is refused without it before anything is read.
903
+
904
+ `wrangler.toml` is parsed as TOML 1.0 with `smol-toml` (zero dependencies), so
905
+ multi-line arrays of inline tables, literal `'…'` strings and dotted keys read as
906
+ they do for wrangler. `wrangler.jsonc` is parsed with TypeScript's
907
+ JSON-with-comments parser (`typescript` is already a runtime dependency, loaded
908
+ lazily): comments and trailing commas are read. That parser also accepts
909
+ JavaScript literal forms JSON does not have (`"\x41"`, `0x10`, `.5`, `1_000`, a
910
+ line continuation), so every string and number token is re-read with
911
+ `JSON.parse` and one it cannot read is refused rather than converted. Other
912
+ non-JSON syntax (single quotes, unquoted keys, `Infinity`) is refused by the
913
+ parser itself. A syntax error in any of the three names the file, line and
914
+ column.
915
+
916
+ `--apply` prints the same plan, then:
917
+
918
+ 1. **Refuses a target project that already has an App** (one App per project);
919
+ `--config-only` writes only the variables into an App you connected yourself.
920
+ 2. **Creates the App** from the repository the Pages project is connected to
921
+ (GitHub; `--repo` overrides it, an unconnected project needs it), on the
922
+ production branch.
923
+ 3. **Writes the production variables** — the `production` deployment config —
924
+ classified by the same rules the checkout half applies to `.env` files:
925
+ `NEXT_PUBLIC_*` and plain values as `ENV`, secrets as `SECRET` (write-only).
926
+ Dropped, with the reason printed: Cloudflare's own variables (`CF_PAGES*`,
927
+ `NODE_VERSION`, `NPM_FLAGS`, `SKIP_DEPENDENCY_INSTALL`, …), the Supabase names
928
+ the platform provides itself, and a `service_role` key anywhere — never
929
+ written. A `secret_text` variable is not disclosed by Cloudflare: it is named
930
+ and the summary prints the `vibe config secret` line for each. Variables that
931
+ exist only on the preview config are reported, not carried.
932
+ 4. **Prints the cutover**: each custom domain with its `vibe domain add` command
933
+ (DNS is never changed for you), and `vibe deploy` as the next step.
934
+
935
+ 🔴 **The bindings are the migration.** A Pages project also carries KV, D1, R2,
936
+ Durable Objects, Queues, Vectorize, Workers AI, Analytics Engine, service
937
+ bindings, mTLS certificates and Browser Rendering — Cloudflare-only services the
938
+ app reaches through globals that do not exist anywhere else. **None of them
939
+ move.** Every one is reported by name with what replaces it here: KV → a Postgres
940
+ table or Storage, D1 → the tenant Postgres (dump and load; the SQL dialect
941
+ differs), R2 → the S3-compatible Storage, Durable Objects → a Postgres row plus a
942
+ lock, Vectorize → pgvector, service bindings → an HTTP call or a route handler.
943
+ Hyperdrive is the one that is simply not needed: the platform hands the app a
944
+ Postgres connection string and pools it itself. Bindings come from the API, so
945
+ they are listed with or without `--dir`. Pages does not inherit bindings between
946
+ environments, so the preview config is read too: a production binding whose
947
+ preview deployments use another resource names both, and a binding only the
948
+ preview config carries is reported by name and resource (it was never defined in
949
+ production).
950
+
951
+ **Routing rules.** With `--dir` pointing at a checkout, `_redirects` and
952
+ `_headers` (in the checkout root, `public/` or `static/`) are read and translated
953
+ into the **same Next.js rule model the Vercel and Netlify importers use**
954
+ (`host/nextrouting.ts` — one model, three parsers) and printed as a next.config
955
+ snippet for you to paste. Routing stays in the app by decision: the router has no
956
+ rule surface.
957
+
958
+ ⚠ **The file names match Netlify's and the dialects do not**, so the three
959
+ differences are enforced rather than assumed: a statusless `_redirects` line is
960
+ **302** here and 301 on Netlify; there is **no `!` force marker** and no
961
+ shadowing (Cloudflare redirects always run, which is what Next does, so there is
962
+ nothing to report); and there are **no `Country`/`Language`/`Role`/`Cookie`
963
+ conditions and no query matching** — a `key=value` token is reported as unreadable
964
+ rather than read as a condition the source platform never honoured.
965
+
966
+ What translates: `301/302/303/307/308` → `redirects()` (exact status kept), `200`
967
+ → `rewrites()`, `_headers` → `headers()`, trailing `/*` splats → `:splat*`, and an
968
+ absolute `_headers` pattern (`https://host/path`) → a `has: [{type:'host'}]`
969
+ condition. What does not, each named in the plan: a `200` proxy to another origin
970
+ (Cloudflare only proxies within the site, so the rule never worked there either),
971
+ a non-trailing `*` such as `/*.jpg`, a `! Header-Name` detach line (Next's
972
+ `headers()` only adds headers), a wildcard host, and any other status.
973
+
974
+ ⚠ **Cloudflare does not apply these files to Pages Functions.** Its docs state
975
+ that `_headers` are not applied to responses generated by Functions and
976
+ `_redirects` are not applied to requests Functions serve; Next's `headers()`
977
+ and `redirects()` apply to every matching response, server-rendered pages and
978
+ route handlers included. When the project shows a Functions surface (a
979
+ Cloudflare Next adapter, a next-on-pages / OpenNext build command, `functions/`,
980
+ `_worker.js` or `_routes.json`) and the snippet is non-empty, the plan names
981
+ that evidence and marks the rules unverified: which paths a Function answered on
982
+ Cloudflare is not checked.
983
+
984
+ The plan also reports `_routes.json`, `functions/` (→ route handlers, with the
985
+ `[param]` / `[[catchall]]` / `_middleware` mapping), `_worker.js` (advanced mode —
986
+ unsupported), the wrangler config (authoritative for Pages, so it can disagree
987
+ with the dashboard), the `@cloudflare/next-on-pages` / `@opennextjs/cloudflare`
988
+ adapter (remove it), a monorepo root directory, a build path filter, a customised
989
+ build command and the Workers compatibility date and flags.
990
+
991
+ ⚠ Cloudflare's response shapes are read from its documentation, not measured
992
+ against a live account: the live run in this repo drives a fake Cloudflare
993
+ (`VIBECLOUD_CLOUDFLARE_API`).
994
+
995
+ ## `vibe migrate firebase` (VIBEC-347)
996
+
997
+ The first source with no Postgres to dump. Firebase is three products, so the
998
+ importer has three data legs and a code leg, all read through Google's own APIs
999
+ with the customer's **Firebase Admin service-account key** (a file; the path is
1000
+ the flag, the key never leaves the machine except as a signature):
1001
+
1002
+ vibe migrate firebase --scan --service-account ./anahtar.json [--dir ./proje] [--hash-params ./hash.json] [--bucket <kova>]
1003
+ vibe migrate firebase --apply --service-account ./anahtar.json --project <slug> [--dir ./proje] [--hash-params ./hash.json] [--bucket <kova>]
1004
+
1005
+ `--scan` reads everything, prints the plan **with the DDL it would run**, and
1006
+ stops — it needs no platform login. `--apply` prints the same plan, then:
1007
+
1008
+ 1. **Mints the time-boxed migration role** (the Supabase importer's lifecycle)
1009
+ and connects to the tenant database as it, retrying while the cell creates it.
1010
+ 2. **Writes the database in ONE transaction**: every `CREATE TABLE`, every
1011
+ Firestore row, every `auth.users` / `auth.identities` row. A failure at any
1012
+ statement rolls the whole thing back, ends the role, and is an error — never
1013
+ a half-import described as done.
1014
+ 3. **Moves the Cloud Storage objects** into private target buckets, stopping at
1015
+ the first failure (same rule).
1016
+ 4. **Asks the server to attest** (`completeMigration`, source `FIREBASE`), which
1017
+ ends the role.
1018
+
1019
+ **Auth → GoTrue.** Users come from Identity Toolkit `accounts:batchGet` with
1020
+ their password hashes. Firebase hashes with a modified scrypt; the tenant's
1021
+ GoTrue (v2.189.0) verifies exactly that when `encrypted_password` is
1022
+ `$fbscrypt$v=1,n=<mem_cost>,r=<rounds>,p=1,ss=<salt_sep>,sk=<signer_key>$<salt>$<hash>`,
1023
+ so **users keep their passwords**. The project's hash parameters come from the
1024
+ Identity Toolkit config; when the service account lacks
1025
+ `firebaseauth.configs.getHashConfig`, pass the console's *Password hash
1026
+ parameters* export as `--hash-params` (an explicit second input, not a guess;
1027
+ without either, password users are skipped by name). Every user gets a
1028
+ deterministic UUIDv5 of their Firebase uid (GoTrue ids are uuids), with the
1029
+ original uid in `raw_user_meta_data.firebase_uid`. Carried: email + password,
1030
+ Google/GitHub/Apple/Facebook/Twitter/Microsoft identities (into
1031
+ `auth.identities` under GoTrue's provider names, `provider_id` = the provider's
1032
+ uid), `emailVerified`, `disabled` (→ banned), display name, photo, custom
1033
+ claims. Not carried, each reported: phone-only sign-in, MFA enrolments,
1034
+ anonymous accounts, providers GoTrue has no name for, Auth settings and OAuth
1035
+ client secrets.
1036
+
1037
+ 🔴 **Proven live, not asserted**: `auth.test.ts` round-trips Firebase's
1038
+ published scrypt test vector through GoTrue's own regexp and primitives, and
1039
+ the repo's live run wrote the importer's rows into a real
1040
+ `supabase/gotrue:v2.189.0` and logged in — token issued for the right password,
1041
+ refused for the wrong one, `User is banned` for a disabled user.
1042
+
1043
+ **Firestore → Postgres.** Every collection is read through the REST API — root
1044
+ collections, their documents, and each document's subcollections recursively
1045
+ (one `listCollectionIds` call per document is the price of completeness). One
1046
+ table per collection id — a subcollection name that appears under many parents
1047
+ is ONE table, Firestore's own collection-group model — with `id text primary
1048
+ key`, `_path` (the full document path), `_parent_id`, `_created_at`,
1049
+ `_updated_at`, and **`_doc jsonb` holding the whole decoded document**, so
1050
+ nothing inference gets wrong is lost. Typed columns are inferred from the union
1051
+ of field types across the collection: string → `text`, integer → `bigint`,
1052
+ double (or integer+double) → `double precision`, boolean, timestamp →
1053
+ `timestamptz`, bytes → `bytea`, reference → `text` path, GeoPoint → `<f>_lat`
1054
+ and `<f>_lng`, map/array → `jsonb`, two incompatible kinds → `jsonb`. Names are
1055
+ sanitised to identifiers; a field that collides with a fixed column (`id`) is
1056
+ suffixed and the rename is recorded in a column comment and the plan. Every
1057
+ table gets **RLS enabled with no policies** — Firestore rules are not
1058
+ translated, so tables start closed and the plan says so.
1059
+
1060
+ **Storage.** Every GCS bucket of the project is listed (`--bucket` narrows it);
1061
+ objects are GET from GCS and PUT to the tenant's storage-api with their content
1062
+ type, `x-upsert` so a re-run overwrites. The default `<project>.appspot.com` /
1063
+ `.firebasestorage.app` bucket becomes `firebase`; others keep their name. Target
1064
+ buckets are created **private**; Storage rules, custom metadata and download
1065
+ tokens do not move and are named.
1066
+
1067
+ **Client code.** With `--dir`, every file importing `firebase/*`, `@firebase/*`
1068
+ or `firebase-admin` is listed by SDK area with its supabase-js counterpart;
1069
+ `firebase.json`, `functions/`, `firestore.rules` and `storage.rules` are
1070
+ detected. Nothing is rewritten — a Firestore query and a SQL query are not the
1071
+ same program.
1072
+
1073
+ **Out of scope, stated in every plan:** Realtime Database, Cloud Functions,
1074
+ FCM, Remote Config, App Check, Hosting, security-rules translation.
1075
+
1076
+ ⚠ Google's response shapes are read from its documentation, not measured
1077
+ against a live Firebase project: the live run drives a fake
1078
+ (`VIBECLOUD_FIREBASE_API`) for the Google half and a real GoTrue + Postgres for
1079
+ the target half. A live-project run remains to be done.
1080
+
1081
+ ## `vibe migrate supabase` (#72)
1082
+
1083
+ Scans an existing Supabase project and reports what moving it onto our
1084
+ platform would involve — in two halves, asked for by name (VIBEC-325):
1085
+
1086
+ vibe migrate supabase --scan --dir . # the application
1087
+ vibe migrate supabase --scan --dsn postgresql://…/postgres # the database [--report rapor.md] [--exact-rows]
1088
+
1089
+ **The application half** is the Next.js project that talks to Supabase: its
1090
+ env NAMES (never values — `NEXT_PUBLIC_SUPABASE_URL` and the anon key map to
1091
+ the project's own endpoints, the service-role key is refused as a secret that
1092
+ must not ride in `env`), the Supabase client it imports, its `next.config`.
1093
+ It is the same scan the host migrator runs, so it needs no database access
1094
+ and works on a fresh clone; findings that say "Vercel paneli" mean the panel
1095
+ of whichever host the app is on today. `--dir` and `--dsn` are not combined:
1096
+ run one, then the other — **into two report files** (`uygulama.md`, `veritabani.md`):
1097
+ each half refuses the other's file by name rather than overwriting it. `--apply
1098
+ --dir` is answered with the host apply (`vibe migrate vercel --apply`), which is
1099
+ the application apply; the database `--apply` is below.
1100
+
1101
+ **The database half** needs the DSN:
1102
+
1103
+ **It is read-only, and the server enforces that** — every query runs inside one
1104
+ `READ ONLY REPEATABLE READ` transaction, so a stray write fails rather than
1105
+ succeeding against the customer's production project, and every number in one
1106
+ report comes from one snapshot. Point it at a live project.
1107
+
1108
+ Findings are classified **mapped / manual / unsupported / unverified**. The last
1109
+ class is the one this command exists for: a database scan runs as some role, and
1110
+ that role's grants decide what it can see, so "found nothing wrong" and "was not
1111
+ allowed to look" must not render the same way. Anything unreadable is reported
1112
+ as unverified and never as clean.
1113
+
1114
+ `--apply` **performs the import** into a target project you have already created:
1115
+
1116
+ vibe migrate supabase --apply --dsn postgresql://…/postgres --project <slug>
1117
+
1118
+ It `pg_dump`s the source and `pg_restore`s into the target (single-transaction, so
1119
+ a failed restore leaves nothing behind), carries the auth users and the storage
1120
+ catalogue the excluded Supabase schemas would otherwise drop, moves the storage
1121
+ blob files object-by-object, and then asks the server to attest the import
1122
+ completed — the migration credit rests on that server-side check of the target's
1123
+ schema, never on the CLI's word. It stops at the first failure and never reports a
1124
+ partial import as complete.
1125
+
1126
+ The target credential is minted for you — the platform issues a time-boxed (24h),
1127
+ owner-equivalent migration role and a matching time-boxed `service_role` key for
1128
+ storage, so you never reveal or hold a standing target secret. The role is ended
1129
+ the moment the import is attested: everything it created is handed to your
1130
+ project's standing `tenant_owner` role and the migration role is dropped, so 24h
1131
+ is the ceiling for an import that never completes, not how long the credential
1132
+ lives. An import that FAILS after the mint — dump, restore, storage — ends the
1133
+ role the same way (`abandonMigration`); if even that call fails, the error says
1134
+ so and the role expires on its own within the 24h. The only value you
1135
+ may supply is your SOURCE Supabase key, and only to move storage: set
1136
+ `VIBECLOUD_SOURCE_STORAGE_KEY` by env (never a flag) if the source has storage
1137
+ objects — without it, storage is skipped, or the import refuses rather than drop
1138
+ files. The source storage URL is derived from `--dsn`; override it with
1139
+ `VIBECLOUD_SOURCE_STORAGE_URL` only for a DSN host we do not recognise. See
1140
+ `ENVIRONMENT.md`. The target must be an empty, freshly-created project — and the
1141
+ server checks: a project whose observed schema already holds user tables is
1142
+ refused before anything is minted (`MIGRATION_TARGET_NOT_EMPTY`, listing the
1143
+ tables in the way). Import into a fresh project, or empty the target yourself.
1144
+
1145
+ `pg_dump`/`pg_restore` must be available. If they are not on your PATH, the CLI
1146
+ refuses before touching anything and prints the install commands for your OS —
1147
+ or, with `--fetch-pg-client` (or a yes at the terminal prompt), downloads the
1148
+ pinned tools from our own mirror, verifies their sha256, and installs them under
1149
+ `~/.vibecloud/bin` (unpacking needs `tar` and `gzip` on PATH). The download never
1150
+ happens unasked, and never in machine mode.
1151
+
1152
+ ### Row counts: estimate by default
1153
+
1154
+ `--scan` reads `pg_class.reltuples` and labels it an estimate. `--exact-rows`
1155
+ runs `count(*)` instead. The default is the estimate deliberately: `count(*)`
1156
+ scans every table of the customer's live project, and `reltuples` is readable
1157
+ without `SELECT` on the table, so it also works for a least-privilege role.
1158
+ `reltuples = -1` (never analyzed) is reported as _no answer_, not as zero rows.
1159
+
1160
+ ⚠ **An exact count under row security can be silently wrong.** A role that is
1161
+ neither superuser nor `BYPASSRLS`, and does not own the table, gets the
1162
+ policy-filtered count — `count(*)` **succeeds** and returns 0 for a table
1163
+ holding 42 rows. Those counts are marked untrusted rather than reported as
1164
+ exact. Scan as Supabase's `postgres` role for a complete inventory.
1165
+
1166
+ ### Verifying the scanner end to end
1167
+
1168
+ `go test ./...` covers the classification and report rendering with no database.
1169
+ The catalog reading is covered against a **real PostgreSQL 17** — a mocked
1170
+ catalog would only prove the mock matches the code — and those tests **skip
1171
+ loudly** unless a DSN is provided. The container is deliberately not started by
1172
+ the test process: that would make the default test path depend on a registry
1173
+ pull, which §8.2 forbids. To run them:
1174
+
1175
+ docker run -d --name vc-sb-pg -e POSTGRES_PASSWORD=pw -p 55432:5432 postgres:17-alpine
1176
+ VIBECLOUD_TEST_SOURCE_DSN='postgresql://postgres:pw@127.0.0.1:55432/postgres' go test ./...
1177
+ docker rm -f vc-sb-pg
1178
+
1179
+ The test creates and drops its own schemas (`sbscan`, `sbext`, `auth`,
1180
+ `storage`, `realtime`, `supabase_functions`, `net`, `app`) and a
1181
+ `sbscan_limited` role in that database, so point it at a **disposable**
1182
+ Postgres, never at anything you care about.
1183
+
1184
+ ### What the scan cannot see
1185
+
1186
+ The report says this too, in Turkish, because a report that looks complete is
1187
+ worse than one that admits its edges: the objects in S3 (only `storage`
1188
+ metadata is read), application code, Supabase dashboard settings, Edge Function
1189
+ source, and Supabase's own backups. The Supabase extension baseline it compares
1190
+ against is transcribed from `../cell/deploy/supabase/bootstrap.sql` — the
1191
+ shipping bootstrap, which disagrees with the design docs; there is no machine-readable
1192
+ declaration of the baseline to import.
1193
+
1194
+ ## `vibe migrate neon` · `vibe migrate prisma` (VIBEC-344 · VIBEC-345 · VIBEC-464)
1195
+
1196
+ The plain-Postgres importers. A Neon database, a Prisma Postgres database, or any
1197
+ Postgres a Prisma ORM app points at, is a plain database with no auth or storage
1198
+ rows to carry — so the whole thing moves in one dump, on the same lifecycle the
1199
+ Supabase importer measured live: the platform mints a 24h owner-equivalent role,
1200
+ the CLI waits until it authenticates, dumps the source, restores as that role
1201
+ (`--no-owner --no-privileges --no-comments --single-transaction`), asks the
1202
+ server to attest completion, and the cell hands every imported object to your
1203
+ `tenant_owner` and drops the role. The same two rules as the Supabase importer
1204
+ apply: the target must be empty (`MIGRATION_TARGET_NOT_EMPTY` otherwise), and a
1205
+ failure after the mint drops the role instead of leaving it for 24h.
1206
+
1207
+ vibe migrate neon --scan --dsn 'postgresql://…@ep-xxx.eu-central-1.aws.neon.tech/neondb?sslmode=require'
1208
+ vibe migrate neon --apply --dsn 'postgresql://…@ep-xxx.eu-central-1.aws.neon.tech/neondb?sslmode=require' --project <slug> --org <org>
1209
+ vibe migrate prisma --scan --dsn 'postgresql://…@db.prisma.io:5432/postgres?sslmode=require'
1210
+ vibe migrate prisma --apply --dsn 'postgresql://…@db.prisma.io:5432/postgres?sslmode=require' --schema prisma/schema.prisma --project <slug> --org <org>
1211
+
1212
+ Exactly one of `--scan` and `--apply` is required, as for `migrate heroku` and
1213
+ `migrate railway`; neither, or both, is refused.
1214
+
1215
+ **`--scan` lists what the dump will carry and changes nothing.** It reads the source
1216
+ in one read-only snapshot and needs no `vibe login` and no `pg_dump`: per schema, the
1217
+ tables, views, materialized views, sequences and indexes (with how many are partial);
1218
+ every materialized view and partial index by name; the extensions that restore on
1219
+ the target, with their versions; the vendor extensions left out of the dump; and, for
1220
+ Prisma, the `_prisma_migrations` row count. Objects that belong to an extension are not
1221
+ counted, because `CREATE EXTENSION` brings them, not the dump. A source that `--apply`
1222
+ would refuse (an extension the target does not ship) gets the same refusal, after the
1223
+ listing, and exits non-zero. `--scan` was added in VIBEC-464 (repo-owner decision
1224
+ 2026-10-02). It reverses the earlier "no `--scan` here", because the preflight printed
1225
+ one line and never said what would move.
1226
+
1227
+ **Row-level security after the import.** The platform forces RLS on every table
1228
+ (decision 64), and a Neon, Prisma, Heroku or Railway app has no policies of its own,
1229
+ so on its own it would read empty tables. When the import completes, every imported
1230
+ table gets:
1231
+
1232
+ - the grants a `tenant_owner`-created table would have;
1233
+ - a `vibecloud_app_access` policy for the server-side roles: `vibe_app`, whose
1234
+ `DATABASE_URL` the platform gives a deployed App, and `tenant_owner`, which
1235
+ `prisma migrate` uses.
1236
+
1237
+ `anon` and `authenticated` stay closed. A table created afterwards needs the same
1238
+ policy, and the command prints the statement.
1239
+
1240
+ Completion also waits for the cell to see the import. The API asks the cell to
1241
+ re-read the schema catalogue, and the CLI polls for up to five minutes.
1242
+
1243
+ `--apply` runs the same preflight before anything is minted, and names the
1244
+ extensions it accepted:
1245
+
1246
+ - **The DSN is classified, not trusted.** A Neon **pooler** host (`-pooler.` in the
1247
+ name) is refused — a dump through a transaction pooler restores cleanly and is
1248
+ internally inconsistent — with the console path to the direct string. A
1249
+ `prisma+postgres://` / `prisma://` **Accelerate** URL, or a `*.prisma-data.net`
1250
+ host, is refused the same way: pg_dump cannot speak to it; use the direct TCP
1251
+ connection string. `sslmode` below `require` is refused; an absent one is set to
1252
+ `require` (both vendors mandate TLS and libpq's default would downgrade).
1253
+ - **Extensions are checked against what tenant Postgres 17 ships.** Anything the
1254
+ image does not carry — banned (`dblink`, `http`, …), unknown, or allowed-but-absent
1255
+ (PostGIS) — refuses before the mint, all of them listed at once. Neon's own
1256
+ `neon`/`neon_utils` are left out of the dump rather than refused. Everything
1257
+ PostgreSQL marks *trusted* on the image (`pg_trgm`, `citext`, `hstore`, `ltree`,
1258
+ `unaccent`, `btree_gin/gist`, …) restores where your dump puts it, because
1259
+ `tenant_owner` holds `CREATE` on the database since 2026-09-17 — the server's
1260
+ trust flag is the boundary, and the tenant bootstrap refuses an image that marks a
1261
+ banned extension trusted.
1262
+ - **Prisma:** `_prisma_migrations` is carried with the rest of `public`, so
1263
+ `prisma migrate deploy` against the new DSN applies nothing. **Do not run
1264
+ `prisma db push` after the import** — it overwrites the migrated schema. With
1265
+ `--schema`, a **Prisma 6** schema has its `datasource` block's `url`/`directUrl` names
1266
+ read and the two new DSNs printed under those exact env names; a missing `directUrl`
1267
+ and a literal Accelerate URL that would survive the swap are called out. A
1268
+ **Prisma 7** schema (the datasource carries only `provider` — Prisma 7 refuses
1269
+ `url`/`directUrl` in a schema file, P1012) is recognised by that absence: the
1270
+ session DSN is printed for `prisma.config.ts`'s `datasource.url` (read as
1271
+ `DIRECT_URL`) and the pooled DSN for the `PrismaClient` adapter (`DATABASE_URL`),
1272
+ as two variables, because Migrate cannot hold its advisory lock through
1273
+ transaction pooling. Without `--schema` both placements are printed.
1274
+
1275
+ The import ends by printing the two connection strings to swap in — the pooled one
1276
+ (`:6543`, the app's `DATABASE_URL` — Prisma 6 `url`, Prisma 7's adapter) and the session one
1277
+ (`:5432`, psql, pg_dump, `prisma migrate` — Prisma 6 `directUrl`, Prisma 7's `prisma.config.ts`) — as your standing
1278
+ `tenant_owner.<projectUid>` role and without the password, which the console hands
1279
+ over (`vibe db connect`). Everything said above about `--fetch-pg-client`,
1280
+ `--project` auto-selection and `--org` applies here too.
1281
+
1282
+ ## `vibe migrate heroku` (VIBEC-350)
1283
+
1284
+ One web dyno plus Heroku Postgres — the shape Turkish agencies' older Node/Next.js
1285
+ apps still run in. The command reads the app through the Heroku Platform API with
1286
+ your own key (`HEROKU_API_KEY`, by environment — never a flag) and does two things,
1287
+ in this order, each refusing before the next starts:
1288
+
1289
+ HEROKU_API_KEY=… vibe migrate heroku --scan --app <heroku app> --project <slug> [--dir <checkout>]
1290
+ HEROKU_API_KEY=… vibe migrate heroku --apply --app <heroku app> --repo <git url> [--branch main] --project <slug>
1291
+
1292
+ `--scan` prints the plan and changes nothing. `--apply` prints the same plan, then:
1293
+
1294
+ 1. **Refuses a target project that already has an App** (one App per project). Use an
1295
+ empty project, or `--config-only` to write only the variables into an App you
1296
+ connected yourself.
1297
+ 2. **Moves Heroku Postgres** on the plain-Postgres core (`vibe migrate neon`'s
1298
+ lifecycle): `DATABASE_URL` by default, a follower with
1299
+ `--database HEROKU_POSTGRESQL_<COLOR>_URL`. Heroku's server certificate cannot
1300
+ be verified and Heroku documents `sslmode=require`, so this — and only this —
1301
+ source is connected encrypted-but-unverified for the preflight; pg_dump follows
1302
+ libpq as always. Extensions are preflighted like Neon's.
1303
+ 3. **Creates the App** from `--repo`/`--branch`. Heroku's public API does not expose
1304
+ the connected GitHub repository, so you name it.
1305
+ 4. **Writes the config vars** the plan carries — `NEXT_PUBLIC_*` as `ENV`, everything
1306
+ else as `SECRET` (write-only). Dropped, with the reason printed: Postgres
1307
+ attachments (the platform seeds `DATABASE_URL` at App creation; the data moved in
1308
+ step 2), Heroku-injected runtime vars (`DYNO`, `PORT`, `WEB_CONCURRENCY`,
1309
+ `NPM_CONFIG_*`, `HEROKU_*`), and the vars provisioned by add-ons we do not carry
1310
+ (Heroku Redis, Memcachier, Kafka, CloudAMQP, Papertrail, Scheduler). External
1311
+ add-ons (SendGrid, …) keep their credentials — the plan tells you to get an
1312
+ account-level key before you remove the add-on on Heroku.
1313
+ 5. **Prints the cutover**: the two Postgres DSNs (`tenant_owner.<uid>`, no
1314
+ password), each custom domain with its `vibe domain add` command (DNS is never
1315
+ changed for you), and `vibe deploy` as the next step.
1316
+
1317
+ The plan reports what does not move: non-web process types (workers, release
1318
+ phase), Heroku Scheduler jobs (copy the cron lines from the dashboard), non-Node
1319
+ buildpacks. With `--dir` pointing at a checkout it also reads the `Procfile` `web:`
1320
+ line (and flags a disagreement with the formation) and `package.json`'s
1321
+ `engines.node` and `heroku-postbuild` — the latter is NOT run by the platform;
1322
+ move its steps into `build`.
1323
+
1324
+ ## `vibe migrate railway` (VIBEC-349)
1325
+
1326
+ One app service plus one Postgres out of a Railway project environment. The command
1327
+ reads the environment through Railway's public GraphQL API with your own token
1328
+ (`RAILWAY_TOKEN`, by environment — never a flag), classifies every service it finds
1329
+ — git-backed app, Docker-image app, Postgres, Redis/MySQL/Mongo (reported, not
1330
+ carried), cron service, volume — and does two things, in this order:
1331
+
1332
+ RAILWAY_TOKEN=… vibe migrate railway --scan --project-id <uuid> --environment production --project <slug> [--service <name>] [--dir <checkout>]
1333
+ RAILWAY_TOKEN=… vibe migrate railway --apply --project-id <uuid> --environment production --project <slug> [--service <name>] [--repo <git url>] [--branch main]
1334
+
1335
+ `--scan` prints the plan and changes nothing. `--apply` prints the same plan, then:
1336
+
1337
+ 1. **Refuses a target project that already has an App** (one App per project), or a
1338
+ target whose database is not empty (`MIGRATION_TARGET_NOT_EMPTY`). Use an empty
1339
+ project, or `--config-only` to write only the variables into an App you connected
1340
+ yourself.
1341
+ 2. **Moves the Postgres** over its **TCP Proxy** — `DATABASE_PUBLIC_URL`, or the proxy
1342
+ plus the service's own `PG*` credentials — on the plain-Postgres core. A database
1343
+ that is private-network-only (no proxy, no `DATABASE_PUBLIC_URL`) cannot be
1344
+ reached from your machine; the plan says so and how to enable the proxy (service →
1345
+ Settings → Networking → TCP Proxy, port 5432; turn it off again afterwards). The
1346
+ Postgres template serves a self-signed certificate, so this — and only this —
1347
+ source is connected encrypted-but-unverified for the preflight, exactly as Heroku
1348
+ is; pg_dump follows libpq as always. Extensions are preflighted like Neon's.
1349
+ 3. **Creates the App** from the service's connected repository (`--repo` overrides
1350
+ it; an image service has none and needs one), on `--branch`.
1351
+ 4. **Writes the variables** the plan carries, with Railway **reference variables
1352
+ resolved to values**: `${{Service.VAR}}` and `${{shared.VAR}}` are substituted,
1353
+ following chains, before the value is written; a reference to a service that does
1354
+ not exist is dropped and listed, never written blank. `NEXT_PUBLIC_*` as `ENV`,
1355
+ everything else as `SECRET` (write-only). Dropped, with the reason printed: every
1356
+ Postgres connection variable (the platform seeds `DATABASE_URL` at App creation;
1357
+ the data moved in step 2), Railway-injected runtime vars (`RAILWAY_*`, `PORT`,
1358
+ `NIXPACKS_*`, `RAILPACK_*`), and any variable that resolves to a Redis/MySQL/Mongo
1359
+ service's address — those services are not carried.
1360
+ 5. **Prints the cutover**: the two Postgres DSNs, each custom domain of the app
1361
+ service with its `vibe domain add` command (DNS is never changed for you), and
1362
+ `vibe deploy` as the next step.
1363
+
1364
+ The plan reports what does not move: Redis/MySQL/Mongo data, cron services (the
1365
+ schedule is printed), volumes, a second app service or a second Postgres (MVP: one
1366
+ of each — `--service` picks the app when there are several), and image services
1367
+ without a repo. With `--dir` pointing at a checkout it reads `railway.json` (or
1368
+ `railway.toml` — the flat `[build]`/`[deploy]` tables Railway writes) for the
1369
+ builder, start command and healthcheck path, which override the API view the way
1370
+ Railway itself applies them, and looks for a `Dockerfile`: one means the rootless
1371
+ BuildKit path; none means Nixpacks/Railpack auto-detection, whose platform
1372
+ counterpart is the Next.js build (other frameworks need a Dockerfile). Without
1373
+ `--dir` the builder question is reported as unverified rather than guessed.
1374
+
1375
+ ⚠ Railway's schema is read from its documentation, not measured against a live
1376
+ account: the live run in this repo drives a fake Railway (`VIBECLOUD_RAILWAY_API`).
1377
+ A renamed field surfaces as a GraphQL error quoted by message.