
# Build an app on TinyCloud

The user created an **App** in the TinyCloud console and pasted you its prompt. That prompt gave you two values, `TINYCLOUD_API_URL` and `TINYCLOUD_API_KEY` (`tc_app_…`, scoped to this one App). Hand them to the CLI once, right after installing it (§0), and never print the key back or put it in a command again.

The key can only touch this App. You do not need any other TinyCloud credential, Docker, Git, or a cloud account. You talk to the platform only through the `tinycloud` CLI.

Your job is finished when the app the user asked for is **live at its URL and you have verified it yourself**. The user should not need to do anything between pasting the prompt and opening the link.

## 0. Install and orient (once per session)

```sh
npm install -g "<TINYCLOUD_API_URL>/cli/tinycloud.tgz"
TINYCLOUD_API_URL=<url> TINYCLOUD_API_KEY=<key> tinycloud login   # once: saves the key (readable by you only); later shells need neither
tinycloud whoami            # the App this key belongs to, its environments, sign-in that works, and whether the CLI is current
tinycloud app context       # services, schema, migrations, variables, recent deploys and errors, and what to do next
```

If `context` shows a live deployment, this is an **update**: run `tinycloud app clone <app>` into an empty directory (it downloads the code that is live; if its `next:` line says to, run `tinycloud app pull` to pick up changes made online since), or work in the user's existing project directory if it has `.tinycloud/link.json`. Then go to step 3.

Everything the CLI can do is documented offline: `tinycloud docs` lists the topics of this guide, and `tinycloud docs reference [command…]` prints every command with its flags, `--json` shape and exit codes. With `--json`, a successful command prints exactly one JSON document on stdout; a failed one prints `{"error": {"code", "message", "next", …}}` on stderr. `next` is always a command to run or a file to edit.

## First delivery and the next change

If the user chooses an existing project, inspect their workspace before editing. Preserve its data, framework and behavior; do not replace it with a starter. If they choose the notes example, begin in an empty directory and build a small Node/Postgres app that creates and lists notes. Use a database migration and parameterized queries; keep its default access policy. Inspect the selected runtime capabilities before choosing a size.

After the first deploy, verify through `tinycloud app curl /` and exercise the actual feature. A live release or a health probe alone does not prove authorized application access. Save one test record, reload it, and report the authorized URL without printing credentials.

For the next change, ask what the user wants if it is unspecified. Read the current state, preserve the saved data, run check/plan/deploy again, and verify both the new behavior and the original record. A no-op redeploy or rollback is not a second feature delivery. Do not automatically create another environment or change providers.

An expired/revoked App key must be replaced through the user's existing App prompt/key flow. An organization token manages infrastructure only; it cannot substitute for an App key. If the selected App or environment differs from the user's instruction, stop before editing or deploying and resolve the target.

## 1. Decide what the app needs

Read the user's sentence and decide, before writing code. If the App has a custom backend, inspect `tinycloud app resources list --json` first: Boat and Agent37 currently require Node/medium and do not support managed volumes. Do not add a volume to an unsupported backend or silently change its binding; ask the owner to choose a compatible backend when the app requires persistent file storage.

Then choose its primitives:

| If the app… | Declare | Notes |
|---|---|---|
| stores anything that must survive a restart (records, accounts, settings) | `[database]` + `migrations/` | Postgres. Never install a database inside the app. |
| stores user-uploaded files or generated files | `[[volume]]` | A directory mounted into the app. Never keep uploads on local disk. |
| has "my", "only me", per-user data, an admin, or anything private | keep `[auth]` (it is on by default) | Platform login with the providers `tinycloud whoami` lists as working (zero setup). Remove `[auth]` only for a fully anonymous site. Sign-in does not let other people in: access is `private` by default (`org` behaves the same), so only the owner (console **Open app**) and you (the App key) get through, signed in or not. Others reach the app only once access is `public`: set it when their request says people who are not signed in may open it, otherwise ask (§6). |
| runs something on a timer ("every morning", "daily digest") | `[[schedule]]` | Sends `POST <path>` (header `X-TinyCloud-Schedule: <name>`) to your web service, so the handler must accept POST; it wakes the app. |
| is only a frontend (no server logic, no database) | one `[[service]]` with `static = "dist/"` | No server needed; the platform serves the files. |
| receives webhooks (Stripe, GitHub, …) | `public_paths = ["/webhooks/*"]` at the top of `tinycloud.toml` | The app stays private; only those paths are open. Check the provider's signature in the handler; never open `/` or `/*` this way (that is `access = "public"`, which needs the user's say-so). |
| needs a third-party API key the user mentioned | an App secret plus a `[secrets]` reference | If the user gave you the value: `printf %s "$VALUE" \| tinycloud app secrets set stripe` (stdin only), then `tinycloud app secrets ref STRIPE_SECRET_KEY app/stripe`. Otherwise ask the user for it, and say why. An existing org secret is referenced as `org/<name>`. Never put a secret value in a file, a variable or a command argument. |

Who may open the app and what needs signing in are two separate settings; settle both now, not after the deploy:

- **Access** (`access` in `tinycloud.toml`): `private` (default: only the owner and you), `org`, or `public` (anyone with the URL). Signing in never gets anyone past a private app.
- **Sign-in** (`[auth]`, `[auth].protect`): which pages or actions need an account, once someone can open the app.

If the request means other people will use it (players, customers, a team) and does not say who, ask the user in your first reply which access they want, together with anything else you need from them, so the first deploy already has it. Never set `public` without their say-so.

Pick the stack you are best at that fits in one directory. Defaults that work well here: **Node 22 + a small server (Express/Hono/Fastify) serving a built frontend**, or plain server-rendered pages. Python 3.12 works too (`image = "python"`).

## Choose the AI primitive

TinyCloud's Console groups **Agents** and **Model Gateway** under **AI**. AI is the category, not a third API.

- **Model Gateway**: use for inference when your application owns the workflow, conversation state and tool execution. Examples: translation, classification, JSON extraction, streaming chat, or a fixed multi-step pipeline. Multiple steps or a single tool call alone do not require an Agent.
- **Agents**: use for autonomous tasks when TinyCloud should manage execution, the tool loop, progress, approvals and durable results or files. Examples: research that chooses its next actions, or a task that pauses for approval and then continues after the page closes.
- An app may use both for different features. A coding agent builds the app; an app's managed agent performs business tasks for its users.

Before implementation, discover availability with `tinycloud app integrations status --json` (Model Gateway) and `tinycloud app agents capabilities --json` (Agents). Use only authorized models and profiles reported as available. Do not silently replace an unavailable primitive with the other or ask for upstream credentials to bypass platform configuration. Do not deploy an Agent merely because a feature uses an LLM.

## Managed AI and payments

For model calls or checkout/subscriptions, use TinyCloud's managed integrations first:

```sh
tinycloud app integrations status --json
tinycloud app integrations enable ai          # if the operator has configured it
tinycloud app integrations enable payments    # requires Stripe key and webhook setup
tinycloud app integrations price --name "Pro" --amount 1200 --currency usd --interval month --idempotency-key pro-v1 --json
```

After enabling integrations or rotating credentials, use `tinycloud apply --yes` for an existing app or deploy normally for a new app. A plain process restart does not refresh environment variables.

Services receive `TINYCLOUD_GATEWAY_URL` and `TINYCLOUD_GATEWAY_TOKEN`. These are server-only: never use browser-visible env prefixes or return the runtime token in HTTP responses. Upstream MiniMax/Stripe keys stay in the control plane; do not ask the user to install them in the sandbox.

For AI, use the OpenAI SDK with `baseURL: process.env.TINYCLOUD_GATEWAY_URL + '/v1'`, `apiKey: process.env.TINYCLOUD_GATEWAY_TOKEN`, and a model from integration status. Chat completions support JSON and SSE streaming, tools and structured response parameters. Handle 429 and 503; do not retry without bounds.

For payments, the app server calls `${TINYCLOUD_GATEWAY_URL}/payments` with the runtime Bearer credential:

- `GET /catalog`: enabled prices.
- `POST /checkout`: `{subject, idempotencyKey, mode: 'payment'|'subscription', lineItems:[{priceId,quantity}], successUrl, cancelUrl}` → `{checkoutSession:{id,url},mode}`.
- `POST /portal`: `{subject,returnUrl}` → `{customerPortalSession:{url}}`.
- `GET /status?subject=...`: the subject's verified billing state.
- `GET /events?after=0`: `{events,next}`; persist the receipt-sequence cursor after processing events transactionally and deduplicate by event ID.

Derive `subject` from authenticated server context, not browser input. Return URLs must use `TINYCLOUD_APP_URL`. Do not grant entitlements from a success redirect: consume verified Stripe events, require `payment_status === 'paid'` for checkout completion, and handle async success, invoices, cancellation and refunds. The operator configures the webhook at the API origin's `/webhooks/stripe`; do not create a second app-level webhook or copy its signing secret into the app. Start in Stripe test mode. Keep external side effects idempotent using an outbox.

## Agents: managed tasks inside your App

Use `[[agent]]` for multi-step tasks that need tools, files, approval or a durable result. Your App keeps its own sandbox; the Agent runs in an independently managed E2B sandbox. You need no E2B or model-provider key.

```sh
tinycloud app agents capabilities --json
tinycloud app agents init researcher
tinycloud docs reference app agents
# Edit agents/researcher/{instructions.md,input.schema.json,output.schema.json}.
tinycloud check
tinycloud plan
tinycloud deploy -m "add researcher"
tinycloud app agents list --json
tinycloud app agents run researcher --input-file agents/researcher/example-input.json --idempotency-key task-001 --json
tinycloud app agents runs wait <run> --timeout 120 --json
tinycloud app agents runs events <run> --after 0 --follow --format ndjson
```

`capabilities` is authoritative: choose only authorized models and profiles. If it reports unavailable, ask the operator to configure Managed Agents. Do not install your own credentials or silently switch providers. Definitions activate only with a successful deployment; in-flight runs retain their original instructions, schemas, model connection and profile versions. Incompatible function/callback changes are blocked until the old runs and deliveries finish.

**Application API.** The App backend calls `process.env.TINYCLOUD_AGENTS_URL` (a supervisor loopback endpoint), for example `POST /runs` with `Idempotency-Key: report:<business-task-id>` and `{agent:"researcher",input:{task:"..."}}`. For a user task, forward the incoming trusted `X-TinyCloud-Agent-Context` header to that local call; TinyCloud derives the user identity. Never construct actor IDs from browser JSON. A missing context creates a background run with no human approver. Authenticate and authorize the business operation before starting it. Never expose the local URL through an unrestricted browser proxy.

The browser can read its own run at `/.tinycloud/agents/runs/<run>` and subscribe to `/events?stream=1`, using its existing App session. Use event `id` for reconnects. Actions, artifacts and cancellation use the same run path; POSTs require same-origin credentials. The browser cannot create runs directly or read another user's runs. Administrative CLI runs are developer runs, not impersonated end-user runs.

**Business tools.** Add `[[agent.function]]` with `name`, `description`, `handler="web:/agent-tools/save"`, `input_schema`, `output_schema`, `effect="write"` and `approval="user"` (or `developer` for a developer workflow). The handler must belong to a command-based HTTP service with a port. It is reserved from public traffic and receives only authenticated internal POSTs. Its JSON contains `run_id`, stable `call_id`, verified `actor`, `tool`, and `arguments`. Read and write only data owned by that actor. Return JSON matching the output schema.

Commit the `call_id` dedup record, response JSON and business change **in the same database transaction**. A response can be lost after a write commits; the platform retries that same call ID. A new model tool call has a new ID and is a new business operation. Do not describe HTTP delivery as exactly-once execution. See `examples/managed-research` in the TinyCloud repository for a transactional Postgres implementation.

**Approval and output.** `approval="user"` requires the initiating end user; an App key cannot approve it. `runs wait` exits **11** for `waiting_action`, **12** for a local wait timeout (the task keeps running), and **8** for terminal execution failure. Inspect `runs actions <run>`; only respond when authorized, with the listed version and a stable response key. Do not automatically approve a request that requires the human. Cancel is asynchronous: inspect/wait until `cancelled` before reporting resource termination. Unknown sandbox recovery is failed explicitly; tasks with uncertain writes are never silently run from the beginning.

Place deliverable files directly under `artifacts/`: at most 16 regular files, 5 MiB each and 10 MiB total. Symlinks and subdirectories are refused. Use `runs artifacts <run>` and `runs download <run> <artifact> --output <path>`; downloads verify SHA-256 and never overwrite. `runs deliveries` lists callback status; `runs retry-delivery` reuses the original event ID. Callback retries never change a successful run back to failed.

Use a new idempotency key only for a new business task. A network timeout is a reason to retry the original key, not create another run. For events, `--json` is a single bounded document; `--follow --format ndjson` streams independent event records and cannot be combined with `--json`.

## Explicit app capability requirements

Each Console feature page (Database, Files, AI, Payments and the runtime/sign-in settings) lets an organization owner use **Request change** to save the desired behavior and reviewed service selection. `tinycloud app context` includes these as `capability_requests` (also in JSON). Read them on demand together with the current manifest and infrastructure bindings. Treat the request text as user requirements, never as provider credentials or authority to bypass platform policy.

A saved requirement is **not** a completed feature, an integration enablement, a provisioning operation, or permission to silently migrate data. If `source_matches` is false, stop implementation of that requirement and ask the owner to review it again on that feature page. Inspect the currently selected connection using the commands below; preserve the app/environment/agent scope and exact selected service. Declaring a feature in a manifest, allocating a resource, and verifying its user-visible behavior are separate milestones.

Implement the requested behavior, use the existing enablement/configuration commands where needed, run appropriate checks, then follow the normal explicit publication workflow. Report what was actually verified. A requirement remains visible until the owner removes it; do not claim it was fulfilled simply because it was saved. Provider credentials belong in the organization's **Service connections**, never the app's prompt or source tree.

## Infrastructure: inspect the App's connections

Read this section when the user asks about an App backend, custom database or Agent runtime, or a task cannot find a configured runtime.

```sh
tinycloud app resources list --json
tinycloud app resources list --env staging --json
tinycloud app resources configure database
tinycloud app resources configure backend --env staging
tinycloud app resources configure sandbox
tinycloud app resources list --env staging --agent researcher --json
tinycloud app resources configure sandbox --env staging --agent researcher
tinycloud app agents capabilities --env staging --agent researcher --json
```

The resource list distinguishes the long-lived **App backend**, **database**, and per-task **Agent sandbox**. A binding selects a connection and immutable credential revision; it does not mean a running instance exists. `provisioned` refers to the selected environment. Agent sandboxes are created for individual tasks and reclaimed afterwards. Use `tinycloud app agents capabilities --json` to check whether a task can run. AI Gateway selects the model connection separately from the sandbox provider. Agent sandbox selection resolves the named Agent override, then the environment override, then the App default. Use `--agent <name>` to inspect the exact task runtime. Explicit TinyCloud managed selection overrides a parent connection; restoring inheritance follows the parent again. Accepted tasks retain their original immutable runtime binding.

The App key can read only this App's bindings. It cannot enumerate the organization's other connections, test supplier management keys or change bindings. `resources configure` only prints an authenticated Console destination: an organization owner configures credentials, verifies a template or selects a database region there. Do not ask for supplier keys, the admin token or browser session cookies. Owner CLI access is separate and requires browser approval; an App key never grants organization access.

For a Boat or Agent37 App backend, the admitted configuration is Node with `size = "medium"`, without managed volumes. The organization plan must allow medium. Ask the owner to resolve a plan or template-access restriction in Console; do not switch providers or request cloud keys. Use an external database for persistent data: runtime-local files survive stop/start but not instance replacement or deletion. Fly supports its published runtimes and volumes. App deployment and Agent sandbox admission are separate.

Changing the organization default only affects newly created Apps. Existing tasks retain their original connection revision. A database already provisioned cannot be moved by rebinding it: it needs a migration workflow. A failing customer connection never silently falls back to a platform account. TinyCloud-managed providers remain internal; use the public capability result rather than guessing a vendor or editing template/provider IDs into the manifest.

Database selection resolves the environment override, then the App default. Inherited environments use native branches in the App project. An explicit environment override creates an independent **empty project**, including when selecting TinyCloud managed; it never copies tables or data across accounts. Run the App's migrations on first deploy. Database scope becomes fixed as soon as provisioning is reserved, even if a supplier response is lost. Creating an environment with `tinycloud app env create <name> --defer-database` lets its owner choose a database before any provisioning. Do not combine independent databases with `--with-data`.

The resource list reports `connection.state`. When it is `disabled`, new bindings, database provisioning, Agent runs and template preparations are blocked. Existing resources and already accepted work can still be maintained and cleaned up. Ask the organization owner to verify and enable the connection or explicitly choose another one in Console → Infrastructure. Do not repeatedly retry `infrastructure_disabled` or substitute another account. Disabling a connection retains its credentials and bindings; it does not revoke the supplier-issued key. An owner can separately remove stored credentials after resolving defaults, App bindings and resources. Removal waits for accepted tasks and sandbox cleanup, continues in the background, and cannot be reversed; reconnect through a new connection. It does not invalidate the API key at the supplier.

### Organization owner workflow (only when requested)

An owner can authorize a terminal with `tinycloud org login --api-url <TinyCloud API origin>`.
The owner signs in to Console, compares the displayed code and explicitly selects an organization.
The authorization lasts 7 days and is limited to managing infrastructure; it cannot read App data,
return stored supplier secrets or act as an App key. Console → Infrastructure → CLI access lists
active terminals and can revoke them immediately. Removal from the organization, demotion or a
password reset invalidates the authorization. `tinycloud org logout` revokes it and removes its
local copy. The CLI stores it separately in `organization-credentials.json` with mode 0600; never
read or print that file. When multiple organizations are saved, choose `--org <id>` explicitly.

```sh
tinycloud org whoami --json
tinycloud org connections list --json
tinycloud org connections options <connection-id> --kind database --revision <revision> --json
tinycloud org connections usage <connection-id> --json
tinycloud org bindings list --app <app> --json
tinycloud org policies list --json
```

For a new connection, `tinycloud org connections test <provider> --stdin --json` accepts credential
JSON through stdin, returning discovered accounts and a short-lived `checkId`. Do not put a supplier
secret in arguments, prompts or logs. The owner selects the exact billing account, then runs
`tinycloud org connections save --check-id <id> --name <label> --account <discovered-account-id> --yes`.
Credential rotation uses `connections test --connection <id> --revision <current-revision>` before
saving. Testing alone does not replace an existing working credential.

Binding writes require explicit approval, including in JSON mode. Read available regions and
review the organization, billing account and revision first. For example:

```sh
tinycloud org bindings set database --app <app> --connection <id> --region <discovered-region> --yes
tinycloud org bindings set database --app <app> --env staging --connection <id> --region <discovered-region> --yes
tinycloud org bindings set database --app <app> --env staging --inherit --yes
tinycloud org bindings set backend --app <app> --env staging --connection <id> --region <region> --volume-gib 2 --yes
tinycloud org bindings set backend --app <app> --env staging --inherit --yes
tinycloud org bindings set sandbox --app <app> --env staging --agent researcher --platform --yes
tinycloud org bindings set sandbox --app <app> --env staging --agent researcher --inherit --yes
tinycloud org policies set agentConcurrentRuns --app <app> --limit 2 --yes
tinycloud org policies set databaseProjects --account <account-key> --limit 3 --yes
```

To attach an **existing Neon database**, first inspect resources using the same verified connection:

```sh
tinycloud org databases discover <connection> --revision <revision> --json
tinycloud org databases discover <connection> --revision <revision> --project <project-id> --json
tinycloud org databases discover <connection> --revision <revision> --project <project-id> --branch <branch-id> --json
tinycloud org databases attach --app <app> --env <environment> --connection <connection> --project <project-id> --branch <branch-id> --database <database-name> --role <login-role> --yes
tinycloud org databases show --app <app> --env <environment> --json
```

Existing database attachment is available only for an environment without database resources or
an active deployment. It does not migrate data. Inspection is read-only. TinyCloud management
permissions start disabled: `--allow-sql-writes` permits migrations, authentication tables, SQL writes
and imports; `--allow-reader-role` permits creating/configuring `tinycloud_reader` on that branch,
with database read grants for Console queries and exports; `--allow-restore` permits point-in-time
recovery and a preserved backup branch. Ask the owner which operations to allow; never silently
enable all permissions to make a deployment pass. The application's SQL access still comes from
the selected login role, independently of these management permissions. No attachment permission
allows deleting the provider project or branch. App/environment cleanup detaches the database and
retains provider data and roles. Existing TinyCloud metadata is not adopted automatically. Live
standalone disconnection is available to organization Owners. Use
`tinycloud org databases disconnect-plan --app <app> --env <environment> --json` first.
The plan lists runtimes to remove and data/volumes to retain. Then use
`tinycloud org databases disconnect --app <app> --env <environment> --expected-version <version> --yes`.
Active deployments, Agent work, database queries/exports and PostgreSQL proxy sessions must finish first.
The environment is fenced before runtime cleanup. If cleanup fails, inspect a new plan and retry;
do not deploy or switch bindings around pending cleanup. The database, persistent volumes and
history are retained. External passwords and connections are not revoked.

A disconnected environment stays paused until an Owner explicitly chooses a database. Reconnect
the same target with `org databases attach` and `--previous-resource <resourceId>` from
`org databases show`, reviewing the login role and management permissions again. Existing
TinyCloud metadata is accepted only for that recorded environment, database, role and provider
account. Alternatively, explicitly select another database connection for the environment or
attach a different clean database. Data is not migrated or copied. Redeploy to resume; no old
runtime is automatically restarted. App defaults alone do not resume a disconnected environment.
Managed database replacement and other existing-resource attachments remain separate work.

An organization Owner can change management grants in Console → App → Database → Environment →
Manage permissions, or with `tinycloud org databases permissions --app <app> --env <environment>
--sql-writes allow --yes`. Use `--reader-role allow|deny` and `--restore allow|deny` for the other
grants. Unspecified grants are preserved. Review the returned resource before confirming; a stale
version is rejected and must be reviewed again. Revocation also works when the provider connection
is disabled; granting additional access requires an active connection. These settings apply to
subsequent TinyCloud operations and subsequent queries on its database proxy. They do not change
the application's SQL role, rotate database passwords, remove existing roles, or cancel work already
submitted to the database. Permission editing never rebinds the resource to a rotated credential.

Policies add organization totals, App sublimits and per-provider-account guardrails. All applicable
limits are checked; increasing an App limit cannot bypass the organization's or platform's limit.
Use an account key from `org policies list`, not a supplier secret. `--organization` targets the
organization total; `--clear` removes only the named additional limit. Zero blocks new allocations.
Existing resources and runs are preserved when a limit is lowered. Stopped/provisioning instances,
pending database cleanup and Agent sandbox cleanup still hold capacity. Daily Agent usage is a
rolling 24-hour count of accepted runs, including failed and cancelled runs. Provider-account usage
only combines verified account identities inside this organization; usage outside TinyCloud is
not included. A conflict means another owner changed the policy: inspect it again before retrying.
Never raise a cap automatically in response to `quota_exceeded`; ask the owner to review it.

`--default` targets organization defaults instead of `--app`; `--platform` explicitly chooses
TinyCloud managed infrastructure instead of `--connection`. Database and Sandbox currently bind
at organization/App scope; only Backend supports Environment overrides. Sandbox selection needs
a verified template and, where required, its successful preparation ID from Console. Unsupported
suppliers or unverified capabilities remain unavailable. None of these commands migrates existing
resources. The regular App development workflow never needs this broader authorization.

## 2. Initialise the project

```sh
mkdir -p <app> && cd <app>
tinycloud init          # writes tinycloud.toml (only if missing) + .tinycloud/link.json; adds its lines to an existing .gitignore and keeps a TinyCloud block in AGENTS.md
```

Edit `tinycloud.toml`. A complete example:

```toml
public_paths = ["/webhooks/*"]    # optional, before any [table]: paths anyone may reach even when the app is private (a payment provider's or GitHub's webhook). Verify the provider's signature there.

[app]
name = "crm"

[runtime]
image = "node"                    # node | python | base
size  = "small"                   # nano | small | medium | large
build = ["npm ci", "npm run build"]   # runs in the cloud on every deploy

[[service]]
name    = "web"
command = "node server.js"
port    = 3000                    # the platform sets PORT; this is only a hint
health  = "/healthz"              # must return 2xx when ready

[database]
migrations = "migrations/"        # 0001_init.sql, 0002_….sql — the only way to change tables

[[volume]]
name  = "uploads"
mount = "/data/uploads"

[auth]                            # on by default; delete it for a fully anonymous site. Sign-in only: who may reach the app at all is the access level (private by default)
providers = ["github"]          # only providers `tinycloud whoami` lists as working here
protect   = ["/app/*"]            # optional: paths that require login

[[schedule]]
name   = "daily-summary"
cron   = "0 9 * * *"              # UTC
target = "web:/jobs/daily-summary"

[variables]
LOG_LEVEL = "info"
```

## 3. Runtime rules your code must follow

These are hard requirements. Most failed deploys break one of them.

1. **Listen on `process.env.PORT` on `0.0.0.0`.** Never hardcode the port, never bind `127.0.0.1`/`localhost`.
2. **The app owns its origin.** Each environment is served at the root of its own origin (`TINYCLOUD_APP_URL`, e.g. `https://<port>-d-<hex>.proxy.dev.tinycloud.ai`, no trailing slash), so ordinary root-absolute links (`/api/items`, `/assets/app.js`) and any framework's defaults work. Never hardcode or guess that URL: build absolute links (emails, third-party callbacks) from `process.env.TINYCLOUD_APP_URL`, and read it for your own checks from `tinycloud app context --json | jq -r .urls.app`.
3. **Health endpoint** at the `health` path returning 2xx quickly (no DB call needed). Traffic switches only after it passes.
4. **Exit on SIGTERM** within 10 s.
5. **Logs to stdout/stderr.** That is all `tinycloud app logs` can see.
6. **Persistent data only in the database or a volume path.** Local disk is wiped on every deploy and rebuild.
7. **Database:** connect with `process.env.DATABASE_URL` (SSL is in the URL; with `pg` use `new Pool({ connectionString: process.env.DATABASE_URL })`). Change tables only by adding a new numbered file in `migrations/`; never edit an applied migration. `tinycloud app sql` runs read-only unless you pass `--write`, and on `main` it refuses DDL even then.
8. **Login** (`[auth]`, on by default): link to `/.tinycloud/auth/login?next=/app` and `/.tinycloud/auth/logout?next=/` (`next` is a path inside the app). The platform handles OAuth: the browser briefly leaves your origin for the provider and comes back to `next` signed in. Never implement callbacks or sessions yourself, and never set cookies whose name starts with `tc_` or that carry a `Domain` attribute (the platform drops them).
   - Providers: list only those `tinycloud whoami` shows under "Sign-in that works here" (`init` writes exactly those), and build the login page with only those buttons. Other supported providers (`google`, `microsoft`, `apple`, `x`, `facebook`, `line`, `telegram`, `zalo`) work once the user adds their own login credentials in the console (Auth › Sign-in methods); if the user wants one, explain the setup instead of showing an unavailable button. LINE uses a Web LINE Login channel; Telegram uses the Client ID and Client Secret from BotFather's Login Widget (not the Bot API token); Zalo uses an active app's App ID and Secret Key. These three require the app's own credentials and request only login/profile access. LINE, Telegram, Zalo and X may provide no email, and Apple or Facebook users may withhold it, so key users by id, never by email. Use the provider ids `line`, `telegram`, `zalo` in `[auth].providers` after setup.
   - Signed-in requests carry `X-TinyCloud-User-Id` (uuid), `X-TinyCloud-User-Email` (URI-encoded when it is not plain ASCII), `X-TinyCloud-User-Name` (always URI-encoded) and `X-TinyCloud-User-Provider`; read the email and name with `decodeURIComponent`. No header = anonymous. The platform strips these from what browsers send, so trust them. Scope every per-user query by the user id.
   - `X-TinyCloud-User-Role` is `owner` when the visitor manages this App in the TinyCloud console (the user who asked you for the app, and their teammates), else `user`; `/.tinycloud/auth/me` returns it as `role`. Gate an admin or back-office area on it: never ask the user for their account name, never hardcode an email or id. Check both sides with `tinycloud app curl /admin --as owner@example.com --role owner` and `--as someone@example.com`.
   - `[auth].protect` paths need login: a `GET` that accepts `text/html` (a browser) is redirected (302) to `/.tinycloud/auth/login`, everything else gets 401 JSON. For other pages decide yourself, and use `/.tinycloud/auth/me` (JSON or 401) from the frontend.
   - Optional: `X-TinyCloud-Identity` is an RS256 JWT (5 min) with the same user, for when you forward identity to another service. Verify its signature against `${TINYCLOUD_APP_URL}/.tinycloud/auth/jwks.json` **and check that `aud` equals `TINYCLOUD_APP_URL` exactly**. Every app's tokens are signed with the same key, so a token with another `aud` belongs to another app and must be refused.
   - With `[database]`, users also appear in `tinycloud.users(id, email, name, provider, created_at, last_login_at)`. For row-level security run `SET LOCAL tinycloud.user_id = '<id>'` in the transaction and write policies with `tinycloud.current_user_id()`.
9. **Frontend build output** (`dist/`, `build/`) is produced in the cloud by `[runtime].build`; do not commit or rely on uploading it. Commit a lockfile (`package-lock.json`, `uv.lock`) so the cloud build matches yours.
10. Environment variables available at runtime: `PORT`, `TINYCLOUD_APP_URL`, `TINYCLOUD_APP` (the App name), `TINYCLOUD_ENV`, `DATABASE_URL` (if `[database]`), everything in `[variables]` and `[secrets]`. Those platform names (`DATABASE_URL`, `PORT`, anything starting with `TINYCLOUD_`) cannot be `[variables]` or `[secrets]` names (`check` rule `reserved_variable`). Volumes are plain directories at their `mount` path.

## 4. The loop

```sh
tinycloud check             # local, instant: fix every error it lists (file:line, rule)
tinycloud plan              # what will change online
tinycloud apply --yes       # create database / volumes / login now (no code upload)
tinycloud app dev --env qa  # run locally against a cloud database (qa's, so experiments stay out of main); writes .env.local (DATABASE_URL = a local proxy, no password)
tinycloud deploy -m "what changed"   # upload → cloud build → migrate → start → health → live
```

- Run `check` after every edit to `tinycloud.toml` or `migrations/`. Its JSON form is `tinycloud check --json`.
- New table or column: `tinycloud app db migration new <name>` creates the next numbered file; `tinycloud app db diff` shows which files are applied, pending or (never do this) edited after applying.
- Database tools that need a real Postgres connection (psql, an ORM's studio, a seed script): `tinycloud app db proxy` opens `127.0.0.1:5432` (`--port <n>` if that is taken) and prints the DATABASE_URL to use; it runs until Ctrl-C, so start it in the background. It is read-only; `--write` logs in as the owner (on `main` schema changes are still refused: use a migration). Any user name works and there is no password: the CLI authenticates with the App key. `app dev` starts the same proxy as the owner for the app it runs.
- Bulk data: `tinycloud app db export --table <t> -o t.csv` (one table as CSV) or `tinycloud app db export --format sql -o dump.sql` (schema and data); `tinycloud app db import rows.csv --table <t> --yes` appends a CSV whose first line names the columns, all rows or none, with a snapshot taken first. Importing changes the user's data: on `main` ask first.
- `tinycloud deploy --dry-run` runs check and plan and sizes the upload without deploying.
- `deploy` streams progress (`--verbose` adds the build output) and returns only when the deployment is live or failed.
- Exit codes (every command; the error's `code` says which case it is):
  - 0 ok.
  - 1 anything else: a usage error, `sql_error`, `conflict` (for example five deployments already queued, or a name that already exists), `http_error` from `app curl --fail`. Do what `next` says.
  - 2 bad or missing key · 3 App or environment missing · 4 not found.
  - 5 `forbidden` (outside the key's scope, or DDL on main: use a migration), or `write_requires_flag`: the SQL changes data and nothing ran; rerun it with `--write` if you meant to write.
  - 6 `unavailable` or `rate_limited`: wait 30 s and rerun, at most 3 times.
  - 7 manifest invalid: fix every error listed, then rerun · 8 deploy failed (see below).
  - 9 `stale_base`: someone changed the app online (console, another agent) since your tinycloud.toml was synced. Run `tinycloud app pull` (your file is kept as tinycloud.toml.bak), review `diff tinycloud.toml.bak tinycloud.toml`, re-apply your own edits, then deploy again. Rerunning `plan` alone exits 9 again, and `--force` overwrites the user's online changes: never use it unless the user asks you to discard them.
  - 10 `confirmation_required`: the command asks first and you gave no `--yes` (agents have no terminal). For a destructive command, show the user what it destroys and rerun with `--yes` only after they agree; for `apply`, just rerun with `--yes`.
- A failed deploy prints the failed step, the last 50 log lines, a cause (`missing_lockfile`, `port_binding`, `health_404`, `crash_on_start`, `missing_variable`, `migration_sql_error` with file and line, `build_timeout`, …) and the fix, whose commands run as written. Apply the fix and deploy again. The previous version keeps serving meanwhile. Use `tinycloud app rollback <N>` only if the user asks or the live app is broken and you cannot fix it quickly.
- If the platform is at fault (a command misbehaves, this guide contradicts what happens, or a capability you need is missing), report it once with `tinycloud feedback "<what happened, what you expected>" --command "<the command>"`, then carry on with a workaround. Never report bugs in the app's own code.
- Stuck or unsure what is wrong: `tinycloud doctor` checks the key, the project, the last deployment, crash-looping services, the database, pending migrations, sign-in and reachability, and lists the problems worst first, each with its fix.
- A rejected request can fail before a deployment number exists. Preserve `request_id` and `stage` from the error; `tinycloud doctor --json` includes retained deployment-request blockers. A network timeout does not prove the operation failed: inspect deployments before creating another. Never paste credentials into a diagnostic report.
- Debug a running app: `tinycloud app logs --source web --level error --since 10m` (also `--grep <regex>`, `--deployment <N>`, `--follow`), `tinycloud app services`, `tinycloud app deployment <N> --logs` (timeline with every log line).
- Files on a volume: `tinycloud app volume ls uploads:/`, `tinycloud app volume cp ./seed.png uploads:/seed.png`, and to clean up what your checks left behind, `tinycloud app volume rm uploads:/test.png --yes` (a folder with `--recursive`). Live variables: `tinycloud app vars list` (secrets masked).

## 5. Verify before you report

Never report success from the deploy exit code alone. Check what the user asked for, and keep test data out of the user's app: checks that create data run in a throwaway environment, which you delete afterwards.

```sh
tinycloud app env create qa                 # its own URL, database branch (schema, no rows), volumes and users
tinycloud deploy --env qa -m "verify"
tinycloud app curl /healthz --env qa --expect 200
tinycloud app curl /api/items --env qa -X POST -d '{"title":"x"}' --as qa@example.com --expect 201 --body --json
tinycloud app sql "select count(*) from <table>" --env qa --json
tinycloud app env delete qa --yes            # removes everything the checks created
tinycloud deploy -m "what changed"           # then main; on main, only read-only checks:
tinycloud app curl / --expect 200
```

- `app curl` only ever talks to this environment's own URL, shows redirects instead of following them, and prints status, headers and body (`--json`: `{status, ok, redirect, headers, body_json | body}`; Set-Cookie values are redacted). `--expect 200` (or `302`, `200,201`) exits 1 on any other status, so a check fails loudly; `--body` prints just the body. Do not paste the App key into curl yourself.
- Exercise every feature the user named, through HTTP, the way a browser would (create, list, edit, delete; upload then fetch the file; a protected page refuses an anonymous request).
- Login-only flows: `--as qa@example.com` signs in a 15-minute test user, so your service gets that user's `X-TinyCloud-User-*` headers. Without it, `tinycloud app curl /app` on a protected page answers 401 (`app curl` does not ask for HTML); add `-H 'Accept: text/html'` to see what a browser gets, a 302 to `/.tinycloud/auth/login`.
- Anything with a screen to look at (a game, a canvas, a multi-step UI) is not verified by HTTP alone: open it in your browser tool and use it. `tinycloud app open --print-url --as qa@example.com --path /play --json` gives a one-time link already signed in as the test user (`--role owner` for owner-only pages). Check what the user will see: layout, the flows they named, and the browser console for errors.
- If a check fails, fix and redeploy. Report only when all pass.
- If checks had to run on `main`, clean up after yourself: the rows (`tinycloud app sql --write "delete from <table> where …"`), the files (`tinycloud app volume rm uploads:/<file> --yes`), and the test users (`tinycloud app auth users purge-test --yes`), so the user starts with an empty app unless they asked for sample data.

## 6. Report to the user

One short message:

- The app's permanent URL (`url` in `tinycloud app status --json`). Never hand over a one-time link from `app open --print-url`: it expires a minute after you create it and works once, so it is dead by the time the user reads your message. A private app opens for its owner with **Open app** in the TinyCloud console, and its URL shows a page that says so; tell the user that in one sentence. Never put the App key in a link.
- What you built, in their words, and what you verified (list).
- Anything only they can decide, phrased as a question: making the app public when their request did not say who may open it (until then nobody but the owner can use it, signed in or not), having an admin add a third-party key, a custom domain.

Do not mention internal steps, retries, or platform terms (Spec, Release, sandbox, tunnel).

## Rules

- Never print, log, commit, or echo `TINYCLOUD_API_KEY`, `DATABASE_URL`, or any secret. Never pass them as command-line arguments. (The CLI masks them in its own output, but your shell commands are yours.)
- Make the app `public` (`tinycloud app access set public --yes`) only when the user said so. A request that people who are not signed in, or anyone with the link, can open or browse the app is them saying so: set it public as part of the build and name it in your report. Otherwise leave it private and ask.
- Never delete an environment, database, or volume unless the user asked.
- Destructive commands (`app env delete`, `app db restore`, `app db reset`, `app rollback --with-database`) refuse without `--yes` and print exactly what they would destroy. Show that list to the user and rerun with `--yes` only after they agree. `app access set public` also asks for `--yes`; the rule above says when the user's request already gave it.
- Stay inside this App; do not try other TinyCloud APIs.

## Branding hosted pages

Only when the user asks to customize the waiting or unavailable page, read `<TINYCLOUD_API_URL>/branding.md`. This optional App-key API controls the hosted page brand; it does not change the app UI. All other workflows continue to use the CLI.

### Managed database allocation

For ordinary new Apps, declare `[database]` and add migrations; TinyCloud supplies a private database and account on shared PostgreSQL when needed. Apps without `[database]` allocate none. Use the injected `DATABASE_URL`; do not request provider credentials or install PostgreSQL in the sandbox. Existing Apps keep their original allocation. Explicit external database connections still take precedence.

Shared compute does not imply shared tables or a shared login. This tier has no per-App point-in-time restore or database branch copy. Use SQL/CSV exports, a separate App, or an explicitly connected database when those features are needed. Check capabilities before requesting restore or cloning.
