{"owner":"prisma","repo":"COMPOSER","hasSkills":true,"totalSkillsCount":15,"totalTokensCount":46952,"categories":["anthropic-skill","subagent-persona","root-instruction","claude-rule","cursor-rule","plugin-manifest"],"hasMcp":false,"mcpConfig":null,"found":[".agents/rules/README.md",".claude/agents/domain-modeler.md","AGENTS.md","CLAUDE.md","docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc","packages/1-prisma-cloud/2-shared-modules/auth/README.md","packages/1-prisma-cloud/2-shared-modules/email/README.md","packages/1-prisma-cloud/2-shared-modules/storage/README.md","packages/1-prisma-cloud/2-shared-modules/streams/README.md","skills-contrib/multiline-commit-messages/SKILL.md","skills-contrib/publish-npm-version/SKILL.md","skills-contrib/upgrade-alchemy-effect/SKILL.md","skills-contrib/upstream-alchemy-distilled/SKILL.md","skills/README.md","skills/prisma-composer-core-concepts/SKILL.md"],"skills":{".agents/rules/README.md":"# Agent Rules Index\n\nCurated rules for agents and developers — quick, actionable guidance.\n\n## Canonical home & sync\n\nEvery rule has a single canonical home: `.agents/rules/<name>.mdc` — the only\ngit-tracked copy. Rule files must use the `.mdc` extension; the harnesses load\n`.mdc` only, so a `.md` rule is silently dead (`pnpm lint:rules:symlinks`\nrejects them). The `.cursor/rules/` and `.claude/rules/` trees are git-ignored\npresentation mirrors containing nothing but relative symlinks back into\n`.agents/rules/`.\n\n```bash\npnpm rules:sync           # Consolidate stray rules + (re)generate the symlink trees\npnpm lint:rules:symlinks  # Fail if a tree is out of sync with canonical (runs in CI)\n```\n\n`rules:sync` also runs from `prepare`, so `pnpm install` rebuilds the trees\nautomatically. **Add or edit rules at the canonical path** (`.agents/rules/`);\na rule dropped only into `.cursor/rules` is git-ignored and will be lost.\n",".claude/agents/domain-modeler.md":"---\nname: domain-modeler\ndescription: Research and write DDD-style domain models for external systems (e.g. Cloudflare/Wrangler) as structured docs under docs/design/04-inspirations/.\ntools: Read, Write, Bash, WebFetch\ncolor: blue\nmodel: inherit\n---\n\nYou are a domain modeling and domain research specialist.\n\nYour job is to take a target system (product + tooling) and produce a **DDD-style written domain description**: ubiquitous language, core concepts, relationships, user workflows, and behavioral/execution flows — written as a small library of docs that can be reused in later design discussions.\n\nThis agent is designed to be “set loose”: you do the research, make reasonable modeling calls, and leave behind a coherent, cross-linked documentation set.\n\n## Core responsibilities\n\n1. **Capture ubiquitous language**\n   - Build a glossary of the system’s key terms as *users* use them (and note internal/mechanical terms separately).\n   - Prefer the product’s native vocabulary over invented terms; call out synonyms and overloaded words.\n\n2. **Model the domain (things + relationships + behaviors)**\n   - Produce a conceptual domain map (relationships between the core concepts).\n   - Enumerate the primary operations (“verbs”) on those concepts.\n   - Document behavioral relationships: what triggers what, what depends on what, what must be true.\n\n3. **Model the user mental model + UX workflows**\n   - Document the user’s day-to-day mental model.\n   - Capture the common workflows (happy paths + sharp edges) as step-by-step flows.\n\n4. **Separate stable research from evolving takeaways**\n   - Keep “how the system works” relatively stable in research docs.\n   - Keep “what Prisma Composer should do because of it” in a separate takeaways doc that can evolve.\n\n5. **Be explicit about uncertainty**\n   - Track open questions and assumptions at the end of each doc.\n   - When unsure, write the best current model and clearly label it as an assumption.\n\n## Workflow (every time)\n\n### Step 0: Anchor on the repo’s doc system (read-first)\n\nRead:\n- `docs/design/README.md`\n- `docs/design/99-process/README.md`\n- `docs/design/04-inspirations/README.md`\n- Any existing inspiration docs for the target system (if present)\n\nGoal: match the house style and keep outputs discoverable and consistent.\n\n### Step 1: Define scope + output location\n\nDecide:\n- The **target system name** (e.g. “Cloudflare”, “Cloudflare Wrangler”, “Cloudflare Workers + Wrangler”).\n- What is in-scope vs out-of-scope (product surfaces, runtime primitives, billing/account, etc.).\n\nCreate (or update) a research library folder:\n- `docs/design/04-inspirations/<System>/`\n\nIf a single-file inspiration note already exists (e.g. `docs/design/04-inspirations/cloudflare.md`), treat it as a short overview and keep the detailed model in the folder.\n\n### Step 2: Research (prefer primary sources)\n\nUse official docs and product references first (then reputable secondary sources).\n\nWhile researching, continuously extract:\n- **Nouns** (things): resources, identifiers, configuration objects, runtimes, projects, accounts.\n- **Verbs** (operations): create/update/deploy/bind/route/observe/debug/rollback.\n- **Rules** (invariants): what must always hold; what configurations are invalid; what is “the unit of deployment”.\n- **Workflows** (UX): “day 1” setup, deploy, local dev, preview/staging, rollout, rollback, debugging.\n- **Control-plane vs runtime split** (if applicable): author-time/build-time/deploy-time vs runtime execution.\n\n### Step 3: Write the DDD artifacts (structured library)\n\nProduce this set of files (mirrors the `TanStack/` pattern):\n\n- `README.md`\n  - what this library covers, what to read, key sources\n- `glossary.md`\n  - terms + definitions; note “user-facing?”; include synonyms/aliases\n- `domain-map.md`\n  - a conceptual relationship map (use Mermaid where useful)\n- `operations.md`\n  - the primary operations on core concepts (CRUD + lifecycle + operational verbs)\n- `user-domain.md`\n  - the user mental model and how it maps to underlying mechanics\n- `execution-flows.md`\n  - the “always happening” flows (deploy lifecycle, routing, local dev loops, etc.)\n- `takeaways-for-prisma-composer.md`\n  - explicitly evolving: what Prisma Composer should emulate/adapt, plus design questions raised\n\nWriting guidelines:\n- Prefer **small, scannable** docs over one huge one.\n- Keep each doc focused; cross-link instead of duplicating.\n- Include **1–2 diagrams** when they materially improve comprehension.\n- Keep a short **Open questions / assumptions** section at the bottom of each file.\n\n### Step 4: Integrate with the inspiration index\n\nUpdate `docs/design/04-inspirations/README.md` to list the new folder (or new key docs) so the library is discoverable.\n\n### Step 5: Finish with a “what changed” summary\n\nWhen done, summarize:\n- Files created/updated\n- Key domain concepts discovered (5–10 bullets)\n- The most important workflows (3–5 bullets)\n- Open questions / unknowns (explicit list)\n\n## Output expectations\n\nWhen asked to “model Cloudflare + Wrangler”, a successful output usually includes:\n\n- A new folder: `docs/design/04-inspirations/Cloudflare/` (or similarly named)\n- The standard library docs listed above, cross-linked and consistent\n- A takeaways doc that cleanly separates “research facts” from “Prisma Composer implications”\n\n## Guardrails\n\n- Do **not** change Prisma Composer’s core domain docs (`docs/design/03-domain-model/`, `docs/design/10-domains/`) unless the user explicitly asks you to translate research into Prisma Composer design changes.\n- Do **not** create ADRs unless the user explicitly indicates a decision has been made.\n- Prefer documenting what you can verify; label inferred models as assumptions.\n","AGENTS.md":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","CLAUDE.md":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## A layer does not know what is built on it\n\nThis is an\n[architectural principle](docs/design/01-principles/architectural-principles.md#a-layer-does-not-know-what-is-built-on-it),\nand it is the one agents most often break without noticing. It comes up as a\nshortcut: code in a higher layer needs a value, the only thing it holds is a\nlower layer's interface, and one more member on that interface is the shortest\nway. Stop there and read the principle.\n\nIf the member would exist for one kind of Connection, one deployment target or\none Module, do not build it. Do not offer it to the operator as an option\neither, whether the idea is yours or a subagent's: the operator would have to\ncatch the problem themselves, and the gap in the design you found would go\nunreported. Report the gap instead: what the higher layer needs, and why\nnothing that exists carries it.\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc":"---\ndescription: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples\nglobs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx\n---\n\n# Convex guidelines\n## Function guidelines\n### New function syntax\n- ALWAYS use the new function syntax for Convex functions. For example:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\nexport const f = query({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n    // Function body\n    },\n});\n```\n\n### Http endpoint syntax\n- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:\n```typescript\nimport { httpRouter } from \"convex/server\";\nimport { httpAction } from \"./_generated/server\";\nconst http = httpRouter();\nhttp.route({\n    path: \"/echo\",\n    method: \"POST\",\n    handler: httpAction(async (ctx, req) => {\n    const body = await req.bytes();\n    return new Response(body, { status: 200 });\n    }),\n});\n```\n- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.\n\n### Validators\n- Below is an example of an array validator:\n```typescript\nimport { mutation } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport default mutation({\nargs: {\n    simpleArray: v.array(v.union(v.string(), v.number())),\n},\nhandler: async (ctx, args) => {\n    //...\n},\n});\n```\n- Below is an example of a schema with validators that codify a discriminated union type:\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n    results: defineTable(\n        v.union(\n            v.object({\n                kind: v.literal(\"error\"),\n                errorMessage: v.string(),\n            }),\n            v.object({\n                kind: v.literal(\"success\"),\n                value: v.number(),\n            }),\n        ),\n    )\n});\n```\n- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport const exampleQuery = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n      console.log(\"This query returns a null value\");\n      return null;\n  },\n});\n```\n- Here are the valid Convex types along with their respective validators:\nConvex Type  | TS/JS type  |  Example Usage         | Validator for argument validation and schemas  | Notes                                                                                                                                                                                                 |\n| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Id          | string      | `doc._id`              | `v.id(tableName)`                              |                                                                                                                                                                                                       |\n| Null        | null        | `null`                 | `v.null()`                                     | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead.                             |\n| Int64       | bigint      | `3n`                   | `v.int64()`                                    | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers.                                                                                              |\n| Float64     | number      | `3.1`                  | `v.number()`                                   | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings.                                                                      |\n| Boolean     | boolean     | `true`                 | `v.boolean()`                                  |\n| String      | string      | `\"abc\"`                | `v.string()`                                   | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8.                                                         |\n| Bytes       | ArrayBuffer | `new ArrayBuffer(8)`   | `v.bytes()`                                    | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types.                                                     |\n| Array       | Array       | `[1, 3.2, \"abc\"]`      | `v.array(values)`                              | Arrays can have at most 8192 values.                                                                                                                                                                  |\n| Object      | Object      | `{a: \"abc\"}`           | `v.object({property: value})`                  | Convex only supports \"plain old JavaScript objects\" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with \"$\" or \"_\". |\n| Record      | Record      | `{\"a\": \"1\", \"b\": \"2\"}` | `v.record(keys, values)`                       | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with \"$\" or \"_\".                                                               |\n\n### Function registration\n- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.\n- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.\n- You CANNOT register a function through the `api` or `internal` objects.\n- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.\n- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.\n\n### Function calling\n- Use `ctx.runQuery` to call a query from a query, mutation, or action.\n- Use `ctx.runMutation` to call a mutation from a mutation or action.\n- Use `ctx.runAction` to call an action from an action.\n- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.\n- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.\n- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.\n- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,\n```\nexport const f = query({\n  args: { name: v.string() },\n  returns: v.string(),\n  handler: async (ctx, args) => {\n    return \"Hello \" + args.name;\n  },\n});\n\nexport const g = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const result: string = await ctx.runQuery(api.example.f, { name: \"Bob\" });\n    return null;\n  },\n});\n```\n\n### Function references\n- Function references are pointers to registered Convex functions.\n- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.\n- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.\n- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.\n- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.\n- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.\n\n### Api design\n- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.\n- Use `query`, `mutation`, and `action` to define public functions.\n- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.\n\n### Pagination\n- Paginated queries are queries that return a list of results in incremental pages.\n- You can define pagination using the following syntax:\n\n```ts\nimport { v } from \"convex/values\";\nimport { query, mutation } from \"./_generated/server\";\nimport { paginationOptsValidator } from \"convex/server\";\nexport const listWithExtraArg = query({\n    args: { paginationOpts: paginationOptsValidator, author: v.string() },\n    handler: async (ctx, args) => {\n        return await ctx.db\n        .query(\"messages\")\n        .withIndex(\"by_author\", (q) => q.eq(\"author\", args.author))\n        .order(\"desc\")\n        .paginate(args.paginationOpts);\n    },\n});\n```\nNote: `paginationOpts` is an object with the following properties:\n- `numItems`: the maximum number of documents to return (the validator is `v.number()`)\n- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)\n- A query that ends in `.paginate()` returns an object that has the following properties:\n- page (contains an array of documents that you fetches)\n- isDone (a boolean that represents whether or not this is the last page of documents)\n- continueCursor (a string that represents the cursor to use to fetch the next page of documents)\n\n\n## Validator guidelines\n- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.\n- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.\n\n## Schema guidelines\n- Always define your schema in `convex/schema.ts`.\n- Always import the schema definition functions from `convex/server`.\n- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.\n- Always include all index fields in the index name. For example, if an index is defined as `[\"field1\", \"field2\"]`, the index name should be \"by_field1_and_field2\".\n- Index fields must be queried in the same order they are defined. If you want to be able to query by \"field1\" then \"field2\" and by \"field2\" then \"field1\", you must create separate indexes.\n\n## Typescript guidelines\n- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.\n- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:\n```ts\nimport { query } from \"./_generated/server\";\nimport { Doc, Id } from \"./_generated/dataModel\";\n\nexport const exampleQuery = query({\n    args: { userIds: v.array(v.id(\"users\")) },\n    returns: v.record(v.id(\"users\"), v.string()),\n    handler: async (ctx, args) => {\n        const idToUsername: Record<Id<\"users\">, string> = {};\n        for (const userId of args.userIds) {\n            const user = await ctx.db.get(\"users\", userId);\n            if (user) {\n                idToUsername[user._id] = user.username;\n            }\n        }\n\n        return idToUsername;\n    },\n});\n```\n- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.\n- Always use `as const` for string literals in discriminated union types.\n- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`\n- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`\n- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.\n\n## Full text search guidelines\n- A query for \"10 messages in channel '#general' that best match the query 'hello hi' in their body\" would look like:\n\nconst messages = await ctx.db\n  .query(\"messages\")\n  .withSearchIndex(\"search_body\", (q) =>\n    q.search(\"body\", \"hello hi\").eq(\"channel\", \"#general\"),\n  )\n  .take(10);\n\n## Query guidelines\n- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.\n- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.\n- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.\n- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.\n### Ordering\n- By default Convex always returns documents in ascending `_creationTime` order.\n- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.\n- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.\n\n\n## Mutation guidelines\n- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })`\n- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })`\n\n## Action guidelines\n- Always add `\"use node\";` to the top of files containing actions that use Node.js built-in modules.\n- Never use `ctx.db` inside of an action. Actions don't have access to the database.\n- Below is an example of the syntax for an action:\n```ts\nimport { action } from \"./_generated/server\";\n\nexport const exampleAction = action({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        console.log(\"This action does not return anything\");\n        return null;\n    },\n});\n```\n\n## Scheduling guidelines\n### Cron guidelines\n- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.\n- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.\n- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,\n```ts\nimport { cronJobs } from \"convex/server\";\nimport { internal } from \"./_generated/api\";\nimport { internalAction } from \"./_generated/server\";\n\nconst empty = internalAction({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    console.log(\"empty\");\n  },\n});\n\nconst crons = cronJobs();\n\n// Run `internal.crons.empty` every two hours.\ncrons.interval(\"delete inactive users\", { hours: 2 }, internal.crons.empty, {});\n\nexport default crons;\n```\n- You can register Convex functions within `crons.ts` just like any other file.\n- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file.\n\n\n## File storage guidelines\n- Convex includes file storage for large files like images, videos, and PDFs.\n- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.\n- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.\n\nInstead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<\"_storage\">`.\n```\nimport { query } from \"./_generated/server\";\nimport { Id } from \"./_generated/dataModel\";\n\ntype FileMetadata = {\n    _id: Id<\"_storage\">;\n    _creationTime: number;\n    contentType?: string;\n    sha256: string;\n    size: number;\n}\n\nexport const exampleQuery = query({\n    args: { fileId: v.id(\"_storage\") },\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        const metadata: FileMetadata | null = await ctx.db.system.get(\"_storage\", args.fileId);\n        console.log(metadata);\n        return null;\n    },\n});\n```\n- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.\n\n\n# Examples:\n## Example: chat-app\n\n### Task\n```\nCreate a real-time chat application backend with AI responses. The app should:\n- Allow creating users with names\n- Support multiple chat channels\n- Enable users to send messages to channels\n- Automatically generate AI responses to user messages\n- Show recent message history\n\nThe backend should provide APIs for:\n1. User management (creation)\n2. Channel management (creation)\n3. Message operations (sending, listing)\n4. AI response generation using OpenAI's GPT-4\n\nMessages should be stored with their channel, author, and content. The system should maintain message order\nand limit history display to the 10 most recent messages per channel.\n\n```\n\n### Analysis\n1. Task Requirements Summary:\n- Build a real-time chat backend with AI integration\n- Support user creation\n- Enable channel-based conversations\n- Store and retrieve messages with proper ordering\n- Generate AI responses automatically\n\n2. Main Components Needed:\n- Database tables: users, channels, messages\n- Public APIs for user/channel management\n- Message handling functions\n- Internal AI response generation system\n- Context loading for AI responses\n\n3. Public API and Internal Functions Design:\nPublic Mutations:\n- createUser:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({userId: v.id(\"users\")})\n  - purpose: Create a new user with a given name\n- createChannel:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({channelId: v.id(\"channels\")})\n  - purpose: Create a new channel with a given name\n- sendMessage:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), authorId: v.id(\"users\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Send a message to a channel and schedule a response from the AI\n\nPublic Queries:\n- listMessages:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n    }))\n  - purpose: List the 10 most recent messages from a channel in descending creation order\n\nInternal Functions:\n- generateResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.null()\n  - purpose: Generate a response from the AI for a given channel\n- loadContext:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }))\n- writeAgentResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Write an AI response to a given channel\n\n4. Schema Design:\n- users\n  - validator: { name: v.string() }\n  - indexes: <none>\n- channels\n  - validator: { name: v.string() }\n  - indexes: <none>\n- messages\n  - validator: { channelId: v.id(\"channels\"), authorId: v.optional(v.id(\"users\")), content: v.string() }\n  - indexes\n    - by_channel: [\"channelId\"]\n\n5. Background Processing:\n- AI response generation runs asynchronously after each user message\n- Uses OpenAI's GPT-4 to generate contextual responses\n- Maintains conversation context using recent message history\n\n\n### Implementation\n\n#### package.json\n```typescript\n{\n  \"name\": \"chat-app\",\n  \"description\": \"This example shows how to build a chat app without authentication.\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"convex\": \"^1.31.2\",\n    \"openai\": \"^4.79.0\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.7.3\"\n  }\n}\n```\n\n#### tsconfig.json\n```typescript\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"exclude\": [\"convex\"],\n  \"include\": [\"**/src/**/*.tsx\", \"**/src/**/*.ts\", \"vite.config.ts\"]\n}\n```\n\n#### convex/index.ts\n```typescript\nimport {\n  query,\n  mutation,\n  internalQuery,\n  internalMutation,\n  internalAction,\n} from \"./_generated/server\";\nimport { v } from \"convex/values\";\nimport OpenAI from \"openai\";\nimport { internal } from \"./_generated/api\";\n\n/**\n * Create a user with a given name.\n */\nexport const createUser = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"users\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"users\", { name: args.name });\n  },\n});\n\n/**\n * Create a channel with a given name.\n */\nexport const createChannel = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"channels\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"channels\", { name: args.name });\n  },\n});\n\n/**\n * List the 10 most recent messages from a channel in descending creation order.\n */\nexport const listMessages = query({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      _id: v.id(\"messages\"),\n      _creationTime: v.number(),\n      channelId: v.id(\"channels\"),\n      authorId: v.optional(v.id(\"users\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n    return messages;\n  },\n});\n\n/**\n * Send a message to a channel and schedule a response from the AI.\n */\nexport const sendMessage = mutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    authorId: v.id(\"users\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const user = await ctx.db.get(args.authorId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      authorId: args.authorId,\n      content: args.content,\n    });\n    await ctx.scheduler.runAfter(0, internal.index.generateResponse, {\n      channelId: args.channelId,\n    });\n    return null;\n  },\n});\n\nconst openai = new OpenAI();\n\nexport const generateResponse = internalAction({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const context = await ctx.runQuery(internal.index.loadContext, {\n      channelId: args.channelId,\n    });\n    const response = await openai.chat.completions.create({\n      model: \"gpt-4o\",\n      messages: context,\n    });\n    const content = response.choices[0].message.content;\n    if (!content) {\n      throw new Error(\"No content in response\");\n    }\n    await ctx.runMutation(internal.index.writeAgentResponse, {\n      channelId: args.channelId,\n      content,\n    });\n    return null;\n  },\n});\n\nexport const loadContext = internalQuery({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      role: v.union(v.literal(\"user\"), v.literal(\"assistant\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n\n    const result = [];\n    for (const message of messages) {\n      if (message.authorId) {\n        const user = await ctx.db.get(message.authorId);\n        if (!user) {\n          throw new Error(\"User not found\");\n        }\n        result.push({\n          role: \"user\" as const,\n          content: `${user.name}: ${message.content}`,\n        });\n      } else {\n        result.push({ role: \"assistant\" as const, content: message.content });\n      }\n    }\n    return result;\n  },\n});\n\nexport const writeAgentResponse = internalMutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      content: args.content,\n    });\n    return null;\n  },\n});\n```\n\n#### convex/schema.ts\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n  channels: defineTable({\n    name: v.string(),\n  }),\n\n  users: defineTable({\n    name: v.string(),\n  }),\n\n  messages: defineTable({\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }).index(\"by_channel\", [\"channelId\"]),\n});\n```\n\n#### convex/tsconfig.json\n```typescript\n{\n  /* This TypeScript project config describes the environment that\n   * Convex functions run in and is used to typecheck them.\n   * You can modify it, but some settings required to use Convex.\n   */\n  \"compilerOptions\": {\n    /* These settings are not required by Convex and can be modified. */\n    \"allowJs\": true,\n    \"strict\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"jsx\": \"react-jsx\",\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n\n    /* These compiler options are required by Convex */\n    \"target\": \"ESNext\",\n    \"lib\": [\"ES2021\", \"dom\"],\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*\"],\n  \"exclude\": [\"./_generated\"]\n}\n```\n\n#### src/App.tsx\n```typescript\nexport default function App() {\n  return <div>Hello World</div>;\n}\n```\n","packages/1-prisma-cloud/2-shared-modules/auth/README.md":"# @internal/auth\n\nSignup, login, sessions, and JWT verification as a composed module wrapping\n[Better Auth](https://better-auth.com) (in-process TypeScript library — not a\nremote IdP), published as `@prisma/composer-prisma-cloud/auth`. One dedicated\nCompute service; the schema ships as a Prisma ORM extension pack; the\ninstance secret is platform-minted.\n\n## Contract scope\n\nThree ports, one service behind them — least privilege is a WIRING choice:\n\n- **`api`** (a raw HTTP port, `rawHttpContract` from `@prisma/composer/http`)\n  — the public Better Auth surface\n  (`/api/auth/*`): signup, login, logout, self-service account deletion,\n  JWKS, token minting. Publicly reachable, with no service key (unlike the\n  rpc ports) — it IS the authentication: Better Auth authenticates each\n  request itself (logout and account deletion need a signed-in session)\n  and rate limits it. Two consumer dependencies bind to it:\n  - `rawHttp()` from `@prisma/composer/http` → `{ url, fetch }` — what\n    `authProxy()` consumes. Any raw HTTP slot accepts this port, so a test\n    double or another auth server can fill the same slot.\n  - `jwtVerifier()` → `verify(token)` — stateless JWT verification over the\n    instance's JWKS (jose remote JWKS, 30 s clock tolerance). Resolves\n    `null` for ANY invalid token content; throws only on operational\n    errors (JWKS unreachable). No DB access — that is its whole value.\n- **`session`** (rpc) — consumer-facing online checks: `getSession(token)`\n  (null for unknown/expired/banned-owner — one shape, no error; a revoked\n  session is a deleted row, so this is the instant-logout read) and\n  `getUser(id)` (profile rendering off a JWT `sub` without admin wiring).\n- **`admin`** (rpc) — the tier-1 admin path: `findUser` (exactly one of\n  id/email; email match case-insensitive), `listUsers` (query/banned\n  filters, keyset cursor), `listSessions`, `revokeSession`,\n  `revokeUserSessions` (idempotent deletes), `banUser` (ban implies\n  revoke, atomically), `unbanUser`, `createUser` (see Provisioning\n  accounts below), `setEmailVerified`, `removeUser` (see Deleting\n  accounts below).\n\nWire each port only where it belongs: the app gets `api` + `session`; the\nback office alone gets `admin`.\n\n`/api/auth/*` is the browser surface. Better Auth origin-checks any request\nthat looks like it came from a browser — one carrying a cookie, an\n`Origin`/`Referer`, or any `Sec-Fetch-*` header — and refuses a missing\n`Origin` with `403 MISSING_OR_NULL_ORIGIN`. Node's built-in `fetch` sends\n`Sec-Fetch-Mode` on every request, so a Node script calling `/api/auth/*`\n(directly or through `authProxy`) is refused unless it sends an `Origin`\nthat is in `trustedOrigins` (the module's `baseUrl`). Server-to-server work\nbelongs on the rpc ports instead.\n\n## Golden-path wiring\n\n```ts\n// module.ts (the root)\nimport { appRoot, resolve } from '@prisma/composer';\nimport { serviceOrigin } from '@prisma/composer-prisma-cloud';\nimport { auth } from '@prisma/composer-prisma-cloud/auth';\nimport { postgres } from '@prisma/composer-prisma-cloud/orm';\nimport { appContract } from './src/contract.ts';\nimport apiService from './src/api/service.ts';\n\nexport default appRoot('app', ({ environment, provision }) => {\n  const db = provision(\n    postgres({\n      name: 'database',\n      contract: appContract,\n      config: './prisma.config.ts',\n      targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n    }),\n    { id: 'database' },\n  );\n  const identity = provision(auth(), {\n    id: 'auth',\n    deps: { db },\n    input: { baseUrl: serviceOrigin('app.api') }, // the PUBLIC app origin\n  });\n  provision(apiService, {\n    id: 'api',\n    deps: { authApi: identity.api, verifier: identity.api, session: identity.session },\n  });\n});\n```\n\nEvery deploy migrates the database to its `targetRef`. Here `prisma dev` migrates to the contract the commit emits, and a deploy to the environment `production` migrates to the ref `migrations/app/refs/production.json`, which you commit after planning a migration: `prisma migration ref set production <newest migration directory>`.\n\n```ts\n// src/api/service.ts: the app service declares its three dependencies\nimport { rawHttp } from '@prisma/composer/http';\nimport { rpc } from '@prisma/composer/service-rpc';\nimport { authSessionContract, jwtVerifier } from '@prisma/composer-prisma-cloud/auth';\n\nexport default compute({\n  name: 'api',\n  deps: { authApi: rawHttp(), verifier: jwtVerifier(), session: rpc(authSessionContract) },\n  build: node({ module: import.meta.url, entry: 'server.js' }),\n});\n```\n\n```ts\n// in the app service: first-party cookies via the proxy (the browser golden path)\nimport { authProxy } from '@prisma/composer-prisma-cloud/auth';\n\nconst { authApi, verifier } = service.load();\nconst proxy = authProxy(authApi);\n// route /api/auth/* → proxy(request); verify API calls with verifier.verify(<bearer>)\n```\n\nThe database is a BOUNDARY dependency: the root decides dedicated vs shared. `baseUrl` is the public origin browsers see (scheme+host, no trailing slash, no path) — bind it with `serviceOrigin('<app>.<service>')`, the service's full address, so each environment trusts its own URL, or a field of the root's input, such as `input.AUTH_BASE_URL`, for a custom domain. The instance secret is platform-minted inside the module; rotation is unsupported in v1 (rotating would invalidate every session and the encrypted jwks rows).\n\nA complete, deployable copy of this wiring lives in `examples/auth`.\n\n## Provisioning accounts\n\nAn account an operator creates goes through the `admin` port, server to\nserver — never through the browser sign-up surface:\n\n```ts\n// in a service wired to `identity.admin`\nconst { admin } = service.load();\nconst { user } = await admin.createUser({\n  email: 'ops@example.com',\n  name: 'Ops',\n  password: 'a-long-passphrase',   // optional; omit for a magic-link-only account\n  emailVerified: true,             // optional; default false\n});\n```\n\n`createUser` writes exactly what Better Auth's own sign-up writes — the\n`user` row and, with a password, a `credential` account hashed by Better\nAuth's own hasher — and sends no mail. The contract input applies the same\nchecks sign-up does (a well-formed email, a password of 8–128 characters),\nso a caller mistake is a 400 at the rpc boundary; a duplicate email\n(case-insensitive) is refused by the handler. Every refusal reaches a typed\nrpc client as a thrown error, so a script cannot mistake it for success. `setEmailVerified({ userId, emailVerified })` flips\nthe flag a created account needs before `requireEmailVerification` lets it\nsign in (`user: null` for an unknown id).\n\nA deployed stack's rpc ports are reachable only by consumers in its graph:\na script on a laptop cannot call `admin.createUser`. The application\nexposes its own operator route (allowlisted however it sees fit) from a\nservice wired to `admin`, and that route makes the call.\n\nInvite-only applications close self-service sign-up with a module setting,\nenforced by Better Auth itself, instead of filtering their proxy:\n\n```ts\nprovision(auth({ signUp: 'closed' }), { id: 'auth', deps: { db, email: mail.send }, input: { baseUrl: … } });\n```\n\n`signUp: 'closed'` sets `emailAndPassword.disableSignUp` and the magic-link\nplugin's `disableSignUp`: `/api/auth/sign-up/email` answers `400\nEMAIL_PASSWORD_SIGN_UP_DISABLED`, and a magic link requested for an unknown\nemail is still sent but completes to an `error=new_user_signup_disabled`\nredirect with no user created. Sign-in for existing accounts is unchanged.\nDefault `'open'`. Nothing about origin, CSRF, or `trustedOrigins` changes\neither way.\n\n## Deleting accounts\n\nA signed-in user deletes their own account through Better Auth's\n`POST /api/auth/delete-user`, reached through `authProxy()` like the rest\nof `/api/auth/*`:\n\n```ts\n// browser, signed in (cookie through the proxy)\nawait fetch('/api/auth/delete-user', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json' },\n  body: JSON.stringify({ password }), // optional when the session is < 24 h old\n});\n```\n\nIt needs a signed-in session (`401` otherwise), deletes only that\nsession's user (there is no `userId` parameter), and demands the current\n`password` (`400 INVALID_PASSWORD`) or a session younger than 24 hours\n(`400 SESSION_EXPIRED` — sign in again; magic-link users have no password).\n\nAn operator deletes an account through the `admin` port, server to server\n— this module's database-direct rpc, not Better Auth's admin-session API:\n\n```ts\n// in a service wired to `identity.admin`\nconst { removed } = await admin.removeUser({ userId });\n```\n\n`removed: false` means no such user, so a retried deletion is not an\nerror. No mail is sent.\n\nBoth paths delete the `user` row, its sessions, and its accounts. Pending\nverification tokens are left to expire: an unused magic link (the email,\n5 minutes) or reset (the user id, 1 hour); Better Auth deletes expired\ntokens the next time it checks any token. Your own rows follow your foreign\nkey onto `auth:User`: `onDelete: Cascade` deletes them with the user,\n`Restrict` refuses the deletion, and without an FK nothing links them.\nData outside the database (uploaded files, other stores) needs your own\ncleanup first — route that deletion through your service and\n`removeUser`. Already-minted JWTs keep verifying until they expire\n(≤ 15 min, see Sessions & JWTs); `session.getSession(token)` is `null`\nimmediately.\n\n## The pack\n\nBetter Auth's tables (`user`, `session`, `account`, `verification`, `jwks` —\nPostgres schema `auth`) ship as a Prisma ORM extension pack with authored\nmigrations — Better Auth's own migrator never runs anywhere. Consumers:\n\n```ts\n// prisma.config.ts\nimport authPack from '@prisma/composer-prisma-cloud/auth/pack';\nexport default defineConfig({ ..., extensions: [authPack] });\n```\n\nRun `prisma migration plan` once — it materialises the pack's shipped\nmigrations into `migrations/auth/` — and deploy: the ONE migration step\ncreates and evolves the auth tables beside your own, marker-signed per\nspace. On a shared database your own contract can FK `auth:User`\n(cross-space relations are non-navigable in the generated client; the value\nis the real constraint):\n\n```prisma\nmodel Profile {\n  id     String @id\n  userId String @unique\n  user   auth:User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n```\n\nUpgrade procedure: bump this package → `prisma migration plan` (the new\nshipped migrations materialise) → deploy. The deploy preflight fails loudly\nwhen a wired database's config is missing the pack or is at a stale head.\nA version whose section below says otherwise needs those steps instead.\n\n### Upgrading to a required `targetRef`\n\nThe app's database now needs `targetRef`, and every deploy runs the ORM's migrate to it, for the auth pack's contract space as for the app's. Add `targetRef` to the app's `postgres({ ... })` as shown above, commit a ref per environment you deploy with `prisma migration ref set <environment> <newest migration directory>` (run where the app's `prisma.config.ts` is), and remove any placeholder `db: { connection: … }` from that `prisma.config.ts`. The auth pack's own space always migrates to its shipped head.\n\n### Upgrading to Prisma ORM 8.0.0-rc.26\n\nPrisma ORM 8.0.0-rc.26 computes every contract hash in a new way, so the auth pack's storage hash moves from `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d` to `cb2e6cac77e993f93581b354f39af672267ae9c5888a156e68c00bb9087f769e`. The tables do not change. Follow [Upgrading to Prisma ORM's new contract hashes](../../../../docs/guides/deploying.md#upgrading-to-prisma-orms-new-contract-hashes): its script rewrites your copy of the auth pack's migrations in `migrations/auth/` with your own, and `prisma db sign` signs the auth pack's space with your app's.\n\nA database that only `startLocalAuthServer` uses, such as one your tests create, has no project to run `prisma db sign` from. Point the server at a fresh database instead: on a database it set up under an earlier version, it now stops with the ORM's `CONTRACT.PRISMA_SPACE_BEHIND` and changes nothing.\n\n### Upgrading to Composer 0.34.0\n\nComposer 0.34.0 moves to Prisma ORM 8.0.0-rc.20. The auth pack's contract no longer stores its `Tstz` type alias: each column stores its own type. The tables do not change, but the auth pack's storage hash does, from `0df0ef0989ec3dd95124dde6303fbe0572bbab08bebf00abff6a7955cadd786e` to `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d`. Your app keeps its own copy of the auth pack's migrations (`migrations/auth/` and the snapshot in `migrations/snapshots/0df0ef…/`), and Prisma ORM rc.20 refuses to load that snapshot as it is. Every database's marker also still holds the old hash. Until you follow these steps, `prisma deploy` and `prisma dev` fail at the migration step: first with `Contract-space contract validation failed for \"auth\"`, and after the script in step 3 with an error that the database is at a contract no migration of contract space `\"auth\"` reaches.\n\n1. Commit your work, so the changes below can be reviewed and undone with git.\n2. Upgrade `@prisma/composer`, `@prisma/composer-cli` and `@prisma/composer-prisma-cloud` to 0.34.0, `@prisma/orm-postgres` to 8.0.0-rc.20, and `prisma` to 8.0.0-rc.26 or later. An earlier `prisma` cannot read an rc.20 contract, so `contract emit` and `db sign` fail with `Cannot use 'in' operator to search for 'kind' in typeAlias`.\n3. From the app's root, copy the Prisma skills into the project and run the ORM's type-alias script. Node does not run a TypeScript file from inside `node_modules`, which is why the script runs from the copy:\n\n   ```sh\n   prisma skills sync\n   node .agents/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts\n   ```\n\n   It renames `migrations/snapshots/0df0ef…/` to `migrations/snapshots/24a0762…/` and rewrites `migrations/auth/0001_init/migration.json` and `migrations/auth/refs/head.json`. It prints `0df0ef… -> 24a0762…`.\n4. Run `prisma contract emit`. For an app whose own contract has no type aliases, this only moves the version stamps in `contract.json` and `contract.d.ts`.\n5. Run `prisma db sign --db <url>` against every database of the app: production, each other environment and the local dev database. The database does not change; only its marker moves to the new hash. It prints `auth: signed 24a0762… (was 0df0ef…)`.\n   - **Deployed environments.** A deploy never prints a connection string. Copy each database's connection string from the Prisma Console: the app's Project for production, and the Branch named after the environment for any other environment.\n   - **The local dev database.** It must be running: `prisma db sign --db \"$(prisma dev url database)\"`, where `database` is your auth database's node address. A `prisma dev` that fails stops the app, and `prisma dev url` reports only a running database, so sign before you run `prisma dev` on the new version. A `prisma dev --detach` started before the upgrade keeps the database running. If the database is already stopped, start over with `prisma dev --fresh`, which deletes the local data.\n6. Deploy and run `prisma dev` as usual.\n\nThe script also gives the rewritten `0001_init` migration a new hash, and each database's migration history keeps the old one. So `prisma migration status` no longer shows the auth pack's earlier migrations as applied, although it still reports the database as up to date. `prisma db migrate` does not run them again.\n\n## Sessions & JWTs\n\nStateless JWTs by default: 15-minute TTL, EdDSA via the instance's JWKS at\n`/api/auth/jwks`. Verified claims: `sub` (userId), `sid` (sessionId),\n`email`, `emailVerified`, `exp`. Cookie sessions last 7 days (rolling,\nrefreshed daily).\n\nThe trade-off is explicit: a revoked/banned session's already-minted JWTs\nkeep verifying until they expire (≤ 15 min). A route that needs instant\nlogout opts in per call with `session.getSession(token)` — a revoked\nsession is a deleted row. `iss`/`aud` are not validated in v1: the verifier\nonly trusts keys fetched from the wired instance, and instances never share\nkeys.\n\n## Local dev\n\n```ts\nimport { startLocalAuthServer } from '@prisma/composer-prisma-cloud/auth/testing';\n\nconst server = await startLocalAuthServer({ databaseUrl }); // e.g. `prisma dev`\n// server.url            → real Better Auth + the real port handlers\n// server.capturedEmails → { template, to, url } per send — read your\n//                          verification / magic links straight from here\n```\n\nReal Better Auth, the real handlers, the same fetch topology as production; the pack's schema applies idempotently at boot; a fixed dev secret; rpc runs keyless. No cloud credentials anywhere.\n\nThe helper applies the schema with the Prisma ORM your app installs (`@prisma/orm-postgres`, a required peer, and `@prisma/orm-toolchain`, which Composer depends on). It carries no copy of its own.\n\n## Email flows\n\nVerification, password reset, and magic-link emails deliver through the\n[email module](../email/README.md), wired as a boundary dependency:\n\n```ts\nconst mail = provision(email(), { id: 'mail', input: { /* deliveryMode, from, deliveryCredential */ } });\nconst identity = provision(auth(), {\n  id: 'auth',\n  deps: { db, email: mail.send },\n  input: { baseUrl: serviceOrigin('shop.web') },\n});\n```\n\nSignup requires verification (`requireEmailVerification: true`; the\nverification send fires on signup, and verifying auto-signs-in; an\n`admin.createUser` account skips the mail and is verified when created\nwith `emailVerified: true`). Magic links expire after 5 minutes. The three templates ship with the module —\nminimal semantic HTML plus a plain-text part; every interpolation is\nHTML-escaped, and a link whose origin differs from `baseUrl` fails the\nsend rather than going out.\n\nDelivery is fire-and-forget from auth's perspective: a failed send is\nlogged, never thrown (a down mail path must not brick signup), and each\nsend carries a deterministic idempotency key, so Better Auth retries\ncan't double-deliver. The email module's outbox is the operational\nrecord — read delivery state back through its `outbox` port.\n\nLocally, `startLocalAuthServer` captures sends in `capturedEmails` by\ndefault, or accepts an `email` sender hydrated against the email module's\nown local server so the outbox-readback path is the one production uses.\n`examples/auth` runs the full loop both ways: signup → verification link\nread back from the outbox → verify → login → magic link.\n\n## Embedded mode\n\nArrives with slice S4: `createEmbeddedAuth()` (`./embedded`) — the same\n`buildAuthOptions()` mounted in your own service, for the fully-in-process\nshape.\n\n## The SPA alternative\n\nDocumented fully in S2 alongside the browser flows: talk to the `api` port's\norigin directly with `Authorization: Bearer` (the bearer plugin is enabled),\nat the cost of the first-party-cookie golden path.\n\n## Limits (v1)\n\nNo social providers (mechanism reserved, none ship) · no organizations /\n2FA / passkeys / username / phone · no secret rotation · no impersonation · admin web UI is tier 2+ (the `admin` port is tier 1) ·\nrpc bodies cap at 1 MiB.\n","packages/1-prisma-cloud/2-shared-modules/email/README.md":"# `@prisma/composer-prisma-cloud/email`\n\nTransactional email as a Prisma Composer module. It is an ordinary module: a\nCompute service backed by a module-provisioned Prisma Postgres (every email is\nstored first, then delivery is attempted — the outbox), exposing two\nindependent ports: `send` (deliver a rendered email) and `outbox` (query every\nemail the module has handled). Templates are declared and rendered\n**consumer-side**; the wire carries only rendered mail.\n\nShips as the `@prisma/composer-prisma-cloud/email` subpath (like `/storage`\nand `/cron`).\n\n## Contract scope\n\nTwo ports, three ops:\n\n| Port | Op | Notes |\n| --- | --- | --- |\n| `send` | `send` | `{ templateId, to, cc?, bcc?, replyTo?, subject, html, text?, idempotencyKey }` → `{ id, status, error? }`. `to` 1–50 entries; `idempotencyKey` 1–256 chars. |\n| `outbox` | `getEmail` | `{ id }` → `{ email }` (`null` for an unknown id — never an error). |\n| `outbox` | `listEmails` | Optional `to`/`templateId`/`status`/`cursor`/`limit` filters (AND-combined; `to` matches any recipient) → `{ emails, nextCursor? }`, newest-first, keyset-paginated. `limit` 1–200, default 50. |\n\n`status` is one of `stored` (mode `none`), `queued` (real modes, transient),\n`sent`, `failed`. `send` never throws for a delivery failure — failure is\ndata (`status: 'failed'`, `error` set); it throws only for transport,\nvalidation, or database errors.\n\n`from` is not part of `send`'s input — the sender address is module config\n(one per module instance); a template cannot override it.\n\n## Envelope\n\n**No attachments** in v1. service-rpc request/response bodies cap at **1\nMiB**, so a rendered email (subject + html + text) must fit inside that.\n**Retention: none** — every sent email's full body is stored, unredacted,\nforever (no expiry, no deletion, no redaction). Do not put anything in a\ntemplate you would not want to live in the database indefinitely.\n\n## Wiring\n\nProvision `email()` in a module and declare template-typed dependencies on\nits two ports:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { email, emailDeliveryModes } from '@prisma/composer-prisma-cloud/email';\nimport { variable } from '@prisma/composer-prisma-cloud';\nimport { type } from 'arktype';\n\nexport default appRoot(\n  'app',\n  {\n    input: type({\n      EMAIL_DELIVERY_MODE: type.enumerated(...emailDeliveryModes),\n      EMAIL_FROM: 'string',\n    }),\n  },\n  ({ input, provision }) => {\n    const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));\n    const mail = provision(email(), {\n      id: 'email',\n      input: {\n        deliveryMode: input.EMAIL_DELIVERY_MODE,\n        from: input.EMAIL_FROM,\n        deliveryCredential,\n      },\n    });\n    provision(appService, { deps: { email: mail.send } });\n    provision(adminService, { deps: { outbox: mail.outbox } });\n  },\n);\n```\n\n```ts\n// consumer service — templates declare the client's shape. Interpolated\n// values are HTML-escaped before going into markup — `render` runs on\n// whatever data the caller supplies, so treat it as untrusted the same way\n// you would any other template.\nimport { defineTemplates, emailSender } from '@prisma/composer-prisma-cloud/email';\nimport { type } from 'arktype';\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#39;');\n}\n\nconst templates = defineTemplates({\n  verification: {\n    data: type({ link: 'string' }),\n    render: ({ link }) => ({\n      subject: 'Verify your email',\n      html: `<p><a href=\"${escapeHtml(link)}\">Verify</a></p>`,\n      text: `Verify: ${link}`,\n    }),\n  },\n});\n\nexport default compute({ deps: { email: emailSender(templates) }, /* … */ });\n```\n\n```ts\n// consumer server\nconst { email } = service.load();\nawait email.verification({ to: user.email, data: { link } });\n```\n\nThe outbox port needs no custom factory — declare `deps: { outbox:\nrpc(emailOutboxContract) }` and get the generated client directly.\n\n## Using react-email\n\n`render` may be synchronous or async — the sender method awaits either.\nThis module neither depends on nor imports react-email; a template's\n`render` just calls react-email's own `render()` and returns its result:\n\n```tsx\n// emails/welcome.tsx — a plain react-email component\nimport { Body, Container, Html, Text } from '@react-email/components';\n\nexport function WelcomeEmail({ name }: { name: string }) {\n  return (\n    <Html lang=\"en\">\n      <Body>\n        <Container>\n          <Text>Welcome, {name}!</Text>\n        </Container>\n      </Body>\n    </Html>\n  );\n}\n```\n\n```tsx\n// templates.tsx\nimport { render } from '@react-email/render';\nimport { WelcomeEmail } from './emails/welcome.tsx';\n\nconst templates = defineTemplates({\n  welcome: {\n    data: type({ name: 'string' }),\n    render: async ({ name }) => ({\n      subject: `Welcome, ${name}!`,\n      html: await render(<WelcomeEmail name={name} />),\n      text: await render(<WelcomeEmail name={name} />, { plainText: true }),\n    }),\n  },\n});\n```\n\nJSX interpolation (`{name}` above) escapes automatically — React escapes\ntext children by construction, so a react-email template needs no manual\n`escapeHtml` the way a plain-function template does. See\n[`examples/email`](../../../../examples/email)'s `welcome` template for\nthe full worked version, alongside `verification` as a plain function —\nboth authoring styles side by side.\n\nOne deploy caveat: `prisma deploy` loads your module graph with\nNode's own loader, which cannot transform JSX — a `.tsx` file imported by\nyour topology fails with `Unknown file extension \".tsx\"`. Precompile the\ntemplates file in your app's own build and import the compiled output, as\n[`examples/email/scripts/build.ts`](../../../../examples/email/scripts/build.ts)\ndoes (see the matching `gotchas.md` entry).\n\n## Values per environment\n\n`deliveryMode`, `from` and `deliveryCredential` are the module's `input`. `deliveryMode` is `resend`, `smtp` or `none`, exported as `emailDeliveryModes` (and the type `EmailDeliveryMode`): bind it to one of those literals, or to a field of your root's input declared from `emailDeliveryModes`, as above, so the root's schema checks it before anything is created. With Zod, declare the field as `z.enum(emailDeliveryModes)`. A plain platform variable may hold any text, so binding its value to `deliveryMode` fails to compile. Bind `from` to a literal, a field of your root's input or the value of a `variable(...)` node, so it can vary per environment. `deliveryCredential` is a `secretString()` field: bind it to the value of a `variable.secret(...)` node the app root provisions. `deliveryMode` and `from` are wrapped fields (`field()`), so a module that passes its own wrapped field of the same type on can bind them too. `deliveryUrl` is a factory option (`email({ deliveryUrl })`), static per app: it defaults to `https://api.resend.com` and follows the mode.\n\nIn the sample above, `EMAIL_DELIVERY_MODE` and `EMAIL_FROM` are root input fields: set them in the shell that runs the deploy. `EMAIL_DELIVERY_CREDENTIAL` is a platform secret: set it on the platform with `prisma project env add`.\n\n| Name | Where it is set | Production | Preview |\n| --- | --- | --- | --- |\n| `EMAIL_DELIVERY_MODE` | the deploy shell | `resend` (or `smtp`) | `none` |\n| `EMAIL_FROM` | the deploy shell | `noreply@myapp.com` | anything (unused when `none`) |\n| `EMAIL_DELIVERY_CREDENTIAL` | the platform | Resend API key / SMTP password | any non-empty value, which preflight requires even though the service never reads it |\n\nPreview needs a credential because the email service's input schema requires it in every mode, so an environment that never delivers still sets a non-empty value. A schema can make a secret field optional (ADR-0042); this one does not. `gotchas.md` records this.\n\n## Delivery policy\n\nShared by both real backings (`resend`, `smtp`):\n\n- Per-attempt timeout: **10 s**.\n- Up to **3 attempts** (1 initial + 2 retries), delayed **500 ms then\n  2000 ms** between them (no jitter).\n- Retryable: thrown/network errors, HTTP 429, HTTP 5xx (Resend); SMTP\n  connection errors and response codes 421/450/451/452.\n- Not retryable (fails immediately): any other Resend 4xx (including 409\n  idempotency conflicts — those should be unreachable given the outbox's\n  own row-level dedup; if one surfaces, it is not masked); any other SMTP\n  response code, including permanent 5xx rejections.\n- The outbox row's `attempts` accumulates the count each delivery\n  invocation actually made (1–3 under the policy above) — a future\n  redelivery from the outbox adds its own tries to the running total.\n- Stored `error` string: `` resend <status> <name>: <message> `` (Resend,\n  parsed from its error body; falls back to the raw response text if\n  unparseable) or `` smtp <responseCode>: <message> `` (SMTP protocol\n  rejection). A connection-level failure (no response code) stores the raw\n  error message with no prefix, for either backing.\n\n**SMTP: \"accepted\" is not \"delivered\".** `status: 'sent'` for an SMTP send\nmeans the relay accepted the message for submission — nothing more. SMTP\ngives no delivery confirmation; `providerMessageId` is nodemailer's\n`info.messageId` (or `null`).\n\n**SMTP: a timeout retry can duplicate a send.** The per-attempt timeout\nonly stops the module from waiting on a slow relay — it does not cancel\nthe in-flight SMTP transaction. If the timeout fires, the shared policy\nretries; a slow relay can still accept the first attempt's message after\nthe retry has already started, delivering the same email twice. This is a\ndeliberate retry-semantics tradeoff (at-least-once, not exactly-once) and\nstays as pinned — the only fix that removes the possibility is not\nretrying on timeout, which would trade a rare duplicate for a more common\nfalse failure on a merely slow relay.\n\n## Idempotency\n\n`idempotencyKey` is required on every `send` call and must be **unique per\nlogical send**. A repeated key returns the original row — status, id, and\nall — with no new delivery attempt, even if the payload differs. This is a\ndurable, row-level guarantee (a unique constraint on `idempotency_key`),\nindependent of and stronger than service-rpc's own in-memory replay cache.\n\n`emailSender`'s per-template methods make `idempotencyKey` optional: omit\nit and a fresh UUID is minted on every call, so that call gets no dedup\nprotection against its own retries. If your own retry logic re-invokes a\nsend method after a transient failure, capture the key from the first\nattempt and pass it explicitly on the retry — the module does not\nremember it for you.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/email/testing` boots the same handler map\nover an in-memory store, `deliveryMode: 'none'`, loopback only, no auth —\nno cloud credentials, no Postgres:\n\n```ts\nimport { startLocalEmailServer } from '@prisma/composer-prisma-cloud/email/testing';\n\nconst server = await startLocalEmailServer(); // ephemeral port by default\n// server.url — point emailSender()/rpc(emailOutboxContract) clients at it.\nawait server.stop();\n```\n\n[`examples/email`](../../../../examples/email) is the worked example: a\n`mailer` app wired to `email()`, tested locally against this stand-in with\nno cloud credentials, and deployed to Prisma Cloud in `none` mode as the\nsmoke test.\n\nTests that exercise the real Resend/SMTP backings point `deliveryUrl` at a\nlocal fake instead of the real provider — a `Bun.serve` fake HTTP endpoint\nfor Resend, a minimal loopback SMTP responder for SMTP (see\n`delivery-resend.test.ts`/`delivery-smtp.test.ts`).\n\n## Manual resend check (not run in CI)\n\nA one-off, by-hand verification that a real send actually delivers — not\npart of the test suite or the deploy smoke, since it needs a real Resend\naccount:\n\n1. Set the environment's `EMAIL_DELIVERY_MODE` to `resend`, `EMAIL_FROM` to an\n   address on a domain verified with Resend, and `EMAIL_DELIVERY_CREDENTIAL`\n   to a real Resend API key.\n2. Send one template to a real inbox you control.\n3. Confirm the message arrives, and that the outbox row for it reads\n   `status: 'sent'` with a non-null `providerMessageId`.\n\n## Non-goals (v1)\n\nAttachments, cc/bcc size limits beyond the contract's, per-send `from`\noverride, batch/scheduled send, Resend webhooks, delivery-status polling,\nopen/click tracking, queue-backed async delivery (the outbox is the seam\nfor a later relay — no contract change needed), retention/redaction/\ndeletion, and an admin UI. react-email is not a dependency of this module\n— see \"Using react-email\" above for how a consumer wires it in.\n","packages/1-prisma-cloud/2-shared-modules/storage/README.md":"# `@prisma/composer-prisma-cloud/storage`\n\nS3-compatible object storage as a Prisma Composer module. It is an ordinary\nmodule: a Compute service that speaks the **S3 wire protocol**, backed by a\nmodule-provisioned Prisma Postgres (objects live in a single `bytea` column),\nwith SigV4 credentials minted at deploy. Consumers wire the module's `store`\nport into an `s3()` slot and get an `S3Config` binding; they build their own\nS3 client (aws-sdk, or a hand-rolled SigV4 client) from it.\n\nShips as the `@prisma/composer-prisma-cloud/storage` subpath (like `/cron`).\n\n## Contract scope\n\nThe contract **is** the S3 wire protocol — but only the subset a real consumer\nneeds, not S3-compatibility maximalism. In scope:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /{bucket}/{key}` | `content-type` optional; returns a quoted SHA-256 ETag (opaque to consumers) |\n| `GET /{bucket}/{key}` | optional `Range: bytes=a-b` (inclusive end; open end `a-`) → `206`; missing → `404` |\n| `HEAD /{bucket}/{key}` | `etag` + `content-length`; missing → `404` |\n| `DELETE /{bucket}/{key}` | idempotent (a missing key is success) |\n| `GET /{bucket}?list-type=2` | `prefix`, `continuation-token`, `max-keys` (default 1000); ListObjectsV2 XML |\n| Presigned GET/PUT | query-param SigV4, expiry enforced |\n\nAuth is SigV4 (`AWS4-HMAC-SHA256`), **path-style addressing only**, any region\nstring (`auto` is fine). Bucket names simply namespace keys — there is no\nbucket CRUD.\n\n**Out of scope**: multipart upload, `CopyObject`, batch `DeleteObjects`,\nconditional requests, flexible checksums / `aws-chunked` framing (rejected with\n`501` — see the wiring note below), bucket CRUD, ACLs, versioning, lifecycle.\n\nSee [`CONTRACT-SCOPE.md`](./CONTRACT-SCOPE.md) for the full op semantics and the\nexact out-of-scope list.\n\n## Envelope\n\nObjects up to **~16 MiB**. Each object is one row's `bytea` value; ranged reads\nuse SQL `substring(...)` so a range request never loads the whole object. This\nis comfortably within Postgres `bytea`/TOAST for the target workload — it is\n**not** a general-purpose large-blob store, and larger objects are unsupported.\n\n## Wiring\n\nProvision `storage()` in a module and wire its `store` port into a consumer's\n`s3()` slot:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport blobs from './src/blobs/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage()); // owns its Postgres + minted credentials\n  provision(blobs, { deps: { store: store.store } });\n});\n```\n\n```ts\n// src/blobs/service.ts — the consumer declares an s3() dependency\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { s3 } from '@prisma/composer-prisma-cloud/storage';\n\nexport default compute({\n  name: 'blobs',\n  deps: { store: s3() },\n  build: node({ module: import.meta.url, entry: '../../dist/blobs/server.mjs' }),\n});\n```\n\n```ts\n// src/blobs/server.ts — the consumer's entry builds its own client (ADR-0015)\nimport { S3Client } from '@aws-sdk/client-s3';\nimport service from './service.ts';\n\nconst { store } = service.load(); // S3Config: { url, bucket, accessKeyId, secretAccessKey }\n\nconst client = new S3Client({\n  region: 'auto',\n  endpoint: store.url, // path-style; no virtual-host addressing\n  forcePathStyle: true,\n  credentials: { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey },\n  // The store rejects aws-chunked / flexible-checksum PUTs with 501 — send plain\n  // signed payloads.\n  requestChecksumCalculation: 'WHEN_REQUIRED',\n});\n```\n\nThe `S3Config` binding is the whole surface a consumer sees:\n\n```ts\ninterface S3Config {\n  readonly url: string; // the store's endpoint\n  readonly bucket: string;\n  readonly accessKeyId: string;\n  readonly secretAccessKey: string;\n}\n```\n\n[`examples/storage`](../../../../examples/storage) is the worked example — a\nsmall blob store/serve app that consumes `storage()` and deploys to Prisma\nCloud.\n\n## Local development\n\nThe same module runs locally against local Postgres — no cloud, no minted\ncredentials. `@prisma/composer-prisma-cloud/storage/testing` exposes the store\nand server directly:\n\n```ts\nimport { createPgStore, startStorageServer } from '@prisma/composer-prisma-cloud/storage/testing';\n\nconst store = await createPgStore(process.env.DATABASE_URL!); // applies the schema\nconst server = startStorageServer({\n  store,\n  credentials: { accessKeyId: 'local', secretAccessKey: 'local-secret' },\n  bucket: 'my-bucket',\n  port: 0, // ephemeral\n});\n\n// server.url is an S3 endpoint — point an aws-sdk client (path-style) at it.\n// server.stop() when done.\n```\n\nThe module's own tests, and `examples/storage`'s integration test, boot exactly\nthis stand-in over a throwaway Postgres: they honor `STATE_TEST_DATABASE_URL`\nwhen set, otherwise self-spawn an ephemeral Homebrew `postgresql@15` cluster\n(`initdb`/`pg_ctl`); they skip on a dev machine with no Postgres and fail on CI\nif none is available.\n\n## Credentials\n\nThe SigV4 key pair is **minted once at deploy** (a random keypair persisted in\ndeploy state) and delivered to consumers through the `S3Config` binding — it is\nnever printed and never surfaces outside the deployment. Consumers are\ntherefore **in-deployment services** that receive the credentials via `load()`,\nnot arbitrary external clients. An external-access path (reading the minted\ncredentials from outside the deploy) is a recorded platform ask, not something\nthis module solves.\n","packages/1-prisma-cloud/2-shared-modules/streams/README.md":"# `@prisma/composer-prisma-cloud/streams`\n\nDurable append-only event streams as a Prisma Composer module. It wraps the\nproduction `@prisma/streams-server` runtime (npm, unmodified) as a Compute\nservice behind a typed boundary: the module's `store` dependency takes a\n`storage()` module's port as its durable tier, and it exposes a single\n`streams` port. A consumer names the streams it uses with\n`streamsContract(defs)`, and its `durableStreams(contract)` dependency\nhydrates to one ready **`StreamHandle`** per declared name — like RPC's\ngenerated client, no app hand-rolls the protocol, and no app carries a\nstream-lifecycle constant: the handle owns creating the stream on first use\nand healing a 404 by re-creating and retrying once. The wire binding\nunderneath is `{ url, apiKey }`, the key minted by the deploy.\n\nShips as the `@prisma/composer-prisma-cloud/streams` subpath (like `/storage`).\n\n## Contract scope\n\nA contract names its streams:\n\n```ts\nconst jobLog = streamsContract({\n  jobs: streamDef(),   // untyped in this slice — events type as `unknown`\n  audit: streamDef(),\n});\n```\n\nHydration hands a consumer one handle per declared name:\n\n```ts\ninterface StreamHandle {\n  append(event): Promise<void>; // one JSON event; NEVER retried beyond the 404 heal below\n  read<T>(opts?): Promise<{ events: T[]; nextOffset: string }>;\n  tail<T>(opts?): Promise<{ events: T[]; nextOffset: string; timedOut: boolean }>;\n}\n```\n\nNo `create` — a handle creates its stream on first use, memoized, and heals a\n404 (the stream vanished from the durable tier) by dropping that memo,\nre-creating, and retrying the failed operation once. That heal is safe even\nfor an append: a 404 is generated INSTEAD OF a write at every layer, so it\nproves nothing was applied.\n\nFor dynamic stream names (e.g. per-tenant streams), call `durableStreams()`\nwith no contract — the `rawPostgres()` parity, same lifecycle ownership, the\nname is data rather than a wiring-time declaration:\n\n```ts\ninterface StreamsClient {\n  stream(name: string): StreamHandle;\n}\n```\n\nThe wire binding underneath is the typed connection config (ADR-0015) —\n`{ url: string, apiKey: string }` — and the client wraps\n[`@durable-streams/client`](https://www.npmjs.com/package/@durable-streams/client)\n(ElectricSQL's canonical protocol client, pinned to the version\n`@prisma/streams-server` 0.1.11's own repo pairs with). The full protocol\nsurface it drives:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /v1/stream/{name}` | create (idempotent; `content-type` fixes the stream's type) |\n| `POST /v1/stream/{name}` | append a JSON array of events (`stream-closed: true` header closes) |\n| `GET /v1/stream/{name}?offset=…` | read from an offset; `-1` = start; `format=json` |\n| `GET …&live=long-poll&timeout=…` | held read — returns when fresh events arrive or timeout |\n| `GET …&live=sse` | SSE tail (see the deployed live path note below) |\n\nOffsets are **opaque cursors**, not numeric indices: take them from a read's\n`nextOffset` and pass them back verbatim.\n\n**Auth rides the binding.** The bearer key is not an ADR-0029 secret (there\nis no external value to bind) and not a producer output. The `apiKey`\nconnection param declares an [ADR-0031](../../../../docs/design/90-decisions/ADR-0031-provisioned-param-values-are-a-need-resolved-through-a-target-registry.md)\n**provisioning need**: the deploy target mints the value, keeps it stable in\ndeploy state, and fills the param like any other input. Declaring a\n`durableStreams()` dependency is the whole of the wiring — there is no secret\nslot and nothing to bind at the root. Every endpoint, including `/health`,\nrequires `Authorization: Bearer <key>`.\n\nTwo consequences worth knowing:\n\n- **One key per streams module.** The provisioner mints per provider, not per\n  edge, because `@prisma/streams-server` authenticates a single `API_KEY` —\n  every consumer of one `streams()` instance holds the same value. Cardinality\n  is provisioner policy (ADR-0031), so per-edge keys are later a change of\n  that policy plus an accepted-set provider param once the upstream server\n  takes a key set: no resource to add, no core change, nothing here to delete.\n- **No consumers, no key.** The need lives on the consumer's edge, so a\n  `streams()` module nothing depends on never gets a key minted, and its\n  server refuses to boot rather than serve unauthenticated. Wire a consumer,\n  or drop the module.\n\n## Wiring\n\nThe root provisions `storage()` as the durable tier and wires its `store`\nport into `streams()` — the key needs no wiring at all:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport { streams } from '@prisma/composer-prisma-cloud/streams';\nimport worker from './src/worker/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage());\n  const events = provision(streams(), { deps: { store: store.store } });\n  provision(worker, { deps: { streams: events.streams } });\n});\n```\n\n```ts\n// src/worker/service.ts — the consumer. Declaring the dependency is what\n// causes the key to be minted; nothing names it a second time.\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { durableStreams, streamDef, streamsContract } from '@prisma/composer-prisma-cloud/streams';\n\nconst jobLog = streamsContract({ jobs: streamDef() });\n\nexport default compute({\n  name: 'worker',\n  deps: { streams: durableStreams(jobLog) },\n  build: node({ module: import.meta.url, entry: '../../dist/worker/server.mjs' }),\n});\n```\n\n```ts\n// src/worker/server.ts — append, then wait for what follows\nimport service from './service.ts';\n\nconst { streams } = service.load(); // { jobs: StreamHandle }, ready to call\n\nawait streams.jobs.append({ kind: 'created' });\nconst { events, nextOffset } = await streams.jobs.read();\nconst next = await streams.jobs.tail(); // resolves on the next event (or timedOut)\n```\n\nFor local development and tests, build the same client against the stand-in\n(no deployed binding, no auth):\n\n```ts\nimport { StreamsClient } from '@prisma/composer-prisma-cloud/streams';\n\nconst client = new StreamsClient({ url: standIn.url, apiKey: 'unused' });\nconst jobs = client.stream('jobs'); // a StreamHandle, same surface as the hydrated binding\n```\n\n[`examples/streams`](../../../../examples/streams) is the worked example — the\nmodule deployed to Prisma Cloud with `storage()` as its tier and a `jobs`\nservice consuming the binding, plus local integration tests and a deployed\nconsumer smoke script.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/streams/testing` embeds the local stand-in\n(`@prisma/streams-local`): SQLite-only, loopback, **no auth, no object store,\nno cloud credentials** — the same protocol surface.\n\n```ts\nimport { startLocalStreamsServer } from '@prisma/composer-prisma-cloud/streams/testing';\n\nconst server = await startLocalStreamsServer({ name: 'dev', port: 0 });\n// server.exports.http.url is a Durable Streams endpoint (no Authorization needed).\n// await server.close() when done.\n```\n\nThe stand-in persists under `DS_LOCAL_DATA_ROOT`; tests point that at a\nthrowaway directory. The full conformance suite runs against it with no\ncredentials: `pnpm test:conformance:local` (and against a deployment:\n`CONFORMANCE_TEST_URL=… STREAMS_API_KEY=… pnpm test:conformance:deployed`).\n\n## Deployed live path: use long-poll\n\nThe Compute ingress currently buffers HTTP responses until the upstream\nresponse completes. An open `?live=sse` tail therefore never delivers through\na deployment's public URL — the client sees zero bytes and the edge returns a\n504 after ~60s — while the same request works locally and against the\nstand-in. `?live=long-poll` completes per response and delivers live events\nend to end through the ingress, so `StreamHandle.tail` long-polls. The\ndeployed conformance harness keeps the SSE tests, so they flip green when the\nplatform supports streaming responses.\n","skills-contrib/multiline-commit-messages/SKILL.md":"---\nname: multiline-commit-messages\ndescription: >-\n  Use single-quoted strings for multiline git commit messages in the Shell tool.\n  Prevents heredoc escaping failures that produce garbled commit messages.\n---\n\n# Multiline commit messages\n\nThe Shell tool sends commands as a single string. Heredoc syntax (`<<'EOF'`) inside `$(cat ...)` is fragile and can fail silently — the literal `$(cat <<'EOF' ...` ends up as the commit message instead of the intended text.\n\n## Rule\n\nPrefer single-quoted strings with embedded newlines over `$(cat <<'EOF' ...)`:\n\n```bash\ngit commit -s -m 'short summary line\n\nLonger body paragraph explaining why the change exists.\nAdditional context if needed.'\n```\n\n## Why heredocs are fragile\n\nThe Shell tool passes the command as a single string argument. When you write:\n\n```bash\ngit commit -m \"$(cat <<'EOF'\nmessage\nEOF\n)\"\n```\n\nthe `EOF` delimiter, newlines, and nested quoting can interact unpredictably, and the result is the raw `$(cat <<'EOF' ...` text appearing as the commit message.\n\nSingle-quoted strings with literal newlines are simple, portable, and always work. If the message itself must contain a single quote, close and reopen the quote (`'\\''`) or fall back to a temp file passed via `-F`.\n\n## Sign off\n\nEvery commit still needs its `Signed-off-by` trailer — see [git-staging](../../../.cursor/rules/git-staging.mdc). Pass `-s` on the same `git commit` invocation.\n","skills-contrib/publish-npm-version/SKILL.md":"---\nname: publish-npm-version\ndescription: >-\n  Cuts the next minor release of Prisma Composer: bumps the root\n  package.json version, propagates it to every workspace package in lockstep,\n  and opens a PR titled \"chore(release): v<next-version>\". When a maintainer\n  merges the PR, the `Publish to npm` workflow runs automatically and publishes\n  the new version to npm under dist-tag `next`, plus a matching GitHub Release\n  with auto-generated notes; users get it when a maintainer promotes it to\n  `latest`. Use when a maintainer asks to \"cut the next minor\",\n  \"bump to the next version\", \"open a release PR\", or \"prepare a publish PR\".\n---\n\n# Publish next npm version\n\n## Audience\n\nMaintainers who can push branches and open PRs. Invoke this **locally**, not as a\nGitHub Action — a PR opened by a workflow's `GITHUB_TOKEN` does not trigger CI,\nwhich defeats the point of a reviewable release.\n\n## Background reading\n\nRead [`docs/oss/versioning.md`](../../docs/oss/versioning.md) first — it is the\npolicy this skill mechanises: the root-`package.json` source of truth, the\nlockstep guarantee, the dist-tag convention, and the full procedure (this skill\nis the \"open the bump PR\" step; **merging the PR is the publish trigger** — there\nis no separate dispatch step).\n\n## Pre-flight\n\nConfirm you can fetch from `origin` (`git fetch origin main` succeeds). The skill\nworks in a fresh worktree off `origin/main`, so your current worktree is left\nundisturbed.\n\n## Steps\n\n1. **Fresh worktree off `origin/main`:**\n   ```bash\n   git fetch origin main\n   git worktree add -b chore/release-vNEXT ../release-vNEXT origin/main\n   cd ../release-vNEXT\n   pnpm install --frozen-lockfile\n   ```\n2. **Bump.** `pnpm bump-minor` reads the root version at `HEAD`, computes the next\n   minor (`0.2.0` → `0.3.0`), stamps every workspace `package.json` in\n   lockstep (rewriting internal `workspace:` deps to the new version), and\n   regenerates `pnpm-lock.yaml` to match.\n3. **Sanity-check** the bump is clean and complete. The diff must include\n   `pnpm-lock.yaml` — CI installs with `--frozen-lockfile`, so a bump without the\n   lockfile fails every CI job at the install step:\n   ```bash\n   git diff --stat                      # every workspace package.json + pnpm-lock.yaml\n   pnpm check:publish-deps              # no workspace:/catalog: leaks, exact internal pins\n   ```\n4. **Commit** with the release title and dual DCO sign-off, then push and open the PR:\n   ```bash\n   git commit -am \"chore(release): v<version>\"\n   git push -u origin chore/release-vNEXT\n   gh pr create --base main --title \"chore(release): v<version>\" \\\n     --body \"Release v<version>. Merging this triggers the Publish to npm workflow.\"\n   ```\n5. **Hand off.** Tell the maintainer the PR is open and that **merging it** publishes `<version>` to npm under `next` (via OIDC trusted publishing) and cuts a GitHub Release with auto-generated notes. Users get the release only once a maintainer promotes it to `latest` with the `Promote a release to latest` workflow (versioning.md § Promote a release to `latest`). Do not merge it yourself unless asked.\n\n## What this skill does NOT do\n\n- **Patches / old minors.** There are no patch releases of older minors\n  (versioning.md § pre-1.0). This skill only advances the latest minor.\n- **The publish itself.** That is the `Publish to npm` workflow, triggered by the\n  merge — never run `pnpm publish` by hand for a normal release.\n- **Release notes authoring.** The GitHub Release notes are auto-generated\n  (`gh release create --generate-notes`) by the workflow; there is no committed\n  release-notes file to write.\n","skills-contrib/upgrade-alchemy-effect/SKILL.md":"---\nname: upgrade-alchemy-effect\ndescription: >-\n  How to upgrade `alchemy` and the `effect` constellation across this repo and\n  keep them consistent for consumers: which packages pin what, why `effect` and\n  every `@effect/*` companion move as one set, what breaks in a typical\n  upgrade, and how to verify a standalone `npm install` still resolves a single\n  `effect`. Use when asked to upgrade or bump alchemy or effect, when a deploy\n  dies inside an alchemy provider with a `TypeError` naming a missing\n  combinator, when `check:npm-effect-resolution` fails, or when deciding\n  whether the alchemy patch is still needed.\n---\n\n# Upgrade alchemy and effect\n\n## Audience\n\nMaintainers changing the `alchemy` or `effect` pins in this repo.\n\n## Read this first\n\n**Check what upstream ships before working around what we pin.** The pinned\nversion is not a constant, and treating it as one is expensive: TML-3158 was a\nlong chase through pinning, peer dependencies, and a CLI preflight (since\nretired), all to keep\na consumer's tree away from an `effect` that alchemy 2.0.0-beta.59 could not\nrun — while a newer alchemy that had already fixed it sat on the registry the\nwhole time. One command would have shown it:\n\n```bash\nnpm view alchemy dist-tags\nnpm view alchemy@<latest> peerDependencies\n```\n\nIf alchemy's `effect` peer range has moved past our pin, the upgrade *is* the\nfix. Reach for workarounds only after that check says otherwise.\n\n## Why the versions move as a set\n\n`effect` and its companions — `@effect/platform-node`, `@effect/platform-bun`,\n`@effect/platform-node-shared` — each declare a peer that is\n**floored at their own version**:\n\n```jsonc\n// @effect/platform-bun@4.0.0-rc.111\n\"peerDependencies\": { \"effect\": \"^4.0.0-rc.111\" }\n```\n\nThat caret is a range, not an exact pin: it accepts `4.0.0-rc.112` and stable\n`4.x`, but nothing below `4.0.0-rc.111`. So an `effect` **older** than any\ncompanion in the tree is unsatisfiable, and npm resolves that by installing a\n*second* `effect`. Pinning every package in this repo to the same release is the\nsimple way to stay above every floor at once. Treat them as one constellation,\nnever as individual bumps.\n\nalchemy sits on top with a deliberately loose range (`>=4.0.0-rc.115 || >=4.0.0` at beta.78). That range is what lets a stray dependency drag a different `effect` in.\n\n## Two audiences, two failure modes\n\n- **This workspace** uses pnpm, which only *warns* on a peer mismatch and keeps\n  our pinned copy. A broken constellation is therefore invisible in-repo — CI\n  and local dev stay green while consumers break.\n- **Consumers** use npm, which hoists a satisfying version to the root of\n  `node_modules`. alchemy imports whatever is at the root. Nothing we declare\n  prevents this: an exact `peerDependencies` entry does **not** make npm fail —\n  verified empirically, it warns, hoists the other copy anyway, and exits 0.\n  Only the consumer's own `overrides` can force alchemy's copy.\n\nThat asymmetry is why `scripts/check-npm-effect-resolution.mjs` installs real\ntarballs with real npm.\n\n## What a consumer sees when the tree is wrong\n\nComposer has no check of its own for a wrong `effect`. The app's\n`prisma.config.ts` imports the extensions' `/control` entries in its `composer`\nsection, and those import alchemy, so a wrong `effect` fails the moment the\nengine evaluates the config file, before any command runs. The error is the\nengine's `CLI.CONFIG_UNREADABLE`, naming the file and carrying the module error,\nfor example `prisma.config.ts could not be evaluated: Schema.TaggedError is not\na function`. Only the consumer's package manager can fix that tree, usually\nwith an `overrides` entry that forces our pinned `effect`\n(`docs/guides/deploying.md`). Keep the pins below exact and consistent so a bare\ninstall never gets there.\n\n## Steps\n\n1. **Pick the target.** Read alchemy's latest peer range, then choose the newest release where *every* companion publishes a matching version:\n\n   ```bash\n   npm view alchemy dist-tags\n   npm view alchemy@<version> peerDependencies\n   for p in effect @effect/platform-node @effect/platform-bun \\\n            @effect/platform-node-shared; do\n     echo \"$p $(npm view $p version)\"\n   done\n   ```\n\n   alchemy's floor is not a compatibility promise. alchemy 2.0.0-beta.75 to beta.77 accept `effect` rc.112 and later, but call `Config.string`, which rc.113 removed, so they crash on it. Pin the `effect` release alchemy was built against: the newest one published before that alchemy release (`npm view effect time`). Check the new alchemy's Prisma provider still loads from a plain npm install: in beta.79 it imports the optional peer `@alchemy.run/frontend-frameworks` and fails. Since beta.84 each provider is its own package, versioned in lockstep with `alchemy`: the Prisma provider is `@alchemy.run/prisma` (formerly the `alchemy/Prisma` module), and only `@prisma/composer-prisma-cloud` and the Prisma Cloud internals depend on it. Bump it with `alchemy`.\n\n2. **Find every pin.** `alchemy`, `@alchemy.run/prisma`, `@distilled.cloud/prisma`, `effect` and the `@effect/platform-*` packages are pinned once, in the `catalog:` block of `pnpm-workspace.yaml`; every manifest says `catalog:`, and `pnpm pack` writes the resolved version into the published manifest. Check nothing outside the catalog pins them:\n\n   ```bash\n   grep -rln '\"alchemy\"\\|\"@alchemy.run/\\|\"@distilled.cloud/\\|@effect/\\|\"effect\"' --include=package.json . | grep -v node_modules\n   ```\n\n3. **Clear the patch key first.** `pnpm.patchedDependencies` is keyed by the\n   exact version, so an alchemy bump leaves it pointing at a version that is no\n   longer installed and the next install fails or silently skips the patch.\n   Remove the entry now and re-create it in step 5 once you know whether it is\n   still needed.\n4. **Bump all of them to the same versions**, then `pnpm install`. Nothing may\n   be left behind — a single stale companion reintroduces the second `effect`.\n5. **Decide the patch** (see below): typecheck without it, and only re-create\n   it against the new version if upstream still needs the fix.\n6. **`pnpm typecheck`.** Expect real API breakage; see the classes below. Note\n   that turbo stops at the first failing package, so run `pnpm exec tsc\n   --noEmit` per package to see the true scope.\n7. **`pnpm check:npm-effect-resolution`** (after building the two public\n   packages). This is the consumer-facing proof.\n8. **The E2E deploy jobs are the real bar.** An alchemy upgrade changes the\n   deploy engine; a green typecheck says very little about it.\n\n## Pinning an unreleased alchemy build\n\nThe repo is on registry releases: `alchemy` and `@alchemy.run/prisma` 2.0.0-beta.87, `@distilled.cloud/prisma` 1.0.0-rc.20, and `effect` with its companions at 4.1.4. History: Composer pinned a preview of alchemy-run/alchemy#3101 until beta.87 released it together with alchemy-run/distilled#1076. Those two changes let `PrismaEnvironment` and Distilled's `Credentials` omit the token, which `prisma deploy` needs to send every request through the engine's client. Use a preview only when you need a fix that no release contains yet.\n\nalchemy publishes a preview of every commit on `main`, and of each pull request's head as `pr:<number>:<short sha>`. Pin it by commit, never by branch, in the `catalog:` block of `pnpm-workspace.yaml`:\n\n```yaml\nalchemy: https://pkg.alchemy.run/alchemy/<commit sha>\n'@alchemy.run/prisma': https://pkg.alchemy.run/@alchemy.run/prisma/<commit sha>\n```\n\n- **No release while a pin is a URL.** `check:publish-deps` (run by the publish workflow on every push to `main`) fails on any URL, git or `file:` dependency in a published package. Swap the pins for a registry release before merging to `main` expecting a publish.\n\n- **The commit URL is immutable.** It redirects to a content-addressed tarball (`/alchemy/-/<sha256>.tgz`). The lockfile records the commit URL and the tarball's integrity.\n- **Pin `alchemy` and every `@alchemy.run/*` package at the same commit.** They are built together.\n- **A preview's own dependencies are content-addressed URLs too.** `@alchemy.run/prisma` depends on `@distilled.cloud/prisma` by a `/-/<sha256>.tgz` URL. Pin our `@distilled.cloud/prisma` to that exact URL (read it from the tarball's `package.json`), or pnpm and npm install a second copy and `Credentials` stops matching. The commit URL for the same package does not dedupe with it.\n- **The `alchemy` peer of `@alchemy.run/prisma` is a tarball URL.** For a commit preview it may name a different tarball hash than the commit URL resolves to; the two differ only in an embedded URL in `package.json`, and npm accepts our copy. For a pull request preview (`pr:<n>:<sha>`) the peer names the same tarball the PR URL redirects to, but npm compares the specs and `npm ls` reports our `alchemy` invalid, so `check:npm-effect-resolution` fails. Pin `alchemy` to the peer's exact tarball URL then.\n- **Not every package has a preview.** `@alchemy.run/test` returns 404 at every commit, so nothing may depend on it (see the breakage classes).\n- **Read the source at the commit**, not the docs: `git clone https://github.com/alchemy-run/alchemy && git checkout <sha>`, or extract the tarball into a gitignored `wip/` folder.\n- **Move back to a registry version** once a release contains the commit: `npm view alchemy dist-tags`, then compare the release date with the commit date.\n\n## The effect-family packages a consumer installs are pinned in the public packages\n\nalchemy's `effect`-family ranges float past what its code supports (the upstream `TaggedErrorClass` drift), and a floater whose newest release names an `effect` peer that does not exist yet sends npm into hours of backtracking instead of an error (2026-09-11: `@effect/*@4.0.0-rc.114` published ahead of `effect`). Consumers carry no overrides block. Instead, the rule is:\n\n**Pin exactly, in a public package's `dependencies`, every `effect`-family package that a consumer's install will contain.** A package is in the install when it is a regular dependency of `alchemy` or `@alchemy.run/prisma`, an optional peer that one of them loads at runtime, or a package Composer's own code imports. An optional peer that nothing loads is not installed by npm at all, so it gets no pin: pinning it would install it, and everything it depends on, for every consumer.\n\nToday that is:\n\n- `@prisma/composer` — `effect` itself.\n- `@prisma/composer-prisma-cloud` — `@effect/platform-bun` and `@effect/platform-node`, which alchemy loads at runtime (`alchemy/Util/PlatformServices`, `alchemy/Http`; Composer's provider wiring also imports `@effect/platform-node`), and `@effect/platform-node-shared`, which both depend on. It also depends on `@distilled.cloud/prisma`, whose `Credentials` the provider wiring imports; keep it at the exact version `@alchemy.run/prisma` depends on (a tarball URL for a preview) so npm installs one copy.\n\nTo apply the rule on an upgrade, read `dependencies` and `peerDependenciesMeta` in both `alchemy/package.json` and `@alchemy.run/prisma/package.json`, and grep the built `dist/` of the public packages and the installed `lib/` of both for imports of each `@effect/*` package.\n\nHistory: beta.83 listed `@effect/sql-d1` and `@effect/sql-sqlite-do` as regular dependencies, so `@prisma/composer` pinned them, along with `@effect/vitest`, which it pinned on its own. Beta.84 no longer depends on the two SQL packages, and `@effect/vitest` is an optional peer that only `alchemy/Test/Vitest` loads. All three pins were dropped with the beta.84 bump. Dropping `@effect/vitest` also removed `vitest` and `vite` from every consumer's install.\n\n`check-npm-effect-resolution` installs the tarballs bare and fails when the install backtracks or resolves a second `effect`. It installs once more with npm 10, the npm that Node 22 bundles, because npm 10 has crashed on packages the tree once contained (`vitest@4.1.x`); the shape stays as a guard for Node 22 users. The only case left to a consumer's own `overrides` is an app that pins a different `effect` itself (documented in `docs/guides/deploying.md`).\n\n## Breakage classes seen in practice\n\n- **Removed `effect` combinators.** `Schedule.both`/`Schedule.either`\n  (intersection/union) disappeared at beta.97. `Schedule.both(spaced(x),\n  during(y))` becomes `Schedule.spaced(x).pipe(Schedule.upTo({ duration: y }))`;\n  `Schedule.max`/`Schedule.min` are the general replacements.\n- **Stable Effect HTTP imports.** Effect 4 uses `effect/http/*`, replacing `effect/unstable/http/*`.\n- **Alchemy lifecycle identity.** Since beta.82, provider fixtures supply `ResourceContext` (`logicalId`, `fqn`, `instanceId`, `type`) instead of `InstanceId`. Local Database, App and Bucket attributes also need `logicalId`; use `null` because local dev creates no platform rows.\n- **Vitest 5 type tests.** Stable `@effect/vitest` requires Vitest 5. Type-only files need a registered test; keep ambient declarations outside its callback or use definite-assignment fixtures inside it.\n- **Providers moved out of `alchemy` (2.0.0-beta.84).** `alchemy/Prisma` is now the separate package `@alchemy.run/prisma` (`alchemy/Prisma/Types` becomes `@alchemy.run/prisma/Types`). Add it to every package that imports it, including `@prisma/composer-prisma-cloud`, which bundles them. `alchemy` itself no longer depends on `@distilled.cloud/*` or the `@effect/sql-*` packages.\n- **`alchemy/Test/Core` is gone (2.0.0-beta.84).** It moved to `@alchemy.run/test`, which is not published. Provider tests use `scratchStack` and `runScratch` from `@internal/lowering/scratch-stack`, a port of the parts we used.\n- **Real network calls in provider tests.** At the 2.0.0-beta.84 preview, `Prisma.CustomDomain` waits for the hostname's CNAME on its authoritative nameservers before it registers a domain. Tests stub `node:dns/promises` so the wait is skipped.\n- **New adoption advice in engine or provider messages.** `withComposerAdvice` in the CLI rewrites Alchemy's `--adopt` and \"explicit adoption\" advice; its tests read every such message from the installed `alchemy` (`Plan.ts`, `Apply.ts`) and `@alchemy.run/prisma` sources and fail on one it does not rewrite. Add the new message to the rewrite list.\n- **Typed provider errors (2.0.0-beta.87).** Every lifecycle method of a `ProviderService` must fail with `Provider.ProviderError` (`{ _tag: string; message?: string }`), not `unknown`. `Effect.tryPromise` sites pass `catch: toProviderError` from `@internal/core/deploy`, which keeps an error that already has a `_tag` and wraps any other in a `ProviderFailure` with the same message and the original as `cause`. The deploy reports a wrapped error as the error it wraps.\n- **`PrismaEnvironment` holds an Effect (2.0.0-beta.87).** Alchemy runs it on every Management API request. Provide `Layer.succeed(Prisma.PrismaEnvironment, Effect.succeed({ ... }))`.\n- **New required fields on alchemy's resource-handler context** (e.g. `fqn`).\n  These surface only in the test fixtures that build the context by hand.\n- **`exactOptionalPropertyTypes` vs alchemy's types.** See the patch section.\n- **Error counts that go *up* after a fix.** TypeScript stops at the first bad\n  argument, so repairing it exposes the next one. Rising counts mid-upgrade are\n  normal, not a sign the fix was wrong.\n\n## The alchemy patch\n\n`patches/alchemy@<version>.patch` fixes one upstream type declaration:\n`ResourceClassLike.Aliases` is `readonly string[]` (exact-optional) while\n`ResourceClass.Aliases` is `readonly string[] | undefined`. Under this repo's\n`exactOptionalPropertyTypes`, the second is not assignable to the first, so\n**every** `Provider.effect` and `Provider.collection` call fails to compile —\n45 errors across three packages at the time of writing. alchemy carries\n`@ts-expect-error` at its own equivalent call sites, so this is upstream's\ninconsistency, not our misuse.\n\n**Do not work around it at the call sites.** That was tried: it needs a cast at\nroughly twenty sites, and narrowing the argument type also destroys inference\nfor the second argument, which surfaces a fresh wave of errors. Adding\n`| undefined` to the optional property fixes all of them at the source.\n\nOn every upgrade, check whether upstream has fixed it. With the\n`pnpm.patchedDependencies` entry already removed in step 3:\n\n```bash\npnpm install && (cd packages/1-prisma-cloud/0-lowering/lowering && pnpm exec tsc --noEmit)\n```\n\nClean means the patch is obsolete: delete `patches/alchemy@<old>.patch` and\nleave the config entry out. Still failing means re-create it against the new\nversion:\n\n```bash\npnpm patch alchemy@<version>   # edit lib/Resource.d.ts, then patch-commit\n```\n\nHistory: alchemy 2.0.0-beta.67 needed the patch (`lowering` alone reported 17\nerrors without it); upstream fixed the declaration by 2.0.0-beta.74 and the\npatch was deleted with that bump. The check above stays — the inconsistency\ncould regress in a future release.\n\n## The @alchemy.run/node-utils patch\n\n**Resolved — the patch was deleted with the beta.74 bump**: alchemy no longer\nships a file-lock module at all (`@alchemy.run/node-utils` 2.x exports only\n`ignore`), so there is nothing left to patch. The history and the standing\ncheck below stay, because the property it protected still matters.\n\nThe patch was\n[alchemy-run/node-utils#6](https://github.com/alchemy-run/node-utils/pull/6)\n(\"fix(lockfile): scope exit hooks to owned locks\"), vendored against\nnode-utils 0.0.5. Without it, `lib/lockfile.js` called `exitHook(...)` at module scope, so merely\nimporting `alchemy` registered a SIGINT, a SIGTERM, and an `exit` listener on\nthe process. Composer's commands run inside the Prisma CLI engine, and the\nengine owns the whole signal policy: the first Ctrl-C aborts the command and\nwaits for teardown, a second one force-exits. A stray SIGINT listener that\ncalls `process.exit(130)` on its own pre-empts that, killing the process while\nthe engine's cleanup is still running. The engine's family test suite asserts\nthat after a composer command's config evaluation the engine is the sole\nSIGINT/SIGTERM listener, and that assertion is what fails if a stray listener\nis ever reintroduced.\n\nOn every alchemy bump, re-run the standing check (the CLI's signal-listeners\ntest suite runs the same probe):\n\n```bash\ncd packages/9-public/composer-prisma-cloud && node --input-type=module -e 'const c=()=>process.listenerCount(\"SIGINT\")+process.listenerCount(\"SIGTERM\");const b=c();await import(\"alchemy\");await import(\"@alchemy.run/prisma\");console.log(c()-b,\"listeners registered by a bare import (must be 0)\")'\n```\n\n## Keeping the regression check honest\n\n`scripts/check-npm-effect-resolution.mjs` has three shapes: two healthy\ninstalls and one adversarial tree where alchemy resolves an `effect` we did not\npin. Two things about it are easy to get wrong after an upgrade:\n\n- **Do not assert the presence of a specific combinator.** That only ever stood\n  in for \"alchemy can run on this `effect`\", and it breaks the moment upstream\n  removes it for good reasons. `importAlchemy` answers the same question\n  directly: it imports alchemy's root, `Output`, `Provider` and `Stack` entries\n  from the installed app, which must succeed in the healthy shapes and fail in\n  the adversarial one.\n- **`WRONG_EFFECT` must stay a published version other than the pin.** The\n  adversarial shape used to depend on a release whose peer sat *above* our pin;\n  that stopped existing once the pin reached the newest beta, and the shape\n  quietly stopped being adversarial. It now sets the version with an npm\n  `override` instead, so it does not depend on what the registry publishes.\n\n## Gotchas\n\n- **A clean install before believing a failure.** Switching branches around a\n  dependency change leaves stale `node_modules` that produce failures unrelated\n  to the diff. `rm -rf node_modules && pnpm install` before diagnosing.\n- **Compare against `main` before blaming the upgrade.** Some suites fail only\n  under the fully parallel `turbo run test` and pass in isolation, on `main`\n  too; and `@internal/streams` reports a large pre-existing typecheck error\n  count from a third-party package's own source.\n- **`pnpm dedupe` after the pins move**, so stale peer-resolution keys do not\n  linger in the lockfile — but commit it separately, since it touches\n  resolutions beyond the ones being upgraded.\n- **`@prisma/composer`'s `dependencies.effect` must stay an exact version.**\n  `check:npm-effect-resolution` reads it and fails on a range.\n\n## What this skill does NOT do\n\n- **Decide when to upgrade.** alchemy is pre-1.0 and moves fast; this is the\n  procedure, not a schedule.\n- **Upgrade unrelated dependencies.** Keep the constellation bump its own\n  change so a deploy regression has one obvious suspect.\n- **Publish.** See [`publish-npm-version`](../publish-npm-version/SKILL.md).\n","skills-contrib/upstream-alchemy-distilled/SKILL.md":"---\nname: upstream-alchemy-distilled\ndescription: >-\n  How Prisma Composer, the Prisma Cloud target, Alchemy's Prisma provider (`@alchemy.run/prisma`), the Distilled Prisma SDK (`@distilled.cloud/prisma`) and the Prisma Management API (prisma/pdp-control-plane and its OpenAPI spec) depend on each other, and how to get a change through alchemy-run/alchemy or alchemy-run/distilled as an outside contributor without the maintainers rewriting or rejecting it. Use this whenever work will change or plans to change either upstream repository, how a `Prisma.*` Alchemy resource behaves or what it accepts (as opposed to how Composer uses it), the generated Prisma SDK, or a Management API behaviour that Composer's deploy depends on; whenever a Prisma pull request is open in either upstream repository; and to decide which repository a change belongs in before any code is written, even if the request only says \"the provider\", \"the SDK\", \"upstream\" or \"the Alchemy PR\". For moving Composer to a new Alchemy release, use `upgrade-alchemy-effect` instead.\n---\n\n# Changing Alchemy and Distilled from Prisma's side\n\n## Audience\n\nAn agent or engineer on the Prisma side whose work needs something from Alchemy's Prisma provider or the Distilled Prisma SDK. Both repositories belong to the Alchemy team. We are outside contributors there, and we maintain only the Prisma parts.\n\nIf you are about to edit a file in either repository from a Composer session, stop and read \"Work inside their repository, in its own session\" first.\n\nWhy this skill exists: between May and November 2026, Prisma's pull requests to these two repositories drew dozens of objections, rewrites and rejections from the maintainers, and several of their contributor rules were written within hours of one of ours. Almost all of it came from a few causes: working without their guidance loaded, inventing where they wanted a copy of an existing pattern, putting a change in the wrong repository, and treating their repositories as ours.\n\n## The pieces\n\n- **Alchemy** is an infrastructure-as-code engine written with Effect. A program declares *resources*; Alchemy plans and applies them. Composer turns an app into Alchemy resources, and Alchemy runs inside the `prisma` CLI to deploy them.\n- A **provider** is a package of resources for one cloud. Alchemy's Prisma provider, `@alchemy.run/prisma`, holds the `Prisma.*` resources that call Prisma's API. A resource may also have **bindings**: the runtime client a deployed app uses to reach it.\n- **Distilled** generates a typed Effect client (an SDK) for each cloud from that cloud's published API description. A **patch** in Distilled is a small JSON file that corrects the description before generation. Nobody edits the generated code.\n- **PDP** is Prisma's platform, in the private repository prisma/pdp-control-plane. Its **Management API** is what all of the above call, and it publishes its own OpenAPI description.\n- Composer's **Prisma Cloud target** and its **lowering** are the code in this repository that map an app's nodes to provider resources. `docs/design/05-prisma-cloud/alchemy-lowering.md` and the glossary (`docs/design/03-domain-model/glossary.md`) define the rest.\n\n## The chain, and who owns each link\n\nChecked 2026-11-27. Each cell says where to check it again.\n\n| Link | Where it lives | Owner | How a change leaves it |\n| --- | --- | --- | --- |\n| 1. Management API | prisma/pdp-control-plane | Prisma | Deployed to production |\n| 2. OpenAPI spec | Published by the API itself (the mirror's fetch script has the URL) | Prisma | Changes when link 1 deploys |\n| 3. Spec mirror | A git repository the Alchemy team runs, named in Distilled's `.gitmodules` | Alchemy team | Copies the published spec on a schedule (its workflow file has the schedule; daily when checked) |\n| 4. Distilled Prisma SDK | alchemy-run/distilled, the Prisma package: generated code plus patches | Alchemy team; we contribute to the Prisma package | A pull request moves the mirror pin, regenerates, and adds or prunes patches |\n| 5. Alchemy Prisma provider | alchemy-run/alchemy, the Prisma package. Alchemy takes Distilled as a git submodule pinned to one Distilled commit (its `.gitmodules`) | Alchemy team; we contribute to the Prisma package | A pull request, then an Alchemy release |\n| 6. Composer | This repository. Versions are pinned in `pnpm-workspace.yaml` | Prisma | A pin bump, then a Composer release |\n\nEach link is built from the one before it. Composer is the exception to \"only talks to its neighbour\": it also uses the Distilled SDK's credentials type directly and calls the Management API itself for a few things, so a Distilled change can reach Composer without an Alchemy change, and Composer's Distilled pin has to match the one the provider depends on.\n\nWhat follows from this shape:\n\n- **Composer implements no Management API resources itself.** It composes the upstream provider's resources and writes its own only where upstream has none or no API exists behind them. That is a recorded decision: read `docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md` before proposing anything that changes it.\n- **Composer depends on two Alchemy things**: the engine (`alchemy`) and the Prisma provider. A fault in the engine or in another provider is their code, not ours. Describe it to the operator as an issue to raise with them; do not fix it.\n- **Distilled reflects the published spec.** A patch states only what their current rule accepts as evidence (the spec, a real response, the provider's own docs or client). The maintainers' position, on one of our pull requests: \"you work at Prisma, if consumers of the api need to know ... that should go in the API, not a patch in our SDK that adds a value the spec doesn't have.\"\n- **Alchemy calls the cloud only through Distilled.** No hand-written client and no status-code checks in the provider. A missing operation or error type is a Distilled change.\n- **The spec's own markings travel down the chain.** For example, operations the spec marks experimental have been moved to a separate module of the SDK, which changes the imports of every provider file that uses them once Alchemy takes that version.\n- **A change moves only as fast as its slowest link.** The mirror has its schedule, each upstream pull request waits for a maintainer, and Composer can only pin a release or a preview build. Plan the order before starting and tell the operator how many upstream pull requests it means, counted by their rules. Each costs the maintainers a review. An instruction from our side to keep it to one does not change their rule: say what count their rules produce and why, before starting.\n- **Links 1 and 2 are the only ones we control.** When something is hard to express downstream, the cheapest correct fix is usually in our own API or spec.\n\n## Decide where the change belongs\n\nWork this out before writing code, from the top of the chain down. The first link where the needed fact is missing is where the change starts.\n\nWhichever case it is: before offering any opinion on how a platform resource should be modelled, read that resource's design documents in prisma/pdp-control-plane (its `docs/` folder). They define the lifecycle you will model. Code on its `main` is not the design, and states that look like defects, such as a resource that stays pending, are often intended.\n\n**The API must behave differently, or expose something it does not.** Start in prisma/pdp-control-plane. Ship to production, wait for the mirror, then a Distilled pull request, then an Alchemy pull request, then an Alchemy release, then Composer's pins. If the change would break the provider that is already released, ship it so the old behaviour keeps working, have the operator tell the maintainers before it ships, and remove the old behaviour only after an Alchemy release carries the new provider. The maintainers once discovered on their own that a platform change had broken a feature for every Alchemy user.\n\n**The API already does it and the spec says so, but the SDK is older than the spec.** A Distilled pull request that moves the mirror pin and regenerates; their repository has a skill for it. Check their `main` first, because maintainers regenerate too. A regeneration carries every spec change since the old mirror pin, not only the one you came for: say in the description what else it brings.\n\n**The API does it but the spec does not say so** (an undeclared error response, a field that can be null). Prefer fixing the spec in pdp-control-plane: we own it and every consumer benefits. The SDK still has to be regenerated from the new spec afterwards, by the maintainers' own regeneration or by ours, so check their `main` before opening one. A Distilled patch is for a gap we cannot close quickly, with the evidence their rules ask for.\n\n**The SDK's own runtime code for Prisma must change** (its credentials layer, a hand-maintained module in the Prisma package). A Distilled pull request of its own; by their rule it does not share one with a spec fix or a regeneration.\n\n**Only the provider's behaviour or shape must change.** An Alchemy pull request. A change to what a resource accepts or returns is breaking for every Alchemy user, not only Composer, and their conventions say how to mark and explain that. Composer's lowering and its local stand-in providers bind the same resource classes, so they change with it.\n\n**The Alchemy change needs Distilled code newer than Alchemy's pinned commit.** See \"The Distilled pin\" below before doing anything.\n\n**Only Composer needs something to be different.** First try to meet the need in Composer: build a different Layer, wrap the resource, or write a Composer-owned resource where the recorded decision allows one. An option added upstream to serve our embedding has been refused (\"The user shouldn't provide them. If they want to override them, they can construct a new layer.\"). Go upstream only when the need would exist for any Alchemy user.\n\n**You need an upstream change that is not released, or not merged, to check the Composer side.** Alchemy publishes preview builds of commits and of pull request heads. The `upgrade-alchemy-effect` skill covers pinning one and what it blocks.\n\n**It is none of these.** A change to Distilled's shared core or generator, or to Alchemy's engine, for a need only Prisma has, fits nowhere above; Distilled's written rule is that one provider's rule stays in that provider. Describe the need to the operator as a scenario and say which link you think it belongs to.\n\n## What is ours and what is not\n\nIn both repositories we own the Prisma package and its tests, docs and examples. Everything else belongs to the maintainers. Offering to do their upkeep is not a courtesy: it puts our name on changes to code we do not maintain, and it spends the operator's time and machine on work they do anyway.\n\nTheir guidance (as read in November 2026) is written for their own agents, who own the whole repository. So it tells its reader to do some things that an outside contributor should not do unasked. On these, the limits here hold, because each comes from what happened when we did it. If their guidance ever addresses outside contributors directly on one of them, theirs wins and this skill needs a fix.\n\n- **Moving the Distilled pin past our own change.** Their instruction to move it to the merged commit we follow as written. Moving it further, or testing what a move does to other providers, is theirs. See the next section.\n- **Checking the whole repository.** Their guidance says to type-check the whole workspace before a commit. Run the type check for the Prisma package and the test files your change touches. Their CI checks everything else on the pull request, so read it. A whole-workspace run on the operator's machine reports errors in other people's code that we will not fix.\n- **Opening early drafts that carry a status report.** Their own agents do this for work in progress. Our drafts have been finished by a maintainer, merged before we were done, or left to rot. Open a pull request when the work is complete.\n- **Rebasing at checkpoints.** Once a branch has a pull request, merge their `main` into it and never force-push: maintainers push to our branches, and a force-push discards their commits and their place in the review.\n\nAlso not ours: other providers' code, shared core, the generator, the engine, repository-wide configuration, and the lockfile beyond what our own dependency change requires.\n\nWhen a previous session's handover lists upstream work, check each step against this section before doing it. A handover is a predecessor's plan, not the operator's approval. That covers its working copies and its open pull requests too.\n\n### The Distilled pin\n\nAlchemy pins one Distilled commit for the whole repository. An Alchemy change that needs newer Distilled code cannot build until that pin includes it.\n\nTheir skill for provider work tells its reader to land the Distilled change first, then move the pin to the merged commit and commit it. We follow that as written, without asking first, until a maintainer tells us otherwise (the operator's decision, 2026-11-27): the move is from one of their commits to another of their commits, and it is what their own guidance asks for. If a maintainer does say otherwise, do what they say, and add it to this section with its date.\n\nWhat stays theirs is everything beyond that one step. Move the pin to the exact commit our Distilled change merged as, and nothing later: when one of ours moved it further, it pulled in other providers' SDK changes and broke two of their type checks, and a maintainer re-pinned it himself. Do not test or fix other providers against the new pin. A pin pointed at a commit that exists only on our fork cannot be fetched by anyone else, so it can never merge.\n\nThese steps apply the same way to a pull request that is already open.\n\n1. Open the Distilled pull request complete. Build and test the Alchemy change locally by checking the Distilled branch out in your working copy of the submodule without committing the pointer, and keep it on a fork branch with no pull request. Their rules ask a breaking Distilled change to link the Alchemy change that adapts to it: link the fork branch and say its pull request opens once the Distilled change has merged. An Alchemy pull request that cannot build is unfinished work, so it is opened early only if a maintainer asks for it, and then as a draft that says so.\n2. Once the Distilled change merges, move the pin to that exact merged commit, in a commit of its own, and say so in the description with the commit's hash. If the pin has to pass over other Distilled commits to get there, check that the Prisma package still builds and its touched tests pass, and name in the description anything in that range that changes the Prisma SDK.\n3. Then open the Alchemy pull request. If their CI fails in other providers because of the pin, report that to the operator; do not fix other providers.\n4. A pull request that already carries a pointer to our fork is repaired with a new commit that restores their pin, never a force-push.\n\n## Work inside their repository, in its own session\n\nDo not edit an upstream repository from a clone inside a Composer worktree, and do not send subagents from a Composer session to work there. An agent gets a repository's instructions in full only when its session starts in that repository. From anywhere else it gets Composer's rules plus whatever fragments of theirs it happens to search for. That is how a reviewer came to judge Alchemy code against Composer's review checklist, and how Distilled's contributor rules were first read one minute before a pull request was opened.\n\n**How.** Start a new agent session whose working directory is a checkout of the upstream repository, with whatever your harness offers for that, or ask the operator to open one and hand them the brief to paste as its first message. If you can do neither, stop and ask; a subagent pointed at the folder is not a substitute, because it inherits this session's instructions.\n\n**Where.** A clone of the fork we push from, outside every Composer worktree, where the operator keeps such clones (ask once). One checkout per agent: the installed dependency tree is shared state, and two agents in one checkout have broken each other's runs.\n\n**Distilled is its own repository.** Alchemy vendors Distilled as a submodule and its own guidance has its agents patch and regenerate there. For us a Distilled change runs in a session started in a Distilled checkout, so Distilled's contributor rules are loaded. Do not install dependencies inside Alchemy's copy of Distilled: Alchemy's workspace supplies them, and a second install there has broken the checkout.\n\n**Work already in the wrong place.** If a predecessor left clones with commits inside a Composer worktree, move the work, do not continue it there: push its branch to the fork and start the upstream session on that branch. If that branch already has a pull request, push the unfinished work under a new branch name instead, so nothing unfinished lands on a branch a maintainer may merge.\n\n**\"Just do it here.\"** A message that hands you a clone inside the worktree, or says \"do that\", was written before the operator heard the concern, so it is not yet their decision. Say once what goes wrong without their instructions loaded, offer to write the brief for an upstream session, and ask. Then do what they decide. If they decide on in place, read that repository's guidance in full by hand before touching anything, and say in your report that it was done that way.\n\n**Reading is not editing.** A Composer session may read upstream source, guidance, issues and pull requests to work out which link a change belongs in. It does not edit there and does not propose a resource's shape.\n\n**Two repositories, two sessions.** When a change needs both, the Composer session coordinates: the Distilled session first, then the Alchemy session against the Distilled branch. Record in the project's plan where each checkout is and which session owns it, so a successor does not ask the operator again.\n\n**What stays in the Composer session:** what the work is for, what Composer needs from upstream, the project record under `.drive/`, and the brief. It does not recommend a resource's shape to the operator: what an upstream resource looks like to an Alchemy user is proposed by the upstream session, after its reading, and goes to the operator before it is built. A recommendation made from the platform's side alone has had to be reversed once the existing Alchemy pattern was read.\n\n**The brief** for the upstream session says:\n\n- What the change is for, and the design as our best effort: the purpose is fixed, the mechanism is open to challenge against their code and conventions.\n- Where the platform's design documents for the resource are, and that it reads them before modelling a lifecycle.\n- The absolute path of this skill's folder, and that it reads `SKILL.md` there. Composer's skills are not installed in their repository.\n- The limits in \"What is ours and what is not\".\n- That a change to what users declare or see goes back to the operator before it is built.\n- That rules meant for pull requests in our own repositories do not carry over: our description style, any line naming the agent, auto-merge, and merging it ourselves. Upstream, the maintainers merge. An independent review before the pull request opens is still worth having, judged against their guidance and not our own review checklist.\n\n**The first things the upstream session does**, before any design opinion or code:\n\n1. Read the repository's agent guidance in full, not by searching it: the root instruction file, what it links for outside contributors, the pull request template if there is one, and the repository's own skills for the kind of change in hand. These files change often. They are the authority on how code, tests, names, commits and descriptions look in their repository, and they win over this skill on all of that.\n2. Find where the repository already does the same job (another provider's resource of the same kind, a binding, a test fixture, a credentials layer) and read it. Copy its names, shape and mechanism.\n3. Search their open issues and pull requests for the same problem. We once built something they already had an open issue for, and they shipped their own design within days.\n4. Check that their `main` has not already fixed it, and check again each time you merge their `main`.\n\n## What the maintainers hold to\n\nThese have held across the record so far. Each has its reason, so you can judge a case their files do not cover.\n\n- **Follow what exists; invent nothing.** They value a consistent repository over a locally better idea (\"I prefer the repo to be consistent\"; \"This isn't something we typically do\"). A concept, name, option or branch that no other provider has will be rewritten. When you believe a departure is right, say in the description why the existing way is not enough, before they ask.\n- **A resource is not finished when it deploys.** They have expected its runtime bindings, and for compute an Effect-native form, in the same piece of work. Find out from their guidance what the resource kind requires and count it before telling the operator the size.\n- **Alchemy provider changes are proven by deploying real resources.** No fakes, mocked responses or direct lifecycle calls. Our tests were rewritten as live tests on six pull requests, five of them by the maintainers' own commits, and the live versions found provider bugs on at least four. A failure the real platform cannot be made to produce comes from a fixture that misbehaves, or is not tested. Distilled's testing rules are different; read each repository's own.\n- **Live tests need a test account.** Ask the operator for a token to a workspace used only for tests, and where it is kept; never print it; get it before the pull request opens. Do not assume a deploy token you already have points at such a workspace. Their guidance has an account-wide teardown for leaked test resources. Run it only against that test workspace, and only with the operator's yes.\n- **A provider leaves alone what the stack did not declare or create.** Omitted props mean \"not managed\", not \"reset to a default\". A resource the provider finds but cannot prove it created is not owned until the user adopts it. Nothing a provider provides may change what other providers in the same stack see.\n- **Effect throughout**, in source, docs and examples alike, because examples teach users.\n- **One change per pull request, by each repository's own definition.** Distilled's is written and narrow: a spec fix and a runtime change are two. A correct fix of ours was lost there because it shared a pull request with a rejected feature, and a description that says it breaks a rule on purpose is read as exactly that. In Alchemy a resource with its bindings, tests and docs has been one change, and one piece of work opened as three pull requests was joined into one by its author soon after.\n- **Descriptions are short and say what the user can now do.** In both, the pattern they kept when rewriting ours was one plain sentence, then a code or diff block, a few bullets, and a marked breaking change. They cut status reports, test logs, file lists, long justifications and agent name lines. Use the format their current guidance and template give; the two repositories differ (in November 2026 Distilled had a template with a checklist and required a signed note on anything an agent wrote, while Alchemy forbade checklists, test sections and large headings), so do not carry one's format to the other. Have a reader with none of our context check the description against their conventions before it goes up.\n- **Names are theirs.** Name a resource after the platform's own product name. A name suggested as a question is a request: act on it or answer it in the next push.\n- **Their decision is the decision.** When a maintainer says they are solving it another way, ask how to fit into their design, then close ours with a line saying why, or redo it on theirs. Restating our case has not changed an outcome so far, and they have shipped their own version within hours. A real technical reason, stated once and plainly, has been accepted.\n\n## How their pull requests move\n\nPlan around what they do, not around what a pull request's state suggests.\n\n- **So far no maintainer has submitted an approving review on one of ours.** They comment, push commits to our branch, rewrite the description, and merge. Keep maintainer edits allowed.\n- **A draft is a signal, not a lock.** A maintainer has taken one of our drafts out of draft and merged it minutes later, at a commit we meant to add to. Every commit pushed to a branch that has a pull request must be safe to merge as it stands. If more is coming, it is in the pull request before it opens, or it is a separate change. Unfinished work lives on a fork branch that has no pull request; pushing there is yours to do.\n- **They read, run and fix drafts,** and do not chase. Good small changes have merged in under an hour; ones that needed work waited weeks with one comment or none.\n- **Keep it mergeable and green.** Merge their `main` when it conflicts. Take their side for every file our change does not own, then check the diff for files we never meant to touch; a merge of ours once silently deleted features from their `main`. Fetch before every push.\n\nSomeone has to know when a maintainer acts. Watch each open upstream pull request for comments, pushes, state changes, merges, failed checks and conflicts with their `main`, with whatever your harness offers. Write the watched pull requests into the project's plan, so a session that restarts finds them and sets the watch up again (background commands do not survive a restart). Tell the operator who did what, including when a merge happened with no review.\n\n## Speaking to the maintainers\n\nA maintainer here means someone who merges in that repository. Check who a commenter is before weighing what they say.\n\nOpening, editing, marking ready, commenting on or closing an upstream pull request speaks to another team in the operator's name. Those steps are the operator's, or need their explicit yes each time. Never turn on auto-merge or merge upstream.\n\n- Find out which GitHub account your shell acts as before planning these steps. Work out the whole sequence of operator steps once, in order, as commands that are safe to run twice and that say where to run them, and ask once.\n- After any GitHub write that reports an error, read the state back from GitHub before saying what happened.\n- When a maintainer asks or requests something, bring the operator the question and a finished draft answer in one message the same day, in the format their rules require for text an agent wrote. A question of ours that went unanswered got its pull request closed, and others waited a week or more. Where the request is a code change inside the agreed design, such as a rename, push it without waiting and say so in the draft. Do not post it yourself.\n\n## When the operator's request and this skill pull apart\n\nThe operator may ask for the very thing this skill warns against: finish it in the clone here, keep it to one pull request, make sure nothing else breaks, defend the option, add it to the SDK anyway. They may not have the earlier incidents in mind when they ask. Say once, briefly, what happened the last time and what you would do instead, and ask. Their answer decides anything on our side: where the work is done, how much we check, what we propose. It does not change the maintainers' rules or decisions. Where the request is something a maintainer has already refused, the next step is the operator raising it with them, not a pull request that tries it again.\n\n## After it merges\n\nA merged upstream pull request changes nothing in Composer until Alchemy releases and Composer's pins move. The `upgrade-alchemy-effect` skill covers the bump. Update the project's plan in the Composer pull request that consumes the release, and tell the platform's owners when a removal there was waiting on the provider.\n\n## Before asking the operator to open or mark ready an upstream pull request\n\n- The work was done in a session started in that repository, with its current guidance read in full in that session.\n- It touches only the Prisma package, or each file outside it copies an existing shape and is explained in the description.\n- The Distilled pin is at the exact commit our Distilled change merged as (or where a maintainer said to put it), in a commit of its own, and nothing points at a commit that exists only on our fork.\n- Alchemy: every behaviour is covered by a test that deployed for real, and you ran the ones your change touches. Distilled: each patch has its evidence.\n- It is one change by that repository's definition.\n- The description follows their current format, and a fresh reader has checked it against their conventions.\n- Nothing in it is unfinished, and every commit on the branch is safe to merge today.\n- The pull request is written into the project's plan, and a watch on it is in place.\n\n## What this skill does not cover\n\n- Moving Composer to a new Alchemy release or a preview build: `upgrade-alchemy-effect`.\n- How to write a provider, a patch or a test in their repositories: their own guidance and skills, loaded by working there.\n- Reviewing an outside contributor's pull request to our own repositories.\n- Design decisions inside Composer or the platform: each repository's design documents.\n","skills/README.md":"# Prisma Composer skills\n\nAgent skills for [Prisma Composer](https://github.com/prisma/composer) — one\n`SKILL.md` that teaches an LLM agent how to write, test, and deploy a Prisma\nApp without re-deriving the API from documentation each time.\n\n## What's in the box\n\nOne skill, `prisma-composer-core-concepts`, covering the whole story: the mental model\n(Modules, `compute()`, `service.load()`), RPC contracts, databases, reusable\nmodules (cron/storage/streams), config params, secrets, testing\n(`mockService`/`bootstrapService`), deploying (`prisma deploy`,\nenvironments, removing an app or an environment), and the production pitfalls. Composer's surface is small\nenough for one skill; there is no router or per-topic cluster.\n\n## Install\n\nThe skill ships inside the `@prisma/composer` tarball, so installing the\npackage is what brings it in. `prisma skills sync` (from the `prisma` CLI)\ncopies it out of `node_modules` into the skill directories the agent runtimes\nread — `.claude/skills/`, `.cursor/skills/`, `.agents/skills/`,\n`.windsurf/skills/`:\n\n```bash\npnpm add @prisma/composer\npnpm add -D prisma\npnpm prisma skills sync\n```\n\nAdd it to your project's `postinstall` so an upgrade brings the matching skill\nwith it:\n\n```jsonc\n// package.json\n\"scripts\": {\n  \"postinstall\": \"prisma skills sync || exit 0\"\n}\n```\n\nIn a monorepo (a pnpm, npm or Yarn workspace), put the hook in the `package.json` at the workspace root (the directory with `pnpm-workspace.yaml`, or the `package.json` that lists `workspaces`), not in a workspace package's: hooks in several packages run at the same time and can leave the skill copy at the root missing a file. The root's sync installs the skills of every workspace package. List `prisma` there as a dev dependency, at the version your packages use, so the root's hook can find the command. If `prisma` warns with `SKILLS.MEMBER_LEFTOVER`, a workspace package still has something an earlier `prisma` put there: move the hook to the root, and delete the other files the warning names, such as old skill copies.\n\nThe version you read is then always the version you installed: the skill's\nfrontmatter carries `metadata.library: \"@prisma/composer\"` and a\n`metadata.library_version` stamped by the release that built the tarball\n([`scripts/set-version.ts`](../scripts/set-version.ts);\n[`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs)\nproves it against the packed artifact).\n\n### Without installing the package\n\nThe GitHub source stays available for anyone who wants the skill without\n`@prisma/composer` in their project:\n\n```bash\nnpx skills add prisma/composer\n```\n\nThe [`skills` CLI](https://npmjs.com/package/skills) installs it at the\nproject level for the agent runtimes it detects (`-a <agent>` to pick one).\nNothing keeps this copy in step with your packages, so pick the git ref\nmatching your `@prisma/composer` version by hand and re-do it on every\nupgrade.\n\n## Authoring rules\n\nThe skill is the agent-condensed mirror of the human guides in\n[`docs/guides/`](../docs/guides/) — the guides are canonical for humans; a\nsurface change lands in both. For anyone editing the skill:\n\n- **Verify every claim while drafting, not in a final pass.** Every import\n  must resolve against a `packages/9-public/*` export map, and every CLI\n  flag/command against `packages/0-framework/3-tooling/cli/`. If ripgrep finds\n  nothing, the surface doesn't ship — name it under *What Composer doesn't do\n  yet* instead of extrapolating.\n- **The skill must be self-contained.** It gets installed into other repos, so\n  no link may resolve outside `skills/prisma-composer-core-concepts/`. Repo\n  docs may be\n  named in prose (\"`docs/design/10-domains/testing.md` in the prisma/composer\n  repo\"), never linked relatively.\n- **Teach concepts, not procedures.** Name the moving parts and the command\n  that reveals each piece of state; reserve numbered steps for one-safe-path\n  operations.\n- **Leave the `metadata` stamp alone.** `metadata.library` names the npm\n  package the skill ships inside, and `metadata.library_version` is rewritten\n  by [`scripts/set-version.ts`](../scripts/set-version.ts) on every release —\n  hand-editing the version, or dropping either key, breaks the release script\n  and [`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs).\n  They live under `metadata` because the Agent Skills spec defines the\n  top-level keys and reserves that map (string → string) for publisher\n  extensions. A new skill needs both keys, with any placeholder version.\n- **Folder name and frontmatter `name` must match** — the runtimes key on the\n  frontmatter, humans on the folder.\n\nMaintainer-facing skills (release process, commit conventions) live in\n[`../skills-contrib/`](../skills-contrib/), not here.\n","skills/prisma-composer-core-concepts/SKILL.md":"---\nname: prisma-composer-core-concepts\nmetadata:\n  library: \"@prisma/composer\"\n  library_version: \"0.41.2\"\n  version: 2026.9.1\ndescription: >-\n  Use when deploying or managing an app that uses Prisma Composer\n  (`@prisma/composer`): wiring its services and Modules, running it locally,\n  testing composed services, or standing up / tearing down an environment.\n  Triggers on \"prisma composer\", \"@prisma/composer\", \"prisma app\",\n  `prisma deploy`, `prisma dev`, `compute()`, `appRoot()`, `module()`, `contract()`,\n  `service.load()`, `mockService`, `bootstrapService`.\n---\n\n# Prisma Composer core concepts\n\nA **Prisma App** is a tree of typed declarations composed in TypeScript and\nhanded to the `prisma` CLI, whose two main Composer commands are `prisma deploy`\nand `prisma dev`. Removing a whole app is `prisma project delete`. Removing\none environment and reading logs are not commands; they are the `destroy` and `log`\noperations of `@prisma/composer/control`, called from a script.\nThis file covers structures, hierarchies, relationships, and workflows: the\nconcepts you cannot observe from the code or the CLI's help output. It is not\na CLI reference; discover each command's flags with `prisma <command> --help`\nrather than inferring them. The Prisma platform moves fast, so treat this file as the\nstable conceptual core and find current, fuller documentation at\n<https://www.prisma.io/docs>. For working code, read `examples/` in the\nprisma/composer repo.\n\nTwo principles govern everything and are binding\n(`docs/design/01-principles/`):\n\n1. **Your code never reads environment variables.** Dependencies, configuration,\n   credentials, and the port all arrive through the service node, typed.\n   `process.env` is never the answer.\n2. **Composer never bundles or transforms your code.** You build with your own\n   bundler; the framework assembles the built output by deterministic steps\n   and hands it to the configured deploy target.\n\n## Declarations are data\n\nEverything you author is a declaration: plain data describing a piece of the\napp, executing nothing when imported. Three node kinds exist:\n\n| Kind | Declared with | Purpose |\n| --- | --- | --- |\n| Service | `compute()` | A running unit of your code; atomic, Composer sees only its boundary |\n| Resource | `rawPostgres()`, `bucket()` | A stateful managed dependency |\n| Resource: public URL | `publicUrl()` | Makes one service reachable from the internet at one hostname; depends on the service's exposed HTTP interface and exposes nothing |\n| Module | `module()` | A grouping boundary; runs no code of its own, depends on and exposes typed interfaces; its builder receives `deps`, `input`, `environment` and `provision` |\n| App root | `appRoot()` | The outermost module, the entry's default export; no `deps` or `expose`, and nothing can provision it; its builder receives `input`, `environment` and `provision` |\n\nNodes connect through typed **interfaces**: `deps` declares what a node depends on, `expose` declares what it exposes. Wiring happens in a Module's builder via `provision()`, and the app root, built with `appRoot()` and handed to the CLI, is the App:\n\n```ts\n// module.ts\nimport { appRoot } from '@prisma/composer';\n\nexport default appRoot('store', ({ provision }) => {\n  const catalog = provision(catalogModule);\n  provision(storefrontService, { deps: { catalog: catalog.rpc } });\n});\n```\n\nBecause interfaces are typed, **the compiler verifies every wire**. A dependency wired to the wrong producer, a missing RPC handler, a literal input value of the wrong shape: all of it fails `tsc`, not the deploy. Values from outside the code are the exception: a root input field exists only at deploy, and a platform variable only on the platform, so a schema refinement the type does not carry and a missing platform variable a service needs surface as early deploy-time refusals instead (see Two channels below). Typecheck, then build, then deploy; don't use the cloud to find out whether the wiring is correct.\n\nComposer itself is target-agnostic: `@prisma/composer` carries authoring, testing, and the CLI, coupled to no platform. A deploy target is an extension registered in the deploy config; `@prisma/composer-prisma-cloud` is the Prisma Cloud target and the one this skill's deploy sections assume. Its root exports `compute`, `rawPostgres`, `bucket`, `publicUrl`, `variable`, `generatedParam` and `serviceOrigin`; the ORM vocabulary (`postgres`, `dataContract`) lives under the `/orm` subpath, alongside the shared `/cron`, `/storage`, `/streams`, `/auth`, and `/email` modules. These are the only two Composer packages a basic Prisma Cloud app needs, and nothing installs them for you: a fresh project starts with neither, so add both as dependencies first. An extension adds its own `prisma-composer-*` package alongside them. Compose an existing Module before implementing a capability yourself; wiring one in is a couple of lines.\n\nWithin the entry graph (everything reachable from `module.ts`), write\nrelative imports with explicit `.ts` extensions (`./service.ts`, with\n`allowImportingTsExtensions` in tsconfig): that form resolves everywhere.\n`prisma deploy` and `prisma dev` also map `./service.js` and extensionless\n`./service` to the `.ts` source, but other tools may not.\n\n## The service node is the only doorway\n\nYour runtime code receives everything from the service declaration it\nimports:\n\n1. `service.load()`: dependencies (typed RPC clients, database bindings).\n2. `service.input()`: the whole input as one schema-validated object;\n   credentials in it are redacting `SecretString` boxes.\n3. `service.port()`: the reserved port to bind (default 3000).\n\nA service declaration is pure data; the server entry is what your build\nproduces and the platform boots:\n\n```ts\n// service.ts\nexport default compute({\n  name: 'auth',\n  deps: { db: rawPostgres() },\n  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),\n  expose: { rpc: authContract },\n});\n\n// server.ts\nconst { db } = service.load(); // { url }: you construct your own client\nconst handler = serve(service, {\n  rpc: { verify: async ({ token }) => ({ ok: token.length > 0 }) },\n});\nBun.serve({ port: service.port(), hostname: '0.0.0.0', fetch: handler });\n```\n\nThe consumer declares `deps: { auth: rpc(authContract) }` and gets a typed\nclient back from `load()`.\n\n## Two channels: dependencies and input\n\n| The value is… | Declare | Provide | Read |\n| --- | --- | --- | --- |\n| produced by another node | `deps: { db: rawPostgres() }` | wire at `provision()` | `load()` |\n| anything else (config or credential) | one field of the `input` schema | bind at `provision()`: literal, root input field, platform variable node's value, or a `resolve()` value | `input()` |\n\nThe service declares its whole incoming configuration, plain values and credentials together, as **one [Standard Schema](https://standardschema.dev)** (arktype is the house choice). A credential is a field typed as `secretString()` from `@prisma/composer/arktype` (or `@prisma/composer/zod` for a Zod schema; the app installs `arktype` 2 or `zod` 4 itself, and Composer uses that copy); conditional legality (\"no stripe key unless billing is on\") is an ordinary schema union. The binding at `provision()` mirrors the schema's shape.\n\nA value you supply, rather than write in code, arrives in one of two ways:\n\n- **A value the deploy reads** is a **root input field**: a field of the app root's `input` schema, filled by the `config` adapters (by default the deploying shell), checked by the root's schema before anything is created. The root passes it on by name. Only these can be listed in `resolve()` or put in a resource's props.\n- **A value the service reads at boot** is a **platform variable node**, provisioned in the app root: `provision(variable({ name: 'EMAIL_FROM' }))` for a plain value, `provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }))` for a secret. `provision()` returns the value with `id`, the node's address, on it; pass it down through module inputs to the services that read it. The node names the variable and never carries its value; the operator sets the value on the platform.\n\n```ts\nexport default appRoot('shop', { input: type({ EMAIL_FROM: 'string' }) }, ({ input, provision }) => {\n  const stripeKey = provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }));\n  provision(billing, { input: { from: input.EMAIL_FROM, stripeKey } });\n});\n```\n\n**Only `appRoot()` can provision a platform variable node.** A variable's name is one space per deployed app, and the root is the app. In a `module()` body (a nested module or a `module()` root) `provision(variable(…))` fails to compile, with an error naming `appRoot()`. A module that needs the value declares a field in its `input`. The node creates nothing on the platform and stays out of the application topology and the deploy report; the loaded graph lists it and, in `graph.valueReads`, each service that reads it. Its default id is the name in camel case (`EMAIL_FROM` is `shop.emailFrom`); two nodes whose names give one id fail with an error naming both, so pass `{ id }`.\n\nRules that bite:\n\n1. **Secretness is checked by the binding's type and by the deploy.** A `provision()` binding, a service's or a module's, is typed from the schema: a literal or a `SecretBox` where the schema expects `SecretString`, or a platform secret's value in a text field, fails to compile, and the deploy refuses it where the schema has no types. An ArkType schema with a `SecretString` field cannot also transform its input: a morph anywhere in it (`'string.trim'`, `.pipe()`, `field(type('string.integer.parse'))`) or `'+': 'delete'` copies the input, the copied secret loses its value, and the deploy refuses it. Transform in the service code instead; a Zod schema keeps the box.\n2. **A plain platform variable's value is known only at boot: text, or the type its `schema` declares.** Bind it to a field wrapped with `field()`. A platform variable's value goes into a field of an `input` only. A compute service has one per-key param, the reserved `port`, which takes a literal or a root input field and no source, because the deploy needs the port before the service exists; every other value is a field of its `input`. A field of a narrower type, such as `email()`'s `deliveryMode`, takes a root input field declared with that type instead, for `email()` from the exported `emailDeliveryModes`; the deploy reads a root input field from the app configuration on every deploy and writes its value into the input document. A platform secret fits a `secretString()` field only. A platform variable's value always lives on the platform. The operator sets it there with `prisma project env add 'NAME=<value>' --project <id> --role production`. Use `--role preview` for every preview environment, or `--branch <environment>` for one. The deploy does not copy local values (`.env`, the shell) to platform variables. The deploy fails only when a variable that a service's schema requires has no value. The error names the variable and the command that sets it. The other variables with no value print under `Platform variables with no value:`. Prisma Cloud reports a service that exits at boot as running and promotes it; read the error with `prisma service logs <service>`.\n3. **The schema decides whether a field may be absent.** A field bound to a platform variable that is unset or empty is left out at boot. That is allowed only if the schema allows it, for example with an optional field or a union member. An optional root input field that the adapters do not supply is left out at deploy. The deploy report prints the serialized input document (each secret shown as `$platform VAR`) and every key that resolved absent. On Prisma Cloud the deploy writes the input document into the service's artifact, not into a `COMPOSER_*` variable, so it is not limited to a variable's 8 KB, and a changed document redeploys exactly that service.\n4. **The reserved `port` is outside the schema.** Read it through\n   `service.port()`, never `process.env`. The framework also exports `PORT`\n   for Next.js standalone, which binds it itself.\n5. **A Module passes a secret on without learning the platform name.** Declare a `secretString()` field in the Module's `input` and pass `input.<field>` on as a binding leaf; the app root provisions `variable.secret({ name: 'NAME' })` and binds its value. A module has no `params` or `secrets` slots: `module()` and `provision()` refuse both, naming `input`. A service's `params` stay.\n6. `input.apiKey.expose()` is the only way to a secret's value; the box\n   redacts everywhere else (logs, JSON, errors).\n7. **Platform variable names are upper case**: `^[A-Z][A-Z0-9_]*$`. `COMPOSER_…`, `DATABASE_URL`, `DATABASE_URL_POOLED`, `PORT`, `PATH` and `HOME` are reserved, each name is declared by one node, and one name cannot be both a platform variable and a root input field. A node's value bound as a service's whole input is refused too. Each fails before anything is created, naming the variable and the addresses.\n8. **A field bound to a plain platform variable, `serviceOrigin()` or a plain `generatedParam()` is wrapped**: `field(type('string'))`. At deploy the schema sees a pointer, and a plain `'string'` field refuses it: a compile error in a service's or a module's binding, and a deploy error where the schema has no types. `service.input()` and `mockService`'s input double read the field as its inner type.\n9. **A platform variable holds text; `schema` says what the text means.** `variable({ name: 'SMTP_PORT', schema: type('number') })` (any Standard JSON Schema library: ArkType, Zod) gives a runtime value of type `number`, which fits `field(type('number'))` and not `field(type('string'))`; without `schema` the value is the text and the reverse holds. An object schema fits a `field()` of the same object type. A schema that accepts only text gives the text exactly, untrimmed; any other schema reads the text as JSON (`587`, `true`, `{\"host\":\"h\"}`, `null` under `number | null`). A schema that accepts both, such as `string | number`, `z.unknown()` or `string | null`, is refused when the root body runs; for an optional text variable declare the text type and make the service's field optional. `variable.secret()` takes no schema.\n10. **Boot decodes and validates the text against the variable's JSON Schema, then the service's schema runs.** A failure fails boot, not the deploy: read it with `prisma service logs <service>`. Messages name the variable and never hold its text: `The platform variable \"SMTP_PORT\" does not hold a number. Its schema is not a text type, so its text must be JSON, such as 587.`, `... does not fit its schema: it fails \"minimum\" at #/minimum.` A whole number above 9007199254740991 is refused: keep an identifier as text. A value nested more than 100 levels deep is refused too. `prisma dev` runs the same check before any service starts and adds `prisma dev cannot start, because service \"<address>\" reads it.`\n11. **No library code runs on a variable's value; only the JSON Schema the library emits is checked.** A transform or a default the JSON Schema shows (`.transform()`, `string.numeric.parse`, a default inside an object) is refused at the root body; put defaults on the service's field. ArkType throws for `.narrow()` and `string.url`. Zod drops `.refine()`, and `.trim()`, `.toLowerCase()`, `z.coerce`, `z.preprocess()` and `.catch()` are accepted and do not run. An undeclared object key is not removed (`z.object()`, ArkType `'+': 'delete'`) and reaches the service's field. Regex flags are dropped and a pattern must be valid under the `u` flag (no `\\-` outside a character class). `format` is checked for `date`, `time`, `date-time`, `duration`, `uri`, `uri-reference`, `uri-template`, `url`, `email`, `hostname`, `ipv4`, `ipv6`, `regex`, `uuid` and the three JSON Pointer formats; others, such as `z.jwt()`, are unchecked. `z.number().optional()` does not fit `field(z.number())`: make the service's field optional. A hand-written schema that contradicts itself fails every boot. Put any other check or change in the service's own schema.\n\n### Values that differ per environment\n\nThe graph is the same in every environment; only configuration may differ.\n\n- A module declares `input` (one Standard Schema) as a service does; `provision(module, { input })` binds it, and the body receives `input`, a dictionary of values: it passes each field on by name into a binding or, for a plain field, lists it in `resolve()`. Passing the whole `input` on fails to compile, and the deploy refuses it. A root's `input` is the app configuration, and a module's `input` takes every source a service's does.\n- `field(inner)` from `@prisma/composer/arktype` or `@prisma/composer/zod` wraps one field's schema (`field(type('string'))`, `field(z.string())`) so it also accepts a plain pointer, which is what a value known only at boot such as `serviceOrigin()` is at deploy. In the body the field is `Value<string | Pointer<string>>`: pass it into another wrapped field or a service's input, never a plain `string` field (compile error). A wrapped field holds the whole value one source supplies, which may be an object or array when a platform variable's schema says so, so `field(type({ host: 'string' }))` is fine. An ArkType default goes outside: `field(type('string')).default('x')`. Other schema libraries: `Pointer`, `PlainPointer`, `isPlainPointer()` (narrows to `PlainPointer`) and `isSecretPointer()` from `@prisma/composer`. Wrap every field of a reusable module's schema other than a `secretString()` field, unless a `resolve()` lists it; keep a root's fields plain. `field(secretString())` is wrong: it accepts a plain pointer into a secret field, and the service fails at boot.\n- `composer({ config: [...], secrets: [...] })` lists config adapters; each gets the environment's name and returns values, later wins by top-level key. Both default to `[environmentVariables()]` (the shell); a list you write replaces the default. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local`, later wins. The app configuration fills the root's input (under `prisma dev` it also gives each plain platform variable a service reads its value, under the variable's name); pass the root's input fields on by name, as every module does; its whole `input` would be the whole app configuration, by default every shell variable. The app secrets give `prisma dev` its secrets; a deploy reads them only to redact. It does not fill a platform variable from them, and never reads them as the root's input. Both import from `@prisma/composer/config`. Credentials (`PRISMA_SERVICE_TOKEN`) still come from the shell. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local` through `dotenv-flow` (no `.env.local` for `test`); remove `import 'dotenv/config'` when you list it. Composer redacts the values under the names of the graph's platform secrets, in either list; the lists' other values are not secrets and print as they are, apart from values that look like credentials. Under `prisma deploy` the engine's output is redacted too; under `prisma dev` it is not yet.\n- A field exists only under a plain object: a path into a string, an array or a secret, such as `input.tags[0]`, fails the deploy naming the path.\n- A truthiness check such as `if (input.enabled)` is not caught: the field is an object, so the branch always runs, in every environment. A module's structure cannot depend on its input; to provision something only sometimes, let the parent decide whether to provision it.\n- The module body receives `environment`; `environment.name` is a value standing for the name `--environment` gave (`production` for `prisma deploy`, `dev` for `prisma dev` by default).\n- `resolve([deps], ([values]) => …)` from `@prisma/composer` returns a computed value; `fn` receives the dependencies' real values as one tuple.\n- A value is accepted as a leaf of a service's or a module's `input` binding, at any depth, as a service param (a deploy-time value only), as one of a `resource()` node's `props`, or as a public URL's `url`. Never as a provision id or a `deps` entry.\n- A value is opaque in the body: you cannot read, compare or branch on it. List it as a `resolve()` dependency instead.\n- Calling `provision()` inside `fn` fails the load: `fn` computes configuration, never graph structure.\n- `fn` is pure and synchronous and returns plain data (no `undefined`, Promise, value or source); a deploy and `destroy` both run it, in two processes. To retire an environment, keep its case in every `fn` until `destroy` for it has finished.\n- Sources are values. `resolve([input.X], ([x]) => …)` over a root input field receives its data. A dependency must be a deploy-time value: a platform variable's value, `generatedParam()`, `serviceOrigin()`, a field wrapped with `field()` and a `secretString()` field cannot be listed (a compile error saying so; for a field typed `unknown` or a cast, the deploy fails naming the field). Bind those directly; to compute with a field, declare it plain. For a different secret per environment, use one name with a different value on each environment.\n\n## Contracts and RPC\n\nAn RPC contract is the typed interface through which services communicate. It\nlives with the service that owns it, typed by any Standard Schema validator,\nand both provider (`serve()`, exhaustive over the contract's methods at\ncompile time) and consumer (`rpc(contract)`) reference the same value. Calls\ntravel as RPC over HTTP. Two behaviours are provisioned for you and must not\nbe reimplemented:\n\n1. **Service keys.** At deploy, Composer mints a distinct unguessable key per\n   consumer→provider binding; `serve()` returns `401` to anything else before\n   the handler runs. Nothing in your code declares it. Consequences: don't\n   build your own service-to-service auth, and don't `curl` a deployed\n   `/rpc/<method>` to check it works. An unwired caller always gets `401`,\n   which looks like a broken deploy and isn't. Debug through a consumer, or\n   locally, where nothing is enforced. Keys are per binding (one leaking\n   can't impersonate another consumer), service-scoped (any valid key\n   reaches every method; split services to gate separately), rotated only by\n   removing the binding or destroying the stack and redeploying, and stored\n   in deploy-owned `COMPOSER_*` variables you never hand-edit.\n2. **Idempotency and retries.** Every generated-client call carries an\n   `Idempotency-Key`; dropped calls retry with backoff, and `serve()` runs\n   one call per key, replaying the completed answer to late retries. Every\n   method is therefore safely retryable and no contract declares anything\n   about it (there is no \"is this idempotent\" flag; don't invent one). A\n   handler may take an optional third argument `(input, deps, ctx)` and read\n   `ctx.idempotencyKey` (`string | undefined`) if it needs exactly-once\n   beyond one instance's memory; most don't. Locally and in tests nothing is\n   provisioned, so `serve()` passes every call through: never supply a key\n   in test inputs.\n\n## Raw HTTP connections\n\nFor a server Composer does not generate (a reverse proxy's upstreams, a\nNext.js app, a static file server), import `rawHttp` and `rawHttpContract`\nfrom `@prisma/composer/http`. The provider declares\n`expose: { http: rawHttpContract }`; the caller declares\n`deps: { site: rawHttp() }`; the Module wires\n`provision(gateway, { deps: { site: siteRef.http } })`. `gateway.load().site`\nis `{ url, fetch(path, init) }`, where `fetch` resolves `path` against `url`.\nThe client never leaves its provider's origin by itself: `fetch` rejects a\npath that resolves to another host (`//other.example/x`, an absolute URL), and\nreturns redirects to the caller instead of following them, unless `init` sets\n`redirect: 'follow'`.\n\nComposer checks only that the provider declared an HTTP port: TypeScript and\nLoad reject a bare service ref or a port of another kind. The caller is\nresponsible for knowing the provider's paths, methods and headers. Raw HTTP\nhas no service key, retry or idempotency key; authentication, if needed, is\nthe app's. Each dependency shows in the application topology as a call, also\nthrough module boundaries; a URL passed as `input` (`serviceOrigin()`)\ndoes not, so declare a dependency for every service you call. The auth\nmodule's `api` port is a raw HTTP port: wire it with `rawHttp()`.\n\n**Public URLs.** A service is reachable from the internet only through a\npublic URL the app declares:\n`provision(publicUrl({ id: 'site', url, target: web.http }))`, where `id`\nsets the address (`shop.site`) and changing it replaces the URL, and where\n`web` exposes `http: rawHttpContract` (an RPC interface as `target` fails\n`tsc`; a module's forwarded HTTP interface lands on the service inside it).\n`url` is required and is one of two strategies: `publicUrl.prismaBuild()`\nserves at the service's `prisma.build` hostname and creates nothing;\n`publicUrl.hostname('shop.com')`, or the bare string `'shop.com'`, attaches\nthat hostname to the service as a custom domain. One hostname per public URL.\nA per-environment `url` is a `resolve()` value returning either strategy or a\nstring; anything else fails deploy and dev before any of the app's resources\nare created or changed. Before\na deploy names a hostname, the TXT record `_prisma-verification.<hostname>`\nand a CNAME to the platform must be published, or the deploy fails with the\nplatform's error (`domain-ownership-required` for the TXT record); don't\nwork around it, publish the records or use `publicUrl.prismaBuild()` there. A\nchange from a serving hostname to one that is not ready fails the deploy and\nthe old hostname keeps serving. `prisma dev` ignores a named hostname and\nwarns once per public URL that names a hostname. A service with no public URL is still reachable at\nits `prisma.build` hostname today.\n\n## Builds are yours\n\nYou build, the framework assembles. For a plain server process, `entry`\npoints at the ESM file your build produced. By default\n(`dependencies: 'bundled'`) deploy copies exactly that and never ships\n`node_modules`, so everything except runtime built-ins (`bun`, `bun:*`,\n`node:*`) must be inlined, or it fails at boot, not at deploy. Rules that\nbite:\n\n1. **Two services in one package means two separate builds**, one per entry.\n   A single multi-entry build splits shared code into a chunk neither output\n   contains.\n2. **A directory build uses `dir` + `entry`** (`dir` relative to the service\n   module, `entry` a file inside `dir`; `../` is an error). The tree is\n   copied verbatim, so the server must resolve siblings against\n   `import.meta.url`, not the working directory. The tree must contain no\n   symlinks: the packager rejects them, names the link, and assembly fails.\n3. **A build that leaves packages external sets `dependencies: 'external'`**\n   (either form). Deploy then traces `entry` and stages the installed\n   packages it imports, which can take minutes on a large build. Astro's Node\n   adapter, SvelteKit's `adapter-node` and React Router's server build leave\n   packages external by default. The default, `'bundled'`, copies exactly\n   what was built. A service that fails to start with\n   `Cannot find package 'x'` needs `x` bundled, or `dependencies: 'external'`.\n4. **Next.js**: `next build` with `output: 'standalone'` is the whole build;\n   `nextjs({ module, appDir })` names the app root. Any page or action that\n   calls `load()` needs `export const dynamic = 'force-dynamic'`, because\n   the runtime environment variables don't exist at build time and Next ignores\n   runtime env for prerendered routes. `prisma dev` needs no build for it: it\n   runs `next dev` instead (see Local development).\n5. **Always build before `deploy`, and before `dev` for a service without a\n   dev server.** Neither builds for you. `node({ ..., dev: ['bun', '--watch',\n   'server.ts'] })` gives a node service a dev server: `prisma dev` runs that\n   command (in the authoring module's directory, nothing appended; it must\n   listen on `PORT`) instead of the built `entry`.\n\nDeploy configuration is the `composer` section of `prisma.config.ts`, and\nnothing else. It names the entry module, the file whose default export is the\napp root (`entry`, relative to the config file; `--entry <path>` overrides it\nfor one run), and registers extensions (`prismaCloud()`, `nodeBuild()`,\n`nextjsBuild()` when the app has a Next.js service) and the deploy-state\nbackend (`prismaState()`):\n\n```ts\n// prisma.config.ts\nimport { defineConfig as composer } from '@prisma/composer/config';\nimport { nodeBuild } from '@prisma/composer/node/control';\nimport { prismaCloud, prismaState } from '@prisma/composer-prisma-cloud/control';\nimport { definePrismaConfig } from 'prisma/config';\n\nexport default definePrismaConfig({\n  composer: composer({\n    entry: './module.ts',\n    extensions: [prismaCloud(), nodeBuild()],\n    state: prismaState(),\n  }),\n});\n```\n\nThe commands find `prisma.config.ts` from the directory they run in, walking up\nto the repository root; the nearest file that declares `composer` wins, and its\nsection is used whole, never merged key by key. Only `entry`, `extensions` and `state`\nare allowed; any other key is an error. App code never imports the file.\n\nA separate `prisma-composer.config.ts` is no longer read, and the old setup is\nrefused, never silently ignored: `CONFIG.SECTION_MISSING` when no loaded\n`prisma.config.ts` declares a `composer` section, `CONFIG.FIELD_RETIRED` when\nthe section still has `configPath`, `CONFIG.FILE_RETIRED` when a\n`prisma-composer.config.*` sits next to the declaring `prisma.config.ts`; all\nthree under the CLI's `CLI.CONFIG_SECTION_INVALID`. `SECTION_MISSING` is fixed by\nadding the `composer` section to `prisma.config.ts`. `FIELD_RETIRED` and\n`FILE_RETIRED` are fixed by moving the old file's `extensions` and `state` into\nthe section, then removing `configPath` or deleting the old file.\n`@prisma/composer-cli/family` no longer exports `ComposerSection`; the\nsection's type is `PrismaAppConfig` from `@prisma/composer/config`.\n\n## Databases and migrations\n\nTwo kinds of Postgres dependency:\n\n1. **`rawPostgres()`**: the binding is `{ url }` and the app owns its client.\n2. **`postgres(...)`**: a Prisma-ORM-typed database. The binding is\n   `{ url, connection, client, clientWith }` (ADR-0040, ADR-0055): the raw\n   connection URL, the connection pool, the typed client Composer constructs\n   from your data contract lazily on first access, and `clientWith(options)`,\n   which builds a typed client with Prisma ORM runtime options. Queries go\n   through `binding.client` and are compile-time checked. Both `postgres` and `dataContract` import from\n   `@prisma/composer-prisma-cloud/orm`, not the package root. The app's\n   `package.json` lists `@prisma/orm-postgres` and the four ORM packages it\n   is built from (`@prisma/orm-framework`, `@prisma/orm-family-sql`,\n   `@prisma/orm-target-postgres`, `@prisma/orm-toolchain`), all at the exact\n   version Composer names, plus `pg`, `@types/pg` and `temporal-polyfill`; the ORM's packages are\n   peers of each other, so the app's list decides the one copy installed. One\n   `dataContract`-wrapped value (emitted from `contract.prisma` by\n   `prisma contract emit`) is referenced by both the dependency end\n   (`deps: { db: postgres(catalogData) }`) and the resource end, which also\n   names the `prisma.config.ts` path so the deploy's migration step can\n   reload the emitted `contract.json` and find `migrations/`, and the required\n   `targetRef`, the ref every deploy migrates the database to (below).\n   Client options never go on the dependency declaration. A contract that\n   uses an extension type (for example `pgvector.Vector(length: 1024)`)\n   needs the pack's runtime extension when the client is built:\n   `export const orm = db.clientWith({ extensions: [pgvectorRuntime] })`,\n   where `pgvectorRuntime` is the default export of\n   `@prisma/orm-extension-pgvector/runtime`; other runtime options, such as\n   `middleware`, go in the same object. Install the pack at exactly the\n   `@prisma/orm-postgres` version: the pack names the ORM's packages as\n   peers at its own version, so with a mismatch npm refuses the install and\n   pnpm, Yarn and Bun only warn, and the client rejects the extension's\n   values. Composer never looks extensions up itself;\n   with `binding.client` instead, the first access throws\n   \"Contract requires extension pack(s) 'pgvector'\".\n\n**Every deploy and every `prisma dev` converge runs the ORM's migrate** for each ORM database: the equivalent of `prisma db migrate --to <targetRef>` against the database Composer provisioned, whether or not anything changed. The ORM decides what is pending; with nothing pending it applies nothing and no service is redeployed. A deploy only migrates: it never runs `db update`, `db init` or `db sign`, and never creates schema from the contract.\n\n`targetRef` is required on the resource end. It takes a ref name (a committed `migrations/app/refs/<name>.json`) or `@contract`, the contract this commit emits. An app that deploys to environments computes it from the environment name:\n\n```ts\npostgres({\n  name: 'database',\n  contract: catalogData,\n  config: './prisma.config.ts',\n  targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n});\n```\n\n`@empty`, `@db`, a contract hash or a migration directory name is refused. A Module that provisions its own ORM database targets `'@contract'`: its migrations ship inside its package, so the app cannot commit refs for it, and a Module that copies the app's `resolve([environment.name], …)` pattern makes the app's first `production` deploy fail with the ORM's `MIGRATION.UNKNOWN_REF`. The `prisma.config.ts` names no database (no `db.connection`); the deploy passes the ORM the one it provisioned. Per-PR environments need one ref rule for all of them (such as a shared `preview` ref, or `'@contract'`); an environment with no ref file fails with the ORM's `MIGRATION.UNKNOWN_REF`.\n\nThe loop for every schema change, including a new database's first schema:\n\n1. Edit `contract.prisma`.\n2. `prisma contract emit` regenerates `contract.json` + `contract.d.ts`.\n3. `prisma migration plan --name <slug>` authors the migration (on an empty graph this authors the baseline).\n4. `prisma migration ref set <environment> <newest migration directory>` for each environment the change should reach.\n5. Commit `migrations/`, then deploy. A fresh database replays the whole path from empty.\n\nUnder `prisma dev`, plan a migration for each contract change: a local database moved with `prisma db update` to a contract no migration ends at is refused on every rebuild with the ORM's `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, although it is at the target, until a migration ending at that contract exists. This is a current Prisma ORM bug. Plan a migration that ends at the contract; do not reset the database or edit its contract signature to get past it.\n\nA deploy moves the database to its ref, not to the code: a ref may trail the contract on purpose, and moving it is the user's job in the pull request that changes the contract. Every service that uses the database deploys only after its migration completes: a failed migration means the new code does not ship. The old code serves against the new schema until the new deployment is live, so keep each migration compatible with the code it replaces.\n\nA failed migration fails the deploy with one Composer line, `<address>: Composer ran prisma db migrate --to <targetRef> on this database.`, and the ORM's own structured error under it: code, summary, `why`, next actions and docs link. Follow the ORM's advice; Composer adds none. Its advised commands repeat `--to <targetRef>`. Composer raises its own errors only before the ORM runs: the emitted contract `prisma.config.ts` names is missing or unreadable, has no storage hash, or differs from the declared `dataContract(...)` value.\n\nWhen a ref declares policies that differ from the database's (a new database has the ORM's defaults), every deploy fails with the ORM's `MIGRATION.POLICY_MISMATCH` and changes nothing. A deploy never changes policies. Applying them is a decision for whoever administers the database, made by hand: `prisma db migrate --to <ref> --permit-policy-change --db <url>`, with the URL from the Prisma Console, from `prisma postgres connection create @<environment>:<address> --name <name> --json` (its output holds a secret shown once), or locally from `prisma dev url <address>` while `prisma dev` runs. A ref's policies are the `policies` field of its JSON file, edited by hand: the pinned Prisma ORM version has no command for them. Do not run that command, or edit a ref's policies, to get a deploy past the refusal: say what the ORM reported and leave the decision to whoever administers the database.\n\nUpgrading an app from before `targetRef` was required: add `targetRef` to each `postgres({ ... })`, commit a ref per deployed environment with `prisma migration ref set <environment> <newest migration directory>`, and remove placeholder `db.connection` entries from `prisma.config.ts`. See `examples/orm-demo` for an app and `examples/store/modules/catalog` for a Module.\n\n## Deploy model: converge, don't script\n\nDeploy compares the declared topology against recorded deploy state and\napplies only the difference. Re-deploying with nothing changed is a no-op;\nremoving a node removes its deployed resource. `prisma deploy` needs a signed-in\nidentity: `prisma auth login` stores a session on a developer machine, and\n`PRISMA_SERVICE_TOKEN` overrides it in CI. The `/control` operations, and so\na destroy script, never use that session: `deploy` and `destroy` read\n`PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` from environment variables (both\nin the workspace's Console settings); `dev` and `log` read neither. The\n`prisma` bin starts under Node; use `pnpm prisma …` or `npx prisma …` by\ndefault. Composer starts Alchemy with Node, but Alchemy's launcher moves to\nBun under `bunx` or `bun run`: `bunx prisma` gives Node then Bun,\n`bunx --bun prisma` Bun then Bun. When the modules `module.ts` imports use\nBun APIs, `bun node_modules/prisma/dist/prisma.js deploy` from a\nshell runs `prisma` under Bun with Alchemy on Node.\n\nA node's **address** is the app name followed by the provision ids down to it\n(`shop.auth.api`); the root's address is the app name, or `--name` when given.\nEvery surface uses this full form: `serviceOrigin('shop.api')`,\n`prisma dev url shop.api`, the `log` operation's `address`, errors and reports.\nServices, managed Postgres databases and buckets record their address as\n`logicalId` on their Branch. Console uses that address to match topology nodes\nto resources and compare them with main. Existing environments receive the\nidentity on their next deploy. A deploy interrupted after creating a resource\nresumes on the next deploy, which finds the resource by its address. Local dev\ncreates no platform rows. Changing a node's address (its name without an\nexplicit `id`, its `id`, or its module) makes a new entity: the next deploy\ndeletes the old rows, and a database's or bucket's data with them.\n\n**Progress.** `prisma deploy` prints each step as it starts and finishes, with its duration (`✔ assemble web (3m 42s)`), and ends with the real total (`Deployed <app> to <environment> in 5m 25s.`). Steps: load config and app, one assemble per service, connect to project and branch, check environment variables, plan and apply (one step: alchemy does both in one process), record result. A slow assemble is usually a Node service with `dependencies: 'external'`, whose runtime dependencies are being traced. With `--json`, each step is a `step-started`/`step-finished` line whose `data` holds `durationMs` plus whatever the build adapter or deploy target reported; those extra fields vary, so don't parse them as a stable format. The `deploy` operation's `onEvent` receives the same steps, its result's `durationMs` is the total, and its `summary.findings` lists the platform variables with no value.\n\n**Environments.** An environment is a named place the app runs, chosen with\n`--environment` at deploy time, never written in the topology. The identical\ngraph deploys everywhere. `prisma deploy` without the flag deploys\n`production`; `prisma dev` runs as `dev` and takes no flag. On the Prisma Cloud\ntarget, a Prisma App is one Project and an environment is a Branch of it, with\nits own running services, its own empty database, its own configuration:\n`production` is the Project's default Branch, any other name is the Branch\nwith that `gitName`, created if absent. The default Branch's own name (such as\n`main`) is refused, since it would be production under a second name. A name\nmust be a valid git ref name, or the deploy fails with\n`DEPLOY.ENVIRONMENT_INVALID`.\n\n**Seeing what is deployed.** `prisma deploy list [--environment <name>]` lists every\nnode of the topology the last deploy recorded, with its kind, platform ID and,\nfor a service, its URL; the root's ID is the Project's, and a module has none.\nIt finds the app as `deploy` does (`--name`, `--entry`) and fails with\n`DEPLOY.TARGET_NOT_FOUND` when the environment has nothing deployed. Piped:\naddress, kind, platform ID, URL per line; `--json`: `[{ address, kind, platformId, url }]`. It needs\na `prisma` CLI release that includes it; 8.0.0-rc.26 does not.\n\n**Using an address with platform commands.** A `prisma project|service|postgres|bucket`\ncommand takes `@<environment>:<address>` in place of the platform ID\n(`prisma service logs @pr-42:shop.api`); no environment means production. It\nacts on that one row. Deleting a service, database or bucket this way leaves\nthe deploy state alone, so the next deploy recreates it; deleting the Project\nremoves its deploy state too. It needs a `prisma` CLI release newer than\n8.0.0-rc.28.\n\n**Removing an app** with every environment is a platform command: find the Project\nid with `prisma project list`, then `prisma project delete <id> --confirm <id>`,\nand check `prisma project list` again to confirm it is gone. It works while the\napp's services are running. Don't write a script for this.\n\n**Destroying one environment** is the `destroy` operation, and its\n`environment` is required, even for production; it has no default and a call\nwithout it fails with `DEPLOY.ENVIRONMENT_REQUIRED`:\n\n```ts\nawait destroy({ entry: 'module.ts', environment: 'pr-42', config });\nawait destroy({ entry: 'module.ts', environment: 'production', config });\n```\n\nDestroying any environment other than production\ndeletes its Branch after removing its resources. Destroying production\nremoves only the resources inside the production Branch, never the Branch\nitself directly; once the Project is empty it is deleted too, and that\ndeletion takes the production Branch with it. A Project still holding\nanother environment's resources is kept. Destroy never creates anything:\ndestroying a\nnever-deployed environment fails rather than standing one up.\n\n**Upgrading from stages.** `--stage <name>` is now `--environment <name>`;\n`destroy({ target })` is now `destroy({ environment })`, with production as\n`'production'`; the `--report` file's `stage` field is now `environment`, at\n`version` 2. Keep `@prisma/composer-prisma-cloud` on the same Composer version\nas the Composer that runs the deploy. An older extension would read every\nenvironment as production, so deploy and destroy refuse it with\n`DEPS.EXTENSION_INCOMPATIBLE`.\n\n**The engine underneath is alchemy.** Convergence is executed by [alchemy](https://alchemy.run), a third-party infrastructure-as-code engine that arrives as an ordinary, exactly-pinned npm dependency of `@prisma/composer` (2.0.0-beta.87 at this library version). Your code never imports or configures it; consult alchemy's own docs for the engine itself. What matters operationally:\n\n`prisma deploy` runs alchemy inside the `prisma` process through alchemy's programmatic API: no generated file and no child process. Its progress prints as one step per resource, and a failure is `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, with credentials redacted, or `DEPLOY.INTERRUPTED` after Ctrl-C, which releases the environment's lease. `prisma dev` runs alchemy in the `prisma` process too, each converge in a new worker thread, so an edit to your app definition applies on the next rebuild. Three kinds of edit need `prisma dev` restarted, and it says so: adding or removing a node, making the root pass on an input field it did not pass on at start, and changing which platform variables the app reads. The `destroy` operation runs alchemy inside the process that calls it, the same way as deploy. The alchemy that runs is the one installed beside the app's `@prisma/composer`, so the app needs no direct `alchemy` dependency, and no global Alchemy installation is needed.\n\n1. No command writes a stack file or starts the alchemy CLI. An engine failure surfaces as `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, credentials redacted, for deploy and destroy alike. A structured error, such as the ORM's, keeps its code, `why`, next actions, docs link and the structured error it was caused by: they print in the CLI's error layout, and its next actions stay `{ kind, label, command?, … }` objects, and are data in `failure.meta.reasons`, in the `--report` file's `failure.reasons` and on `prisma dev`'s `converge-failed` events. Only the copy sent to the Prisma Cloud build is shortened, to 5000 characters, by cutting the middle of the longest `why`.\n2. Destroy runs the same preparation as deploy, assembly included, so **an app must be built before it can be torn down**.\n3. alchemy is why the `effect` pin exists: it resolves the `effect`\n   constellation, and a hoisted newer `effect` halts every command (failure\n   mode 1 below).\n\n**The deploy report** ends with the app's own topology: authored names, the\nplatform resource each became, and public URLs. Read ids out of it rather\nthan hunting in the Console. A URL appears only where the address is\ngenuinely public: a service prints one, a database never does, and a\nnode whose product is secret material reports no resource line at all.\n\n**Connection contract refusals.** A connection declares the values it needs\nby name; a producer that omits one fails the deploy, naming the edge, the\nparam, and what the producer did supply:\n\n```text\nConnection input \"auth.db\" declares param \"url\", but its producer \"db\" did not\nsupply it — the producer's outputs carry [host].\n```\n\nThis is a deploy-time refusal, not a broken deploy, and it can appear on an\napp whose code didn't change (the gap used to pass silently as `undefined`\nand crash the consumer at boot). Fix whichever end is wrong; don't mark the\nparam `optional` unless absent really is legal. Only reachable if you\nauthored the connection or an extension on one side.\n\n**Driving deploys from code.** A script imports only\n`@prisma/composer/control`; the extensions' `/control` entries are imported\nonly by `prisma.config.ts` (ADR-0017). `@prisma/composer/control` exposes typed\n`deploy`, `destroy`, `dev`, `devUrl`, `devStop`, and `log` returning structured\nresults; `prisma deploy`, `prisma dev`, `prisma dev url` and `prisma dev stop`\nrender `deploy`, `dev`, `devUrl` and `devStop`. Each takes\na required `config: { value, file }` (`ComposerConfigSource`): the `composer`\nexport of your `prisma.config.ts` and that file's path; a relative `file`\nresolves against `cwd`, so build it from `import.meta.url`. The operations\nnever look for a config file, but refuse what the CLI refuses before any work\nstarts (`CONFIG.FIELD_UNKNOWN` for the whole export instead of its `composer`\nproperty, `CONFIG.FILE_RETIRED`, `CONFIG.FILE_MISSING`); the deploy re-imports\n`file`, so `value` must be its `composer` export. Failures come back as\n`{ ok: false, failure }` with a dotted `failure.code` from a closed registry\n(e.g. `ASSEMBLE.BUILD_FAILED`, `DEPLOY.ENGINE_FAILED`,\n`DEPS.EXECUTOR_UNLOADABLE`); branch on the code, not the message. A\nnon-structured rejection out of an operation is a bug in composer, not an\nexpected failure.\n\n## Local development\n\n`prisma dev` runs the whole app on this machine, wired as it deploys,\nagainst local emulators. No cloud credentials are needed or read. Concepts\nthat surprise:\n\n1. It runs the same pipeline as deploy, so **build first**, exactly like\n   deploy, except for a service that runs a dev server (below). It watches\n   built output and restarts a service when its build changes.\n   **Dev servers.** A service whose build adapter declares one runs it in\n   place of its artifact, with no flag: every `nextjs()` service runs\n   `next dev` (the app's own `next`, resolved from `appDir`), and a `node()`\n   service runs its `dev` argv when it has one. It runs on the service's\n   instance and URL, with the deployment's environment variables: `service.load()`,\n   `service.input()` and `service.port()` work exactly as deployed, so never add a\n   `process.env` fallback for plain `next dev`. It also keeps the shell's\n   environment variables; Composer's values win. `dev` prints ``<address>: runs\n   `<command>` in <dir>`` before the app comes up and streams the dev\n   server's output prefixed `[<address>]` (other services' logs are not\n   streamed). Source edits are the dev server's own hot reload; `dev` watches\n   the entry and every app file it imports, applies an edit to them on the\n   next rebuild (adding or removing a node, passing on a new root input field, or changing which platform variables the app reads needs `dev` restarted, and it says so), and restarts a dev server only when its environment variables changed\n   (``<address>: its environment changed; `<command>` restarted``). It has no\n   terminal (no colours or key shortcuts). The standalone build is not run\n   locally, so a standalone-only\n\n<!-- [TRUNCATED AT 50KB] -->"},"files":{".agents/rules/README.md":"# Agent Rules Index\n\nCurated rules for agents and developers — quick, actionable guidance.\n\n## Canonical home & sync\n\nEvery rule has a single canonical home: `.agents/rules/<name>.mdc` — the only\ngit-tracked copy. Rule files must use the `.mdc` extension; the harnesses load\n`.mdc` only, so a `.md` rule is silently dead (`pnpm lint:rules:symlinks`\nrejects them). The `.cursor/rules/` and `.claude/rules/` trees are git-ignored\npresentation mirrors containing nothing but relative symlinks back into\n`.agents/rules/`.\n\n```bash\npnpm rules:sync           # Consolidate stray rules + (re)generate the symlink trees\npnpm lint:rules:symlinks  # Fail if a tree is out of sync with canonical (runs in CI)\n```\n\n`rules:sync` also runs from `prepare`, so `pnpm install` rebuilds the trees\nautomatically. **Add or edit rules at the canonical path** (`.agents/rules/`);\na rule dropped only into `.cursor/rules` is git-ignored and will be lost.\n",".claude/agents/domain-modeler.md":"---\nname: domain-modeler\ndescription: Research and write DDD-style domain models for external systems (e.g. Cloudflare/Wrangler) as structured docs under docs/design/04-inspirations/.\ntools: Read, Write, Bash, WebFetch\ncolor: blue\nmodel: inherit\n---\n\nYou are a domain modeling and domain research specialist.\n\nYour job is to take a target system (product + tooling) and produce a **DDD-style written domain description**: ubiquitous language, core concepts, relationships, user workflows, and behavioral/execution flows — written as a small library of docs that can be reused in later design discussions.\n\nThis agent is designed to be “set loose”: you do the research, make reasonable modeling calls, and leave behind a coherent, cross-linked documentation set.\n\n## Core responsibilities\n\n1. **Capture ubiquitous language**\n   - Build a glossary of the system’s key terms as *users* use them (and note internal/mechanical terms separately).\n   - Prefer the product’s native vocabulary over invented terms; call out synonyms and overloaded words.\n\n2. **Model the domain (things + relationships + behaviors)**\n   - Produce a conceptual domain map (relationships between the core concepts).\n   - Enumerate the primary operations (“verbs”) on those concepts.\n   - Document behavioral relationships: what triggers what, what depends on what, what must be true.\n\n3. **Model the user mental model + UX workflows**\n   - Document the user’s day-to-day mental model.\n   - Capture the common workflows (happy paths + sharp edges) as step-by-step flows.\n\n4. **Separate stable research from evolving takeaways**\n   - Keep “how the system works” relatively stable in research docs.\n   - Keep “what Prisma Composer should do because of it” in a separate takeaways doc that can evolve.\n\n5. **Be explicit about uncertainty**\n   - Track open questions and assumptions at the end of each doc.\n   - When unsure, write the best current model and clearly label it as an assumption.\n\n## Workflow (every time)\n\n### Step 0: Anchor on the repo’s doc system (read-first)\n\nRead:\n- `docs/design/README.md`\n- `docs/design/99-process/README.md`\n- `docs/design/04-inspirations/README.md`\n- Any existing inspiration docs for the target system (if present)\n\nGoal: match the house style and keep outputs discoverable and consistent.\n\n### Step 1: Define scope + output location\n\nDecide:\n- The **target system name** (e.g. “Cloudflare”, “Cloudflare Wrangler”, “Cloudflare Workers + Wrangler”).\n- What is in-scope vs out-of-scope (product surfaces, runtime primitives, billing/account, etc.).\n\nCreate (or update) a research library folder:\n- `docs/design/04-inspirations/<System>/`\n\nIf a single-file inspiration note already exists (e.g. `docs/design/04-inspirations/cloudflare.md`), treat it as a short overview and keep the detailed model in the folder.\n\n### Step 2: Research (prefer primary sources)\n\nUse official docs and product references first (then reputable secondary sources).\n\nWhile researching, continuously extract:\n- **Nouns** (things): resources, identifiers, configuration objects, runtimes, projects, accounts.\n- **Verbs** (operations): create/update/deploy/bind/route/observe/debug/rollback.\n- **Rules** (invariants): what must always hold; what configurations are invalid; what is “the unit of deployment”.\n- **Workflows** (UX): “day 1” setup, deploy, local dev, preview/staging, rollout, rollback, debugging.\n- **Control-plane vs runtime split** (if applicable): author-time/build-time/deploy-time vs runtime execution.\n\n### Step 3: Write the DDD artifacts (structured library)\n\nProduce this set of files (mirrors the `TanStack/` pattern):\n\n- `README.md`\n  - what this library covers, what to read, key sources\n- `glossary.md`\n  - terms + definitions; note “user-facing?”; include synonyms/aliases\n- `domain-map.md`\n  - a conceptual relationship map (use Mermaid where useful)\n- `operations.md`\n  - the primary operations on core concepts (CRUD + lifecycle + operational verbs)\n- `user-domain.md`\n  - the user mental model and how it maps to underlying mechanics\n- `execution-flows.md`\n  - the “always happening” flows (deploy lifecycle, routing, local dev loops, etc.)\n- `takeaways-for-prisma-composer.md`\n  - explicitly evolving: what Prisma Composer should emulate/adapt, plus design questions raised\n\nWriting guidelines:\n- Prefer **small, scannable** docs over one huge one.\n- Keep each doc focused; cross-link instead of duplicating.\n- Include **1–2 diagrams** when they materially improve comprehension.\n- Keep a short **Open questions / assumptions** section at the bottom of each file.\n\n### Step 4: Integrate with the inspiration index\n\nUpdate `docs/design/04-inspirations/README.md` to list the new folder (or new key docs) so the library is discoverable.\n\n### Step 5: Finish with a “what changed” summary\n\nWhen done, summarize:\n- Files created/updated\n- Key domain concepts discovered (5–10 bullets)\n- The most important workflows (3–5 bullets)\n- Open questions / unknowns (explicit list)\n\n## Output expectations\n\nWhen asked to “model Cloudflare + Wrangler”, a successful output usually includes:\n\n- A new folder: `docs/design/04-inspirations/Cloudflare/` (or similarly named)\n- The standard library docs listed above, cross-linked and consistent\n- A takeaways doc that cleanly separates “research facts” from “Prisma Composer implications”\n\n## Guardrails\n\n- Do **not** change Prisma Composer’s core domain docs (`docs/design/03-domain-model/`, `docs/design/10-domains/`) unless the user explicitly asks you to translate research into Prisma Composer design changes.\n- Do **not** create ADRs unless the user explicitly indicates a decision has been made.\n- Prefer documenting what you can verify; label inferred models as assumptions.\n","AGENTS.md":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","CLAUDE.md":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## A layer does not know what is built on it\n\nThis is an\n[architectural principle](docs/design/01-principles/architectural-principles.md#a-layer-does-not-know-what-is-built-on-it),\nand it is the one agents most often break without noticing. It comes up as a\nshortcut: code in a higher layer needs a value, the only thing it holds is a\nlower layer's interface, and one more member on that interface is the shortest\nway. Stop there and read the principle.\n\nIf the member would exist for one kind of Connection, one deployment target or\none Module, do not build it. Do not offer it to the operator as an option\neither, whether the idea is yours or a subagent's: the operator would have to\ncatch the problem themselves, and the gap in the design you found would go\nunreported. Report the gap instead: what the higher layer needs, and why\nnothing that exists carries it.\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc":"---\ndescription: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples\nglobs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx\n---\n\n# Convex guidelines\n## Function guidelines\n### New function syntax\n- ALWAYS use the new function syntax for Convex functions. For example:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\nexport const f = query({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n    // Function body\n    },\n});\n```\n\n### Http endpoint syntax\n- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:\n```typescript\nimport { httpRouter } from \"convex/server\";\nimport { httpAction } from \"./_generated/server\";\nconst http = httpRouter();\nhttp.route({\n    path: \"/echo\",\n    method: \"POST\",\n    handler: httpAction(async (ctx, req) => {\n    const body = await req.bytes();\n    return new Response(body, { status: 200 });\n    }),\n});\n```\n- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.\n\n### Validators\n- Below is an example of an array validator:\n```typescript\nimport { mutation } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport default mutation({\nargs: {\n    simpleArray: v.array(v.union(v.string(), v.number())),\n},\nhandler: async (ctx, args) => {\n    //...\n},\n});\n```\n- Below is an example of a schema with validators that codify a discriminated union type:\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n    results: defineTable(\n        v.union(\n            v.object({\n                kind: v.literal(\"error\"),\n                errorMessage: v.string(),\n            }),\n            v.object({\n                kind: v.literal(\"success\"),\n                value: v.number(),\n            }),\n        ),\n    )\n});\n```\n- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport const exampleQuery = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n      console.log(\"This query returns a null value\");\n      return null;\n  },\n});\n```\n- Here are the valid Convex types along with their respective validators:\nConvex Type  | TS/JS type  |  Example Usage         | Validator for argument validation and schemas  | Notes                                                                                                                                                                                                 |\n| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Id          | string      | `doc._id`              | `v.id(tableName)`                              |                                                                                                                                                                                                       |\n| Null        | null        | `null`                 | `v.null()`                                     | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead.                             |\n| Int64       | bigint      | `3n`                   | `v.int64()`                                    | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers.                                                                                              |\n| Float64     | number      | `3.1`                  | `v.number()`                                   | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings.                                                                      |\n| Boolean     | boolean     | `true`                 | `v.boolean()`                                  |\n| String      | string      | `\"abc\"`                | `v.string()`                                   | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8.                                                         |\n| Bytes       | ArrayBuffer | `new ArrayBuffer(8)`   | `v.bytes()`                                    | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types.                                                     |\n| Array       | Array       | `[1, 3.2, \"abc\"]`      | `v.array(values)`                              | Arrays can have at most 8192 values.                                                                                                                                                                  |\n| Object      | Object      | `{a: \"abc\"}`           | `v.object({property: value})`                  | Convex only supports \"plain old JavaScript objects\" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with \"$\" or \"_\". |\n| Record      | Record      | `{\"a\": \"1\", \"b\": \"2\"}` | `v.record(keys, values)`                       | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with \"$\" or \"_\".                                                               |\n\n### Function registration\n- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.\n- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.\n- You CANNOT register a function through the `api` or `internal` objects.\n- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.\n- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.\n\n### Function calling\n- Use `ctx.runQuery` to call a query from a query, mutation, or action.\n- Use `ctx.runMutation` to call a mutation from a mutation or action.\n- Use `ctx.runAction` to call an action from an action.\n- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.\n- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.\n- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.\n- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,\n```\nexport const f = query({\n  args: { name: v.string() },\n  returns: v.string(),\n  handler: async (ctx, args) => {\n    return \"Hello \" + args.name;\n  },\n});\n\nexport const g = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const result: string = await ctx.runQuery(api.example.f, { name: \"Bob\" });\n    return null;\n  },\n});\n```\n\n### Function references\n- Function references are pointers to registered Convex functions.\n- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.\n- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.\n- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.\n- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.\n- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.\n\n### Api design\n- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.\n- Use `query`, `mutation`, and `action` to define public functions.\n- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.\n\n### Pagination\n- Paginated queries are queries that return a list of results in incremental pages.\n- You can define pagination using the following syntax:\n\n```ts\nimport { v } from \"convex/values\";\nimport { query, mutation } from \"./_generated/server\";\nimport { paginationOptsValidator } from \"convex/server\";\nexport const listWithExtraArg = query({\n    args: { paginationOpts: paginationOptsValidator, author: v.string() },\n    handler: async (ctx, args) => {\n        return await ctx.db\n        .query(\"messages\")\n        .withIndex(\"by_author\", (q) => q.eq(\"author\", args.author))\n        .order(\"desc\")\n        .paginate(args.paginationOpts);\n    },\n});\n```\nNote: `paginationOpts` is an object with the following properties:\n- `numItems`: the maximum number of documents to return (the validator is `v.number()`)\n- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)\n- A query that ends in `.paginate()` returns an object that has the following properties:\n- page (contains an array of documents that you fetches)\n- isDone (a boolean that represents whether or not this is the last page of documents)\n- continueCursor (a string that represents the cursor to use to fetch the next page of documents)\n\n\n## Validator guidelines\n- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.\n- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.\n\n## Schema guidelines\n- Always define your schema in `convex/schema.ts`.\n- Always import the schema definition functions from `convex/server`.\n- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.\n- Always include all index fields in the index name. For example, if an index is defined as `[\"field1\", \"field2\"]`, the index name should be \"by_field1_and_field2\".\n- Index fields must be queried in the same order they are defined. If you want to be able to query by \"field1\" then \"field2\" and by \"field2\" then \"field1\", you must create separate indexes.\n\n## Typescript guidelines\n- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.\n- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:\n```ts\nimport { query } from \"./_generated/server\";\nimport { Doc, Id } from \"./_generated/dataModel\";\n\nexport const exampleQuery = query({\n    args: { userIds: v.array(v.id(\"users\")) },\n    returns: v.record(v.id(\"users\"), v.string()),\n    handler: async (ctx, args) => {\n        const idToUsername: Record<Id<\"users\">, string> = {};\n        for (const userId of args.userIds) {\n            const user = await ctx.db.get(\"users\", userId);\n            if (user) {\n                idToUsername[user._id] = user.username;\n            }\n        }\n\n        return idToUsername;\n    },\n});\n```\n- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.\n- Always use `as const` for string literals in discriminated union types.\n- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`\n- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`\n- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.\n\n## Full text search guidelines\n- A query for \"10 messages in channel '#general' that best match the query 'hello hi' in their body\" would look like:\n\nconst messages = await ctx.db\n  .query(\"messages\")\n  .withSearchIndex(\"search_body\", (q) =>\n    q.search(\"body\", \"hello hi\").eq(\"channel\", \"#general\"),\n  )\n  .take(10);\n\n## Query guidelines\n- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.\n- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.\n- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.\n- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.\n### Ordering\n- By default Convex always returns documents in ascending `_creationTime` order.\n- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.\n- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.\n\n\n## Mutation guidelines\n- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })`\n- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })`\n\n## Action guidelines\n- Always add `\"use node\";` to the top of files containing actions that use Node.js built-in modules.\n- Never use `ctx.db` inside of an action. Actions don't have access to the database.\n- Below is an example of the syntax for an action:\n```ts\nimport { action } from \"./_generated/server\";\n\nexport const exampleAction = action({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        console.log(\"This action does not return anything\");\n        return null;\n    },\n});\n```\n\n## Scheduling guidelines\n### Cron guidelines\n- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.\n- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.\n- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,\n```ts\nimport { cronJobs } from \"convex/server\";\nimport { internal } from \"./_generated/api\";\nimport { internalAction } from \"./_generated/server\";\n\nconst empty = internalAction({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    console.log(\"empty\");\n  },\n});\n\nconst crons = cronJobs();\n\n// Run `internal.crons.empty` every two hours.\ncrons.interval(\"delete inactive users\", { hours: 2 }, internal.crons.empty, {});\n\nexport default crons;\n```\n- You can register Convex functions within `crons.ts` just like any other file.\n- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file.\n\n\n## File storage guidelines\n- Convex includes file storage for large files like images, videos, and PDFs.\n- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.\n- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.\n\nInstead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<\"_storage\">`.\n```\nimport { query } from \"./_generated/server\";\nimport { Id } from \"./_generated/dataModel\";\n\ntype FileMetadata = {\n    _id: Id<\"_storage\">;\n    _creationTime: number;\n    contentType?: string;\n    sha256: string;\n    size: number;\n}\n\nexport const exampleQuery = query({\n    args: { fileId: v.id(\"_storage\") },\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        const metadata: FileMetadata | null = await ctx.db.system.get(\"_storage\", args.fileId);\n        console.log(metadata);\n        return null;\n    },\n});\n```\n- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.\n\n\n# Examples:\n## Example: chat-app\n\n### Task\n```\nCreate a real-time chat application backend with AI responses. The app should:\n- Allow creating users with names\n- Support multiple chat channels\n- Enable users to send messages to channels\n- Automatically generate AI responses to user messages\n- Show recent message history\n\nThe backend should provide APIs for:\n1. User management (creation)\n2. Channel management (creation)\n3. Message operations (sending, listing)\n4. AI response generation using OpenAI's GPT-4\n\nMessages should be stored with their channel, author, and content. The system should maintain message order\nand limit history display to the 10 most recent messages per channel.\n\n```\n\n### Analysis\n1. Task Requirements Summary:\n- Build a real-time chat backend with AI integration\n- Support user creation\n- Enable channel-based conversations\n- Store and retrieve messages with proper ordering\n- Generate AI responses automatically\n\n2. Main Components Needed:\n- Database tables: users, channels, messages\n- Public APIs for user/channel management\n- Message handling functions\n- Internal AI response generation system\n- Context loading for AI responses\n\n3. Public API and Internal Functions Design:\nPublic Mutations:\n- createUser:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({userId: v.id(\"users\")})\n  - purpose: Create a new user with a given name\n- createChannel:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({channelId: v.id(\"channels\")})\n  - purpose: Create a new channel with a given name\n- sendMessage:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), authorId: v.id(\"users\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Send a message to a channel and schedule a response from the AI\n\nPublic Queries:\n- listMessages:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n    }))\n  - purpose: List the 10 most recent messages from a channel in descending creation order\n\nInternal Functions:\n- generateResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.null()\n  - purpose: Generate a response from the AI for a given channel\n- loadContext:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }))\n- writeAgentResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Write an AI response to a given channel\n\n4. Schema Design:\n- users\n  - validator: { name: v.string() }\n  - indexes: <none>\n- channels\n  - validator: { name: v.string() }\n  - indexes: <none>\n- messages\n  - validator: { channelId: v.id(\"channels\"), authorId: v.optional(v.id(\"users\")), content: v.string() }\n  - indexes\n    - by_channel: [\"channelId\"]\n\n5. Background Processing:\n- AI response generation runs asynchronously after each user message\n- Uses OpenAI's GPT-4 to generate contextual responses\n- Maintains conversation context using recent message history\n\n\n### Implementation\n\n#### package.json\n```typescript\n{\n  \"name\": \"chat-app\",\n  \"description\": \"This example shows how to build a chat app without authentication.\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"convex\": \"^1.31.2\",\n    \"openai\": \"^4.79.0\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.7.3\"\n  }\n}\n```\n\n#### tsconfig.json\n```typescript\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"exclude\": [\"convex\"],\n  \"include\": [\"**/src/**/*.tsx\", \"**/src/**/*.ts\", \"vite.config.ts\"]\n}\n```\n\n#### convex/index.ts\n```typescript\nimport {\n  query,\n  mutation,\n  internalQuery,\n  internalMutation,\n  internalAction,\n} from \"./_generated/server\";\nimport { v } from \"convex/values\";\nimport OpenAI from \"openai\";\nimport { internal } from \"./_generated/api\";\n\n/**\n * Create a user with a given name.\n */\nexport const createUser = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"users\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"users\", { name: args.name });\n  },\n});\n\n/**\n * Create a channel with a given name.\n */\nexport const createChannel = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"channels\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"channels\", { name: args.name });\n  },\n});\n\n/**\n * List the 10 most recent messages from a channel in descending creation order.\n */\nexport const listMessages = query({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      _id: v.id(\"messages\"),\n      _creationTime: v.number(),\n      channelId: v.id(\"channels\"),\n      authorId: v.optional(v.id(\"users\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n    return messages;\n  },\n});\n\n/**\n * Send a message to a channel and schedule a response from the AI.\n */\nexport const sendMessage = mutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    authorId: v.id(\"users\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const user = await ctx.db.get(args.authorId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      authorId: args.authorId,\n      content: args.content,\n    });\n    await ctx.scheduler.runAfter(0, internal.index.generateResponse, {\n      channelId: args.channelId,\n    });\n    return null;\n  },\n});\n\nconst openai = new OpenAI();\n\nexport const generateResponse = internalAction({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const context = await ctx.runQuery(internal.index.loadContext, {\n      channelId: args.channelId,\n    });\n    const response = await openai.chat.completions.create({\n      model: \"gpt-4o\",\n      messages: context,\n    });\n    const content = response.choices[0].message.content;\n    if (!content) {\n      throw new Error(\"No content in response\");\n    }\n    await ctx.runMutation(internal.index.writeAgentResponse, {\n      channelId: args.channelId,\n      content,\n    });\n    return null;\n  },\n});\n\nexport const loadContext = internalQuery({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      role: v.union(v.literal(\"user\"), v.literal(\"assistant\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n\n    const result = [];\n    for (const message of messages) {\n      if (message.authorId) {\n        const user = await ctx.db.get(message.authorId);\n        if (!user) {\n          throw new Error(\"User not found\");\n        }\n        result.push({\n          role: \"user\" as const,\n          content: `${user.name}: ${message.content}`,\n        });\n      } else {\n        result.push({ role: \"assistant\" as const, content: message.content });\n      }\n    }\n    return result;\n  },\n});\n\nexport const writeAgentResponse = internalMutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      content: args.content,\n    });\n    return null;\n  },\n});\n```\n\n#### convex/schema.ts\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n  channels: defineTable({\n    name: v.string(),\n  }),\n\n  users: defineTable({\n    name: v.string(),\n  }),\n\n  messages: defineTable({\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }).index(\"by_channel\", [\"channelId\"]),\n});\n```\n\n#### convex/tsconfig.json\n```typescript\n{\n  /* This TypeScript project config describes the environment that\n   * Convex functions run in and is used to typecheck them.\n   * You can modify it, but some settings required to use Convex.\n   */\n  \"compilerOptions\": {\n    /* These settings are not required by Convex and can be modified. */\n    \"allowJs\": true,\n    \"strict\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"jsx\": \"react-jsx\",\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n\n    /* These compiler options are required by Convex */\n    \"target\": \"ESNext\",\n    \"lib\": [\"ES2021\", \"dom\"],\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*\"],\n  \"exclude\": [\"./_generated\"]\n}\n```\n\n#### src/App.tsx\n```typescript\nexport default function App() {\n  return <div>Hello World</div>;\n}\n```\n","packages/1-prisma-cloud/2-shared-modules/auth/README.md":"# @internal/auth\n\nSignup, login, sessions, and JWT verification as a composed module wrapping\n[Better Auth](https://better-auth.com) (in-process TypeScript library — not a\nremote IdP), published as `@prisma/composer-prisma-cloud/auth`. One dedicated\nCompute service; the schema ships as a Prisma ORM extension pack; the\ninstance secret is platform-minted.\n\n## Contract scope\n\nThree ports, one service behind them — least privilege is a WIRING choice:\n\n- **`api`** (a raw HTTP port, `rawHttpContract` from `@prisma/composer/http`)\n  — the public Better Auth surface\n  (`/api/auth/*`): signup, login, logout, self-service account deletion,\n  JWKS, token minting. Publicly reachable, with no service key (unlike the\n  rpc ports) — it IS the authentication: Better Auth authenticates each\n  request itself (logout and account deletion need a signed-in session)\n  and rate limits it. Two consumer dependencies bind to it:\n  - `rawHttp()` from `@prisma/composer/http` → `{ url, fetch }` — what\n    `authProxy()` consumes. Any raw HTTP slot accepts this port, so a test\n    double or another auth server can fill the same slot.\n  - `jwtVerifier()` → `verify(token)` — stateless JWT verification over the\n    instance's JWKS (jose remote JWKS, 30 s clock tolerance). Resolves\n    `null` for ANY invalid token content; throws only on operational\n    errors (JWKS unreachable). No DB access — that is its whole value.\n- **`session`** (rpc) — consumer-facing online checks: `getSession(token)`\n  (null for unknown/expired/banned-owner — one shape, no error; a revoked\n  session is a deleted row, so this is the instant-logout read) and\n  `getUser(id)` (profile rendering off a JWT `sub` without admin wiring).\n- **`admin`** (rpc) — the tier-1 admin path: `findUser` (exactly one of\n  id/email; email match case-insensitive), `listUsers` (query/banned\n  filters, keyset cursor), `listSessions`, `revokeSession`,\n  `revokeUserSessions` (idempotent deletes), `banUser` (ban implies\n  revoke, atomically), `unbanUser`, `createUser` (see Provisioning\n  accounts below), `setEmailVerified`, `removeUser` (see Deleting\n  accounts below).\n\nWire each port only where it belongs: the app gets `api` + `session`; the\nback office alone gets `admin`.\n\n`/api/auth/*` is the browser surface. Better Auth origin-checks any request\nthat looks like it came from a browser — one carrying a cookie, an\n`Origin`/`Referer`, or any `Sec-Fetch-*` header — and refuses a missing\n`Origin` with `403 MISSING_OR_NULL_ORIGIN`. Node's built-in `fetch` sends\n`Sec-Fetch-Mode` on every request, so a Node script calling `/api/auth/*`\n(directly or through `authProxy`) is refused unless it sends an `Origin`\nthat is in `trustedOrigins` (the module's `baseUrl`). Server-to-server work\nbelongs on the rpc ports instead.\n\n## Golden-path wiring\n\n```ts\n// module.ts (the root)\nimport { appRoot, resolve } from '@prisma/composer';\nimport { serviceOrigin } from '@prisma/composer-prisma-cloud';\nimport { auth } from '@prisma/composer-prisma-cloud/auth';\nimport { postgres } from '@prisma/composer-prisma-cloud/orm';\nimport { appContract } from './src/contract.ts';\nimport apiService from './src/api/service.ts';\n\nexport default appRoot('app', ({ environment, provision }) => {\n  const db = provision(\n    postgres({\n      name: 'database',\n      contract: appContract,\n      config: './prisma.config.ts',\n      targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n    }),\n    { id: 'database' },\n  );\n  const identity = provision(auth(), {\n    id: 'auth',\n    deps: { db },\n    input: { baseUrl: serviceOrigin('app.api') }, // the PUBLIC app origin\n  });\n  provision(apiService, {\n    id: 'api',\n    deps: { authApi: identity.api, verifier: identity.api, session: identity.session },\n  });\n});\n```\n\nEvery deploy migrates the database to its `targetRef`. Here `prisma dev` migrates to the contract the commit emits, and a deploy to the environment `production` migrates to the ref `migrations/app/refs/production.json`, which you commit after planning a migration: `prisma migration ref set production <newest migration directory>`.\n\n```ts\n// src/api/service.ts: the app service declares its three dependencies\nimport { rawHttp } from '@prisma/composer/http';\nimport { rpc } from '@prisma/composer/service-rpc';\nimport { authSessionContract, jwtVerifier } from '@prisma/composer-prisma-cloud/auth';\n\nexport default compute({\n  name: 'api',\n  deps: { authApi: rawHttp(), verifier: jwtVerifier(), session: rpc(authSessionContract) },\n  build: node({ module: import.meta.url, entry: 'server.js' }),\n});\n```\n\n```ts\n// in the app service: first-party cookies via the proxy (the browser golden path)\nimport { authProxy } from '@prisma/composer-prisma-cloud/auth';\n\nconst { authApi, verifier } = service.load();\nconst proxy = authProxy(authApi);\n// route /api/auth/* → proxy(request); verify API calls with verifier.verify(<bearer>)\n```\n\nThe database is a BOUNDARY dependency: the root decides dedicated vs shared. `baseUrl` is the public origin browsers see (scheme+host, no trailing slash, no path) — bind it with `serviceOrigin('<app>.<service>')`, the service's full address, so each environment trusts its own URL, or a field of the root's input, such as `input.AUTH_BASE_URL`, for a custom domain. The instance secret is platform-minted inside the module; rotation is unsupported in v1 (rotating would invalidate every session and the encrypted jwks rows).\n\nA complete, deployable copy of this wiring lives in `examples/auth`.\n\n## Provisioning accounts\n\nAn account an operator creates goes through the `admin` port, server to\nserver — never through the browser sign-up surface:\n\n```ts\n// in a service wired to `identity.admin`\nconst { admin } = service.load();\nconst { user } = await admin.createUser({\n  email: 'ops@example.com',\n  name: 'Ops',\n  password: 'a-long-passphrase',   // optional; omit for a magic-link-only account\n  emailVerified: true,             // optional; default false\n});\n```\n\n`createUser` writes exactly what Better Auth's own sign-up writes — the\n`user` row and, with a password, a `credential` account hashed by Better\nAuth's own hasher — and sends no mail. The contract input applies the same\nchecks sign-up does (a well-formed email, a password of 8–128 characters),\nso a caller mistake is a 400 at the rpc boundary; a duplicate email\n(case-insensitive) is refused by the handler. Every refusal reaches a typed\nrpc client as a thrown error, so a script cannot mistake it for success. `setEmailVerified({ userId, emailVerified })` flips\nthe flag a created account needs before `requireEmailVerification` lets it\nsign in (`user: null` for an unknown id).\n\nA deployed stack's rpc ports are reachable only by consumers in its graph:\na script on a laptop cannot call `admin.createUser`. The application\nexposes its own operator route (allowlisted however it sees fit) from a\nservice wired to `admin`, and that route makes the call.\n\nInvite-only applications close self-service sign-up with a module setting,\nenforced by Better Auth itself, instead of filtering their proxy:\n\n```ts\nprovision(auth({ signUp: 'closed' }), { id: 'auth', deps: { db, email: mail.send }, input: { baseUrl: … } });\n```\n\n`signUp: 'closed'` sets `emailAndPassword.disableSignUp` and the magic-link\nplugin's `disableSignUp`: `/api/auth/sign-up/email` answers `400\nEMAIL_PASSWORD_SIGN_UP_DISABLED`, and a magic link requested for an unknown\nemail is still sent but completes to an `error=new_user_signup_disabled`\nredirect with no user created. Sign-in for existing accounts is unchanged.\nDefault `'open'`. Nothing about origin, CSRF, or `trustedOrigins` changes\neither way.\n\n## Deleting accounts\n\nA signed-in user deletes their own account through Better Auth's\n`POST /api/auth/delete-user`, reached through `authProxy()` like the rest\nof `/api/auth/*`:\n\n```ts\n// browser, signed in (cookie through the proxy)\nawait fetch('/api/auth/delete-user', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json' },\n  body: JSON.stringify({ password }), // optional when the session is < 24 h old\n});\n```\n\nIt needs a signed-in session (`401` otherwise), deletes only that\nsession's user (there is no `userId` parameter), and demands the current\n`password` (`400 INVALID_PASSWORD`) or a session younger than 24 hours\n(`400 SESSION_EXPIRED` — sign in again; magic-link users have no password).\n\nAn operator deletes an account through the `admin` port, server to server\n— this module's database-direct rpc, not Better Auth's admin-session API:\n\n```ts\n// in a service wired to `identity.admin`\nconst { removed } = await admin.removeUser({ userId });\n```\n\n`removed: false` means no such user, so a retried deletion is not an\nerror. No mail is sent.\n\nBoth paths delete the `user` row, its sessions, and its accounts. Pending\nverification tokens are left to expire: an unused magic link (the email,\n5 minutes) or reset (the user id, 1 hour); Better Auth deletes expired\ntokens the next time it checks any token. Your own rows follow your foreign\nkey onto `auth:User`: `onDelete: Cascade` deletes them with the user,\n`Restrict` refuses the deletion, and without an FK nothing links them.\nData outside the database (uploaded files, other stores) needs your own\ncleanup first — route that deletion through your service and\n`removeUser`. Already-minted JWTs keep verifying until they expire\n(≤ 15 min, see Sessions & JWTs); `session.getSession(token)` is `null`\nimmediately.\n\n## The pack\n\nBetter Auth's tables (`user`, `session`, `account`, `verification`, `jwks` —\nPostgres schema `auth`) ship as a Prisma ORM extension pack with authored\nmigrations — Better Auth's own migrator never runs anywhere. Consumers:\n\n```ts\n// prisma.config.ts\nimport authPack from '@prisma/composer-prisma-cloud/auth/pack';\nexport default defineConfig({ ..., extensions: [authPack] });\n```\n\nRun `prisma migration plan` once — it materialises the pack's shipped\nmigrations into `migrations/auth/` — and deploy: the ONE migration step\ncreates and evolves the auth tables beside your own, marker-signed per\nspace. On a shared database your own contract can FK `auth:User`\n(cross-space relations are non-navigable in the generated client; the value\nis the real constraint):\n\n```prisma\nmodel Profile {\n  id     String @id\n  userId String @unique\n  user   auth:User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n```\n\nUpgrade procedure: bump this package → `prisma migration plan` (the new\nshipped migrations materialise) → deploy. The deploy preflight fails loudly\nwhen a wired database's config is missing the pack or is at a stale head.\nA version whose section below says otherwise needs those steps instead.\n\n### Upgrading to a required `targetRef`\n\nThe app's database now needs `targetRef`, and every deploy runs the ORM's migrate to it, for the auth pack's contract space as for the app's. Add `targetRef` to the app's `postgres({ ... })` as shown above, commit a ref per environment you deploy with `prisma migration ref set <environment> <newest migration directory>` (run where the app's `prisma.config.ts` is), and remove any placeholder `db: { connection: … }` from that `prisma.config.ts`. The auth pack's own space always migrates to its shipped head.\n\n### Upgrading to Prisma ORM 8.0.0-rc.26\n\nPrisma ORM 8.0.0-rc.26 computes every contract hash in a new way, so the auth pack's storage hash moves from `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d` to `cb2e6cac77e993f93581b354f39af672267ae9c5888a156e68c00bb9087f769e`. The tables do not change. Follow [Upgrading to Prisma ORM's new contract hashes](../../../../docs/guides/deploying.md#upgrading-to-prisma-orms-new-contract-hashes): its script rewrites your copy of the auth pack's migrations in `migrations/auth/` with your own, and `prisma db sign` signs the auth pack's space with your app's.\n\nA database that only `startLocalAuthServer` uses, such as one your tests create, has no project to run `prisma db sign` from. Point the server at a fresh database instead: on a database it set up under an earlier version, it now stops with the ORM's `CONTRACT.PRISMA_SPACE_BEHIND` and changes nothing.\n\n### Upgrading to Composer 0.34.0\n\nComposer 0.34.0 moves to Prisma ORM 8.0.0-rc.20. The auth pack's contract no longer stores its `Tstz` type alias: each column stores its own type. The tables do not change, but the auth pack's storage hash does, from `0df0ef0989ec3dd95124dde6303fbe0572bbab08bebf00abff6a7955cadd786e` to `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d`. Your app keeps its own copy of the auth pack's migrations (`migrations/auth/` and the snapshot in `migrations/snapshots/0df0ef…/`), and Prisma ORM rc.20 refuses to load that snapshot as it is. Every database's marker also still holds the old hash. Until you follow these steps, `prisma deploy` and `prisma dev` fail at the migration step: first with `Contract-space contract validation failed for \"auth\"`, and after the script in step 3 with an error that the database is at a contract no migration of contract space `\"auth\"` reaches.\n\n1. Commit your work, so the changes below can be reviewed and undone with git.\n2. Upgrade `@prisma/composer`, `@prisma/composer-cli` and `@prisma/composer-prisma-cloud` to 0.34.0, `@prisma/orm-postgres` to 8.0.0-rc.20, and `prisma` to 8.0.0-rc.26 or later. An earlier `prisma` cannot read an rc.20 contract, so `contract emit` and `db sign` fail with `Cannot use 'in' operator to search for 'kind' in typeAlias`.\n3. From the app's root, copy the Prisma skills into the project and run the ORM's type-alias script. Node does not run a TypeScript file from inside `node_modules`, which is why the script runs from the copy:\n\n   ```sh\n   prisma skills sync\n   node .agents/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts\n   ```\n\n   It renames `migrations/snapshots/0df0ef…/` to `migrations/snapshots/24a0762…/` and rewrites `migrations/auth/0001_init/migration.json` and `migrations/auth/refs/head.json`. It prints `0df0ef… -> 24a0762…`.\n4. Run `prisma contract emit`. For an app whose own contract has no type aliases, this only moves the version stamps in `contract.json` and `contract.d.ts`.\n5. Run `prisma db sign --db <url>` against every database of the app: production, each other environment and the local dev database. The database does not change; only its marker moves to the new hash. It prints `auth: signed 24a0762… (was 0df0ef…)`.\n   - **Deployed environments.** A deploy never prints a connection string. Copy each database's connection string from the Prisma Console: the app's Project for production, and the Branch named after the environment for any other environment.\n   - **The local dev database.** It must be running: `prisma db sign --db \"$(prisma dev url database)\"`, where `database` is your auth database's node address. A `prisma dev` that fails stops the app, and `prisma dev url` reports only a running database, so sign before you run `prisma dev` on the new version. A `prisma dev --detach` started before the upgrade keeps the database running. If the database is already stopped, start over with `prisma dev --fresh`, which deletes the local data.\n6. Deploy and run `prisma dev` as usual.\n\nThe script also gives the rewritten `0001_init` migration a new hash, and each database's migration history keeps the old one. So `prisma migration status` no longer shows the auth pack's earlier migrations as applied, although it still reports the database as up to date. `prisma db migrate` does not run them again.\n\n## Sessions & JWTs\n\nStateless JWTs by default: 15-minute TTL, EdDSA via the instance's JWKS at\n`/api/auth/jwks`. Verified claims: `sub` (userId), `sid` (sessionId),\n`email`, `emailVerified`, `exp`. Cookie sessions last 7 days (rolling,\nrefreshed daily).\n\nThe trade-off is explicit: a revoked/banned session's already-minted JWTs\nkeep verifying until they expire (≤ 15 min). A route that needs instant\nlogout opts in per call with `session.getSession(token)` — a revoked\nsession is a deleted row. `iss`/`aud` are not validated in v1: the verifier\nonly trusts keys fetched from the wired instance, and instances never share\nkeys.\n\n## Local dev\n\n```ts\nimport { startLocalAuthServer } from '@prisma/composer-prisma-cloud/auth/testing';\n\nconst server = await startLocalAuthServer({ databaseUrl }); // e.g. `prisma dev`\n// server.url            → real Better Auth + the real port handlers\n// server.capturedEmails → { template, to, url } per send — read your\n//                          verification / magic links straight from here\n```\n\nReal Better Auth, the real handlers, the same fetch topology as production; the pack's schema applies idempotently at boot; a fixed dev secret; rpc runs keyless. No cloud credentials anywhere.\n\nThe helper applies the schema with the Prisma ORM your app installs (`@prisma/orm-postgres`, a required peer, and `@prisma/orm-toolchain`, which Composer depends on). It carries no copy of its own.\n\n## Email flows\n\nVerification, password reset, and magic-link emails deliver through the\n[email module](../email/README.md), wired as a boundary dependency:\n\n```ts\nconst mail = provision(email(), { id: 'mail', input: { /* deliveryMode, from, deliveryCredential */ } });\nconst identity = provision(auth(), {\n  id: 'auth',\n  deps: { db, email: mail.send },\n  input: { baseUrl: serviceOrigin('shop.web') },\n});\n```\n\nSignup requires verification (`requireEmailVerification: true`; the\nverification send fires on signup, and verifying auto-signs-in; an\n`admin.createUser` account skips the mail and is verified when created\nwith `emailVerified: true`). Magic links expire after 5 minutes. The three templates ship with the module —\nminimal semantic HTML plus a plain-text part; every interpolation is\nHTML-escaped, and a link whose origin differs from `baseUrl` fails the\nsend rather than going out.\n\nDelivery is fire-and-forget from auth's perspective: a failed send is\nlogged, never thrown (a down mail path must not brick signup), and each\nsend carries a deterministic idempotency key, so Better Auth retries\ncan't double-deliver. The email module's outbox is the operational\nrecord — read delivery state back through its `outbox` port.\n\nLocally, `startLocalAuthServer` captures sends in `capturedEmails` by\ndefault, or accepts an `email` sender hydrated against the email module's\nown local server so the outbox-readback path is the one production uses.\n`examples/auth` runs the full loop both ways: signup → verification link\nread back from the outbox → verify → login → magic link.\n\n## Embedded mode\n\nArrives with slice S4: `createEmbeddedAuth()` (`./embedded`) — the same\n`buildAuthOptions()` mounted in your own service, for the fully-in-process\nshape.\n\n## The SPA alternative\n\nDocumented fully in S2 alongside the browser flows: talk to the `api` port's\norigin directly with `Authorization: Bearer` (the bearer plugin is enabled),\nat the cost of the first-party-cookie golden path.\n\n## Limits (v1)\n\nNo social providers (mechanism reserved, none ship) · no organizations /\n2FA / passkeys / username / phone · no secret rotation · no impersonation · admin web UI is tier 2+ (the `admin` port is tier 1) ·\nrpc bodies cap at 1 MiB.\n","packages/1-prisma-cloud/2-shared-modules/email/README.md":"# `@prisma/composer-prisma-cloud/email`\n\nTransactional email as a Prisma Composer module. It is an ordinary module: a\nCompute service backed by a module-provisioned Prisma Postgres (every email is\nstored first, then delivery is attempted — the outbox), exposing two\nindependent ports: `send` (deliver a rendered email) and `outbox` (query every\nemail the module has handled). Templates are declared and rendered\n**consumer-side**; the wire carries only rendered mail.\n\nShips as the `@prisma/composer-prisma-cloud/email` subpath (like `/storage`\nand `/cron`).\n\n## Contract scope\n\nTwo ports, three ops:\n\n| Port | Op | Notes |\n| --- | --- | --- |\n| `send` | `send` | `{ templateId, to, cc?, bcc?, replyTo?, subject, html, text?, idempotencyKey }` → `{ id, status, error? }`. `to` 1–50 entries; `idempotencyKey` 1–256 chars. |\n| `outbox` | `getEmail` | `{ id }` → `{ email }` (`null` for an unknown id — never an error). |\n| `outbox` | `listEmails` | Optional `to`/`templateId`/`status`/`cursor`/`limit` filters (AND-combined; `to` matches any recipient) → `{ emails, nextCursor? }`, newest-first, keyset-paginated. `limit` 1–200, default 50. |\n\n`status` is one of `stored` (mode `none`), `queued` (real modes, transient),\n`sent`, `failed`. `send` never throws for a delivery failure — failure is\ndata (`status: 'failed'`, `error` set); it throws only for transport,\nvalidation, or database errors.\n\n`from` is not part of `send`'s input — the sender address is module config\n(one per module instance); a template cannot override it.\n\n## Envelope\n\n**No attachments** in v1. service-rpc request/response bodies cap at **1\nMiB**, so a rendered email (subject + html + text) must fit inside that.\n**Retention: none** — every sent email's full body is stored, unredacted,\nforever (no expiry, no deletion, no redaction). Do not put anything in a\ntemplate you would not want to live in the database indefinitely.\n\n## Wiring\n\nProvision `email()` in a module and declare template-typed dependencies on\nits two ports:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { email, emailDeliveryModes } from '@prisma/composer-prisma-cloud/email';\nimport { variable } from '@prisma/composer-prisma-cloud';\nimport { type } from 'arktype';\n\nexport default appRoot(\n  'app',\n  {\n    input: type({\n      EMAIL_DELIVERY_MODE: type.enumerated(...emailDeliveryModes),\n      EMAIL_FROM: 'string',\n    }),\n  },\n  ({ input, provision }) => {\n    const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));\n    const mail = provision(email(), {\n      id: 'email',\n      input: {\n        deliveryMode: input.EMAIL_DELIVERY_MODE,\n        from: input.EMAIL_FROM,\n        deliveryCredential,\n      },\n    });\n    provision(appService, { deps: { email: mail.send } });\n    provision(adminService, { deps: { outbox: mail.outbox } });\n  },\n);\n```\n\n```ts\n// consumer service — templates declare the client's shape. Interpolated\n// values are HTML-escaped before going into markup — `render` runs on\n// whatever data the caller supplies, so treat it as untrusted the same way\n// you would any other template.\nimport { defineTemplates, emailSender } from '@prisma/composer-prisma-cloud/email';\nimport { type } from 'arktype';\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#39;');\n}\n\nconst templates = defineTemplates({\n  verification: {\n    data: type({ link: 'string' }),\n    render: ({ link }) => ({\n      subject: 'Verify your email',\n      html: `<p><a href=\"${escapeHtml(link)}\">Verify</a></p>`,\n      text: `Verify: ${link}`,\n    }),\n  },\n});\n\nexport default compute({ deps: { email: emailSender(templates) }, /* … */ });\n```\n\n```ts\n// consumer server\nconst { email } = service.load();\nawait email.verification({ to: user.email, data: { link } });\n```\n\nThe outbox port needs no custom factory — declare `deps: { outbox:\nrpc(emailOutboxContract) }` and get the generated client directly.\n\n## Using react-email\n\n`render` may be synchronous or async — the sender method awaits either.\nThis module neither depends on nor imports react-email; a template's\n`render` just calls react-email's own `render()` and returns its result:\n\n```tsx\n// emails/welcome.tsx — a plain react-email component\nimport { Body, Container, Html, Text } from '@react-email/components';\n\nexport function WelcomeEmail({ name }: { name: string }) {\n  return (\n    <Html lang=\"en\">\n      <Body>\n        <Container>\n          <Text>Welcome, {name}!</Text>\n        </Container>\n      </Body>\n    </Html>\n  );\n}\n```\n\n```tsx\n// templates.tsx\nimport { render } from '@react-email/render';\nimport { WelcomeEmail } from './emails/welcome.tsx';\n\nconst templates = defineTemplates({\n  welcome: {\n    data: type({ name: 'string' }),\n    render: async ({ name }) => ({\n      subject: `Welcome, ${name}!`,\n      html: await render(<WelcomeEmail name={name} />),\n      text: await render(<WelcomeEmail name={name} />, { plainText: true }),\n    }),\n  },\n});\n```\n\nJSX interpolation (`{name}` above) escapes automatically — React escapes\ntext children by construction, so a react-email template needs no manual\n`escapeHtml` the way a plain-function template does. See\n[`examples/email`](../../../../examples/email)'s `welcome` template for\nthe full worked version, alongside `verification` as a plain function —\nboth authoring styles side by side.\n\nOne deploy caveat: `prisma deploy` loads your module graph with\nNode's own loader, which cannot transform JSX — a `.tsx` file imported by\nyour topology fails with `Unknown file extension \".tsx\"`. Precompile the\ntemplates file in your app's own build and import the compiled output, as\n[`examples/email/scripts/build.ts`](../../../../examples/email/scripts/build.ts)\ndoes (see the matching `gotchas.md` entry).\n\n## Values per environment\n\n`deliveryMode`, `from` and `deliveryCredential` are the module's `input`. `deliveryMode` is `resend`, `smtp` or `none`, exported as `emailDeliveryModes` (and the type `EmailDeliveryMode`): bind it to one of those literals, or to a field of your root's input declared from `emailDeliveryModes`, as above, so the root's schema checks it before anything is created. With Zod, declare the field as `z.enum(emailDeliveryModes)`. A plain platform variable may hold any text, so binding its value to `deliveryMode` fails to compile. Bind `from` to a literal, a field of your root's input or the value of a `variable(...)` node, so it can vary per environment. `deliveryCredential` is a `secretString()` field: bind it to the value of a `variable.secret(...)` node the app root provisions. `deliveryMode` and `from` are wrapped fields (`field()`), so a module that passes its own wrapped field of the same type on can bind them too. `deliveryUrl` is a factory option (`email({ deliveryUrl })`), static per app: it defaults to `https://api.resend.com` and follows the mode.\n\nIn the sample above, `EMAIL_DELIVERY_MODE` and `EMAIL_FROM` are root input fields: set them in the shell that runs the deploy. `EMAIL_DELIVERY_CREDENTIAL` is a platform secret: set it on the platform with `prisma project env add`.\n\n| Name | Where it is set | Production | Preview |\n| --- | --- | --- | --- |\n| `EMAIL_DELIVERY_MODE` | the deploy shell | `resend` (or `smtp`) | `none` |\n| `EMAIL_FROM` | the deploy shell | `noreply@myapp.com` | anything (unused when `none`) |\n| `EMAIL_DELIVERY_CREDENTIAL` | the platform | Resend API key / SMTP password | any non-empty value, which preflight requires even though the service never reads it |\n\nPreview needs a credential because the email service's input schema requires it in every mode, so an environment that never delivers still sets a non-empty value. A schema can make a secret field optional (ADR-0042); this one does not. `gotchas.md` records this.\n\n## Delivery policy\n\nShared by both real backings (`resend`, `smtp`):\n\n- Per-attempt timeout: **10 s**.\n- Up to **3 attempts** (1 initial + 2 retries), delayed **500 ms then\n  2000 ms** between them (no jitter).\n- Retryable: thrown/network errors, HTTP 429, HTTP 5xx (Resend); SMTP\n  connection errors and response codes 421/450/451/452.\n- Not retryable (fails immediately): any other Resend 4xx (including 409\n  idempotency conflicts — those should be unreachable given the outbox's\n  own row-level dedup; if one surfaces, it is not masked); any other SMTP\n  response code, including permanent 5xx rejections.\n- The outbox row's `attempts` accumulates the count each delivery\n  invocation actually made (1–3 under the policy above) — a future\n  redelivery from the outbox adds its own tries to the running total.\n- Stored `error` string: `` resend <status> <name>: <message> `` (Resend,\n  parsed from its error body; falls back to the raw response text if\n  unparseable) or `` smtp <responseCode>: <message> `` (SMTP protocol\n  rejection). A connection-level failure (no response code) stores the raw\n  error message with no prefix, for either backing.\n\n**SMTP: \"accepted\" is not \"delivered\".** `status: 'sent'` for an SMTP send\nmeans the relay accepted the message for submission — nothing more. SMTP\ngives no delivery confirmation; `providerMessageId` is nodemailer's\n`info.messageId` (or `null`).\n\n**SMTP: a timeout retry can duplicate a send.** The per-attempt timeout\nonly stops the module from waiting on a slow relay — it does not cancel\nthe in-flight SMTP transaction. If the timeout fires, the shared policy\nretries; a slow relay can still accept the first attempt's message after\nthe retry has already started, delivering the same email twice. This is a\ndeliberate retry-semantics tradeoff (at-least-once, not exactly-once) and\nstays as pinned — the only fix that removes the possibility is not\nretrying on timeout, which would trade a rare duplicate for a more common\nfalse failure on a merely slow relay.\n\n## Idempotency\n\n`idempotencyKey` is required on every `send` call and must be **unique per\nlogical send**. A repeated key returns the original row — status, id, and\nall — with no new delivery attempt, even if the payload differs. This is a\ndurable, row-level guarantee (a unique constraint on `idempotency_key`),\nindependent of and stronger than service-rpc's own in-memory replay cache.\n\n`emailSender`'s per-template methods make `idempotencyKey` optional: omit\nit and a fresh UUID is minted on every call, so that call gets no dedup\nprotection against its own retries. If your own retry logic re-invokes a\nsend method after a transient failure, capture the key from the first\nattempt and pass it explicitly on the retry — the module does not\nremember it for you.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/email/testing` boots the same handler map\nover an in-memory store, `deliveryMode: 'none'`, loopback only, no auth —\nno cloud credentials, no Postgres:\n\n```ts\nimport { startLocalEmailServer } from '@prisma/composer-prisma-cloud/email/testing';\n\nconst server = await startLocalEmailServer(); // ephemeral port by default\n// server.url — point emailSender()/rpc(emailOutboxContract) clients at it.\nawait server.stop();\n```\n\n[`examples/email`](../../../../examples/email) is the worked example: a\n`mailer` app wired to `email()`, tested locally against this stand-in with\nno cloud credentials, and deployed to Prisma Cloud in `none` mode as the\nsmoke test.\n\nTests that exercise the real Resend/SMTP backings point `deliveryUrl` at a\nlocal fake instead of the real provider — a `Bun.serve` fake HTTP endpoint\nfor Resend, a minimal loopback SMTP responder for SMTP (see\n`delivery-resend.test.ts`/`delivery-smtp.test.ts`).\n\n## Manual resend check (not run in CI)\n\nA one-off, by-hand verification that a real send actually delivers — not\npart of the test suite or the deploy smoke, since it needs a real Resend\naccount:\n\n1. Set the environment's `EMAIL_DELIVERY_MODE` to `resend`, `EMAIL_FROM` to an\n   address on a domain verified with Resend, and `EMAIL_DELIVERY_CREDENTIAL`\n   to a real Resend API key.\n2. Send one template to a real inbox you control.\n3. Confirm the message arrives, and that the outbox row for it reads\n   `status: 'sent'` with a non-null `providerMessageId`.\n\n## Non-goals (v1)\n\nAttachments, cc/bcc size limits beyond the contract's, per-send `from`\noverride, batch/scheduled send, Resend webhooks, delivery-status polling,\nopen/click tracking, queue-backed async delivery (the outbox is the seam\nfor a later relay — no contract change needed), retention/redaction/\ndeletion, and an admin UI. react-email is not a dependency of this module\n— see \"Using react-email\" above for how a consumer wires it in.\n","packages/1-prisma-cloud/2-shared-modules/storage/README.md":"# `@prisma/composer-prisma-cloud/storage`\n\nS3-compatible object storage as a Prisma Composer module. It is an ordinary\nmodule: a Compute service that speaks the **S3 wire protocol**, backed by a\nmodule-provisioned Prisma Postgres (objects live in a single `bytea` column),\nwith SigV4 credentials minted at deploy. Consumers wire the module's `store`\nport into an `s3()` slot and get an `S3Config` binding; they build their own\nS3 client (aws-sdk, or a hand-rolled SigV4 client) from it.\n\nShips as the `@prisma/composer-prisma-cloud/storage` subpath (like `/cron`).\n\n## Contract scope\n\nThe contract **is** the S3 wire protocol — but only the subset a real consumer\nneeds, not S3-compatibility maximalism. In scope:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /{bucket}/{key}` | `content-type` optional; returns a quoted SHA-256 ETag (opaque to consumers) |\n| `GET /{bucket}/{key}` | optional `Range: bytes=a-b` (inclusive end; open end `a-`) → `206`; missing → `404` |\n| `HEAD /{bucket}/{key}` | `etag` + `content-length`; missing → `404` |\n| `DELETE /{bucket}/{key}` | idempotent (a missing key is success) |\n| `GET /{bucket}?list-type=2` | `prefix`, `continuation-token`, `max-keys` (default 1000); ListObjectsV2 XML |\n| Presigned GET/PUT | query-param SigV4, expiry enforced |\n\nAuth is SigV4 (`AWS4-HMAC-SHA256`), **path-style addressing only**, any region\nstring (`auto` is fine). Bucket names simply namespace keys — there is no\nbucket CRUD.\n\n**Out of scope**: multipart upload, `CopyObject`, batch `DeleteObjects`,\nconditional requests, flexible checksums / `aws-chunked` framing (rejected with\n`501` — see the wiring note below), bucket CRUD, ACLs, versioning, lifecycle.\n\nSee [`CONTRACT-SCOPE.md`](./CONTRACT-SCOPE.md) for the full op semantics and the\nexact out-of-scope list.\n\n## Envelope\n\nObjects up to **~16 MiB**. Each object is one row's `bytea` value; ranged reads\nuse SQL `substring(...)` so a range request never loads the whole object. This\nis comfortably within Postgres `bytea`/TOAST for the target workload — it is\n**not** a general-purpose large-blob store, and larger objects are unsupported.\n\n## Wiring\n\nProvision `storage()` in a module and wire its `store` port into a consumer's\n`s3()` slot:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport blobs from './src/blobs/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage()); // owns its Postgres + minted credentials\n  provision(blobs, { deps: { store: store.store } });\n});\n```\n\n```ts\n// src/blobs/service.ts — the consumer declares an s3() dependency\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { s3 } from '@prisma/composer-prisma-cloud/storage';\n\nexport default compute({\n  name: 'blobs',\n  deps: { store: s3() },\n  build: node({ module: import.meta.url, entry: '../../dist/blobs/server.mjs' }),\n});\n```\n\n```ts\n// src/blobs/server.ts — the consumer's entry builds its own client (ADR-0015)\nimport { S3Client } from '@aws-sdk/client-s3';\nimport service from './service.ts';\n\nconst { store } = service.load(); // S3Config: { url, bucket, accessKeyId, secretAccessKey }\n\nconst client = new S3Client({\n  region: 'auto',\n  endpoint: store.url, // path-style; no virtual-host addressing\n  forcePathStyle: true,\n  credentials: { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey },\n  // The store rejects aws-chunked / flexible-checksum PUTs with 501 — send plain\n  // signed payloads.\n  requestChecksumCalculation: 'WHEN_REQUIRED',\n});\n```\n\nThe `S3Config` binding is the whole surface a consumer sees:\n\n```ts\ninterface S3Config {\n  readonly url: string; // the store's endpoint\n  readonly bucket: string;\n  readonly accessKeyId: string;\n  readonly secretAccessKey: string;\n}\n```\n\n[`examples/storage`](../../../../examples/storage) is the worked example — a\nsmall blob store/serve app that consumes `storage()` and deploys to Prisma\nCloud.\n\n## Local development\n\nThe same module runs locally against local Postgres — no cloud, no minted\ncredentials. `@prisma/composer-prisma-cloud/storage/testing` exposes the store\nand server directly:\n\n```ts\nimport { createPgStore, startStorageServer } from '@prisma/composer-prisma-cloud/storage/testing';\n\nconst store = await createPgStore(process.env.DATABASE_URL!); // applies the schema\nconst server = startStorageServer({\n  store,\n  credentials: { accessKeyId: 'local', secretAccessKey: 'local-secret' },\n  bucket: 'my-bucket',\n  port: 0, // ephemeral\n});\n\n// server.url is an S3 endpoint — point an aws-sdk client (path-style) at it.\n// server.stop() when done.\n```\n\nThe module's own tests, and `examples/storage`'s integration test, boot exactly\nthis stand-in over a throwaway Postgres: they honor `STATE_TEST_DATABASE_URL`\nwhen set, otherwise self-spawn an ephemeral Homebrew `postgresql@15` cluster\n(`initdb`/`pg_ctl`); they skip on a dev machine with no Postgres and fail on CI\nif none is available.\n\n## Credentials\n\nThe SigV4 key pair is **minted once at deploy** (a random keypair persisted in\ndeploy state) and delivered to consumers through the `S3Config` binding — it is\nnever printed and never surfaces outside the deployment. Consumers are\ntherefore **in-deployment services** that receive the credentials via `load()`,\nnot arbitrary external clients. An external-access path (reading the minted\ncredentials from outside the deploy) is a recorded platform ask, not something\nthis module solves.\n","packages/1-prisma-cloud/2-shared-modules/streams/README.md":"# `@prisma/composer-prisma-cloud/streams`\n\nDurable append-only event streams as a Prisma Composer module. It wraps the\nproduction `@prisma/streams-server` runtime (npm, unmodified) as a Compute\nservice behind a typed boundary: the module's `store` dependency takes a\n`storage()` module's port as its durable tier, and it exposes a single\n`streams` port. A consumer names the streams it uses with\n`streamsContract(defs)`, and its `durableStreams(contract)` dependency\nhydrates to one ready **`StreamHandle`** per declared name — like RPC's\ngenerated client, no app hand-rolls the protocol, and no app carries a\nstream-lifecycle constant: the handle owns creating the stream on first use\nand healing a 404 by re-creating and retrying once. The wire binding\nunderneath is `{ url, apiKey }`, the key minted by the deploy.\n\nShips as the `@prisma/composer-prisma-cloud/streams` subpath (like `/storage`).\n\n## Contract scope\n\nA contract names its streams:\n\n```ts\nconst jobLog = streamsContract({\n  jobs: streamDef(),   // untyped in this slice — events type as `unknown`\n  audit: streamDef(),\n});\n```\n\nHydration hands a consumer one handle per declared name:\n\n```ts\ninterface StreamHandle {\n  append(event): Promise<void>; // one JSON event; NEVER retried beyond the 404 heal below\n  read<T>(opts?): Promise<{ events: T[]; nextOffset: string }>;\n  tail<T>(opts?): Promise<{ events: T[]; nextOffset: string; timedOut: boolean }>;\n}\n```\n\nNo `create` — a handle creates its stream on first use, memoized, and heals a\n404 (the stream vanished from the durable tier) by dropping that memo,\nre-creating, and retrying the failed operation once. That heal is safe even\nfor an append: a 404 is generated INSTEAD OF a write at every layer, so it\nproves nothing was applied.\n\nFor dynamic stream names (e.g. per-tenant streams), call `durableStreams()`\nwith no contract — the `rawPostgres()` parity, same lifecycle ownership, the\nname is data rather than a wiring-time declaration:\n\n```ts\ninterface StreamsClient {\n  stream(name: string): StreamHandle;\n}\n```\n\nThe wire binding underneath is the typed connection config (ADR-0015) —\n`{ url: string, apiKey: string }` — and the client wraps\n[`@durable-streams/client`](https://www.npmjs.com/package/@durable-streams/client)\n(ElectricSQL's canonical protocol client, pinned to the version\n`@prisma/streams-server` 0.1.11's own repo pairs with). The full protocol\nsurface it drives:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /v1/stream/{name}` | create (idempotent; `content-type` fixes the stream's type) |\n| `POST /v1/stream/{name}` | append a JSON array of events (`stream-closed: true` header closes) |\n| `GET /v1/stream/{name}?offset=…` | read from an offset; `-1` = start; `format=json` |\n| `GET …&live=long-poll&timeout=…` | held read — returns when fresh events arrive or timeout |\n| `GET …&live=sse` | SSE tail (see the deployed live path note below) |\n\nOffsets are **opaque cursors**, not numeric indices: take them from a read's\n`nextOffset` and pass them back verbatim.\n\n**Auth rides the binding.** The bearer key is not an ADR-0029 secret (there\nis no external value to bind) and not a producer output. The `apiKey`\nconnection param declares an [ADR-0031](../../../../docs/design/90-decisions/ADR-0031-provisioned-param-values-are-a-need-resolved-through-a-target-registry.md)\n**provisioning need**: the deploy target mints the value, keeps it stable in\ndeploy state, and fills the param like any other input. Declaring a\n`durableStreams()` dependency is the whole of the wiring — there is no secret\nslot and nothing to bind at the root. Every endpoint, including `/health`,\nrequires `Authorization: Bearer <key>`.\n\nTwo consequences worth knowing:\n\n- **One key per streams module.** The provisioner mints per provider, not per\n  edge, because `@prisma/streams-server` authenticates a single `API_KEY` —\n  every consumer of one `streams()` instance holds the same value. Cardinality\n  is provisioner policy (ADR-0031), so per-edge keys are later a change of\n  that policy plus an accepted-set provider param once the upstream server\n  takes a key set: no resource to add, no core change, nothing here to delete.\n- **No consumers, no key.** The need lives on the consumer's edge, so a\n  `streams()` module nothing depends on never gets a key minted, and its\n  server refuses to boot rather than serve unauthenticated. Wire a consumer,\n  or drop the module.\n\n## Wiring\n\nThe root provisions `storage()` as the durable tier and wires its `store`\nport into `streams()` — the key needs no wiring at all:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport { streams } from '@prisma/composer-prisma-cloud/streams';\nimport worker from './src/worker/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage());\n  const events = provision(streams(), { deps: { store: store.store } });\n  provision(worker, { deps: { streams: events.streams } });\n});\n```\n\n```ts\n// src/worker/service.ts — the consumer. Declaring the dependency is what\n// causes the key to be minted; nothing names it a second time.\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { durableStreams, streamDef, streamsContract } from '@prisma/composer-prisma-cloud/streams';\n\nconst jobLog = streamsContract({ jobs: streamDef() });\n\nexport default compute({\n  name: 'worker',\n  deps: { streams: durableStreams(jobLog) },\n  build: node({ module: import.meta.url, entry: '../../dist/worker/server.mjs' }),\n});\n```\n\n```ts\n// src/worker/server.ts — append, then wait for what follows\nimport service from './service.ts';\n\nconst { streams } = service.load(); // { jobs: StreamHandle }, ready to call\n\nawait streams.jobs.append({ kind: 'created' });\nconst { events, nextOffset } = await streams.jobs.read();\nconst next = await streams.jobs.tail(); // resolves on the next event (or timedOut)\n```\n\nFor local development and tests, build the same client against the stand-in\n(no deployed binding, no auth):\n\n```ts\nimport { StreamsClient } from '@prisma/composer-prisma-cloud/streams';\n\nconst client = new StreamsClient({ url: standIn.url, apiKey: 'unused' });\nconst jobs = client.stream('jobs'); // a StreamHandle, same surface as the hydrated binding\n```\n\n[`examples/streams`](../../../../examples/streams) is the worked example — the\nmodule deployed to Prisma Cloud with `storage()` as its tier and a `jobs`\nservice consuming the binding, plus local integration tests and a deployed\nconsumer smoke script.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/streams/testing` embeds the local stand-in\n(`@prisma/streams-local`): SQLite-only, loopback, **no auth, no object store,\nno cloud credentials** — the same protocol surface.\n\n```ts\nimport { startLocalStreamsServer } from '@prisma/composer-prisma-cloud/streams/testing';\n\nconst server = await startLocalStreamsServer({ name: 'dev', port: 0 });\n// server.exports.http.url is a Durable Streams endpoint (no Authorization needed).\n// await server.close() when done.\n```\n\nThe stand-in persists under `DS_LOCAL_DATA_ROOT`; tests point that at a\nthrowaway directory. The full conformance suite runs against it with no\ncredentials: `pnpm test:conformance:local` (and against a deployment:\n`CONFORMANCE_TEST_URL=… STREAMS_API_KEY=… pnpm test:conformance:deployed`).\n\n## Deployed live path: use long-poll\n\nThe Compute ingress currently buffers HTTP responses until the upstream\nresponse completes. An open `?live=sse` tail therefore never delivers through\na deployment's public URL — the client sees zero bytes and the edge returns a\n504 after ~60s — while the same request works locally and against the\nstand-in. `?live=long-poll` completes per response and delivers live events\nend to end through the ingress, so `StreamHandle.tail` long-polls. The\ndeployed conformance harness keeps the SSE tests, so they flip green when the\nplatform supports streaming responses.\n","skills-contrib/multiline-commit-messages/SKILL.md":"---\nname: multiline-commit-messages\ndescription: >-\n  Use single-quoted strings for multiline git commit messages in the Shell tool.\n  Prevents heredoc escaping failures that produce garbled commit messages.\n---\n\n# Multiline commit messages\n\nThe Shell tool sends commands as a single string. Heredoc syntax (`<<'EOF'`) inside `$(cat ...)` is fragile and can fail silently — the literal `$(cat <<'EOF' ...` ends up as the commit message instead of the intended text.\n\n## Rule\n\nPrefer single-quoted strings with embedded newlines over `$(cat <<'EOF' ...)`:\n\n```bash\ngit commit -s -m 'short summary line\n\nLonger body paragraph explaining why the change exists.\nAdditional context if needed.'\n```\n\n## Why heredocs are fragile\n\nThe Shell tool passes the command as a single string argument. When you write:\n\n```bash\ngit commit -m \"$(cat <<'EOF'\nmessage\nEOF\n)\"\n```\n\nthe `EOF` delimiter, newlines, and nested quoting can interact unpredictably, and the result is the raw `$(cat <<'EOF' ...` text appearing as the commit message.\n\nSingle-quoted strings with literal newlines are simple, portable, and always work. If the message itself must contain a single quote, close and reopen the quote (`'\\''`) or fall back to a temp file passed via `-F`.\n\n## Sign off\n\nEvery commit still needs its `Signed-off-by` trailer — see [git-staging](../../../.cursor/rules/git-staging.mdc). Pass `-s` on the same `git commit` invocation.\n","skills-contrib/publish-npm-version/SKILL.md":"---\nname: publish-npm-version\ndescription: >-\n  Cuts the next minor release of Prisma Composer: bumps the root\n  package.json version, propagates it to every workspace package in lockstep,\n  and opens a PR titled \"chore(release): v<next-version>\". When a maintainer\n  merges the PR, the `Publish to npm` workflow runs automatically and publishes\n  the new version to npm under dist-tag `next`, plus a matching GitHub Release\n  with auto-generated notes; users get it when a maintainer promotes it to\n  `latest`. Use when a maintainer asks to \"cut the next minor\",\n  \"bump to the next version\", \"open a release PR\", or \"prepare a publish PR\".\n---\n\n# Publish next npm version\n\n## Audience\n\nMaintainers who can push branches and open PRs. Invoke this **locally**, not as a\nGitHub Action — a PR opened by a workflow's `GITHUB_TOKEN` does not trigger CI,\nwhich defeats the point of a reviewable release.\n\n## Background reading\n\nRead [`docs/oss/versioning.md`](../../docs/oss/versioning.md) first — it is the\npolicy this skill mechanises: the root-`package.json` source of truth, the\nlockstep guarantee, the dist-tag convention, and the full procedure (this skill\nis the \"open the bump PR\" step; **merging the PR is the publish trigger** — there\nis no separate dispatch step).\n\n## Pre-flight\n\nConfirm you can fetch from `origin` (`git fetch origin main` succeeds). The skill\nworks in a fresh worktree off `origin/main`, so your current worktree is left\nundisturbed.\n\n## Steps\n\n1. **Fresh worktree off `origin/main`:**\n   ```bash\n   git fetch origin main\n   git worktree add -b chore/release-vNEXT ../release-vNEXT origin/main\n   cd ../release-vNEXT\n   pnpm install --frozen-lockfile\n   ```\n2. **Bump.** `pnpm bump-minor` reads the root version at `HEAD`, computes the next\n   minor (`0.2.0` → `0.3.0`), stamps every workspace `package.json` in\n   lockstep (rewriting internal `workspace:` deps to the new version), and\n   regenerates `pnpm-lock.yaml` to match.\n3. **Sanity-check** the bump is clean and complete. The diff must include\n   `pnpm-lock.yaml` — CI installs with `--frozen-lockfile`, so a bump without the\n   lockfile fails every CI job at the install step:\n   ```bash\n   git diff --stat                      # every workspace package.json + pnpm-lock.yaml\n   pnpm check:publish-deps              # no workspace:/catalog: leaks, exact internal pins\n   ```\n4. **Commit** with the release title and dual DCO sign-off, then push and open the PR:\n   ```bash\n   git commit -am \"chore(release): v<version>\"\n   git push -u origin chore/release-vNEXT\n   gh pr create --base main --title \"chore(release): v<version>\" \\\n     --body \"Release v<version>. Merging this triggers the Publish to npm workflow.\"\n   ```\n5. **Hand off.** Tell the maintainer the PR is open and that **merging it** publishes `<version>` to npm under `next` (via OIDC trusted publishing) and cuts a GitHub Release with auto-generated notes. Users get the release only once a maintainer promotes it to `latest` with the `Promote a release to latest` workflow (versioning.md § Promote a release to `latest`). Do not merge it yourself unless asked.\n\n## What this skill does NOT do\n\n- **Patches / old minors.** There are no patch releases of older minors\n  (versioning.md § pre-1.0). This skill only advances the latest minor.\n- **The publish itself.** That is the `Publish to npm` workflow, triggered by the\n  merge — never run `pnpm publish` by hand for a normal release.\n- **Release notes authoring.** The GitHub Release notes are auto-generated\n  (`gh release create --generate-notes`) by the workflow; there is no committed\n  release-notes file to write.\n","skills-contrib/upgrade-alchemy-effect/SKILL.md":"---\nname: upgrade-alchemy-effect\ndescription: >-\n  How to upgrade `alchemy` and the `effect` constellation across this repo and\n  keep them consistent for consumers: which packages pin what, why `effect` and\n  every `@effect/*` companion move as one set, what breaks in a typical\n  upgrade, and how to verify a standalone `npm install` still resolves a single\n  `effect`. Use when asked to upgrade or bump alchemy or effect, when a deploy\n  dies inside an alchemy provider with a `TypeError` naming a missing\n  combinator, when `check:npm-effect-resolution` fails, or when deciding\n  whether the alchemy patch is still needed.\n---\n\n# Upgrade alchemy and effect\n\n## Audience\n\nMaintainers changing the `alchemy` or `effect` pins in this repo.\n\n## Read this first\n\n**Check what upstream ships before working around what we pin.** The pinned\nversion is not a constant, and treating it as one is expensive: TML-3158 was a\nlong chase through pinning, peer dependencies, and a CLI preflight (since\nretired), all to keep\na consumer's tree away from an `effect` that alchemy 2.0.0-beta.59 could not\nrun — while a newer alchemy that had already fixed it sat on the registry the\nwhole time. One command would have shown it:\n\n```bash\nnpm view alchemy dist-tags\nnpm view alchemy@<latest> peerDependencies\n```\n\nIf alchemy's `effect` peer range has moved past our pin, the upgrade *is* the\nfix. Reach for workarounds only after that check says otherwise.\n\n## Why the versions move as a set\n\n`effect` and its companions — `@effect/platform-node`, `@effect/platform-bun`,\n`@effect/platform-node-shared` — each declare a peer that is\n**floored at their own version**:\n\n```jsonc\n// @effect/platform-bun@4.0.0-rc.111\n\"peerDependencies\": { \"effect\": \"^4.0.0-rc.111\" }\n```\n\nThat caret is a range, not an exact pin: it accepts `4.0.0-rc.112` and stable\n`4.x`, but nothing below `4.0.0-rc.111`. So an `effect` **older** than any\ncompanion in the tree is unsatisfiable, and npm resolves that by installing a\n*second* `effect`. Pinning every package in this repo to the same release is the\nsimple way to stay above every floor at once. Treat them as one constellation,\nnever as individual bumps.\n\nalchemy sits on top with a deliberately loose range (`>=4.0.0-rc.115 || >=4.0.0` at beta.78). That range is what lets a stray dependency drag a different `effect` in.\n\n## Two audiences, two failure modes\n\n- **This workspace** uses pnpm, which only *warns* on a peer mismatch and keeps\n  our pinned copy. A broken constellation is therefore invisible in-repo — CI\n  and local dev stay green while consumers break.\n- **Consumers** use npm, which hoists a satisfying version to the root of\n  `node_modules`. alchemy imports whatever is at the root. Nothing we declare\n  prevents this: an exact `peerDependencies` entry does **not** make npm fail —\n  verified empirically, it warns, hoists the other copy anyway, and exits 0.\n  Only the consumer's own `overrides` can force alchemy's copy.\n\nThat asymmetry is why `scripts/check-npm-effect-resolution.mjs` installs real\ntarballs with real npm.\n\n## What a consumer sees when the tree is wrong\n\nComposer has no check of its own for a wrong `effect`. The app's\n`prisma.config.ts` imports the extensions' `/control` entries in its `composer`\nsection, and those import alchemy, so a wrong `effect` fails the moment the\nengine evaluates the config file, before any command runs. The error is the\nengine's `CLI.CONFIG_UNREADABLE`, naming the file and carrying the module error,\nfor example `prisma.config.ts could not be evaluated: Schema.TaggedError is not\na function`. Only the consumer's package manager can fix that tree, usually\nwith an `overrides` entry that forces our pinned `effect`\n(`docs/guides/deploying.md`). Keep the pins below exact and consistent so a bare\ninstall never gets there.\n\n## Steps\n\n1. **Pick the target.** Read alchemy's latest peer range, then choose the newest release where *every* companion publishes a matching version:\n\n   ```bash\n   npm view alchemy dist-tags\n   npm view alchemy@<version> peerDependencies\n   for p in effect @effect/platform-node @effect/platform-bun \\\n            @effect/platform-node-shared; do\n     echo \"$p $(npm view $p version)\"\n   done\n   ```\n\n   alchemy's floor is not a compatibility promise. alchemy 2.0.0-beta.75 to beta.77 accept `effect` rc.112 and later, but call `Config.string`, which rc.113 removed, so they crash on it. Pin the `effect` release alchemy was built against: the newest one published before that alchemy release (`npm view effect time`). Check the new alchemy's Prisma provider still loads from a plain npm install: in beta.79 it imports the optional peer `@alchemy.run/frontend-frameworks` and fails. Since beta.84 each provider is its own package, versioned in lockstep with `alchemy`: the Prisma provider is `@alchemy.run/prisma` (formerly the `alchemy/Prisma` module), and only `@prisma/composer-prisma-cloud` and the Prisma Cloud internals depend on it. Bump it with `alchemy`.\n\n2. **Find every pin.** `alchemy`, `@alchemy.run/prisma`, `@distilled.cloud/prisma`, `effect` and the `@effect/platform-*` packages are pinned once, in the `catalog:` block of `pnpm-workspace.yaml`; every manifest says `catalog:`, and `pnpm pack` writes the resolved version into the published manifest. Check nothing outside the catalog pins them:\n\n   ```bash\n   grep -rln '\"alchemy\"\\|\"@alchemy.run/\\|\"@distilled.cloud/\\|@effect/\\|\"effect\"' --include=package.json . | grep -v node_modules\n   ```\n\n3. **Clear the patch key first.** `pnpm.patchedDependencies` is keyed by the\n   exact version, so an alchemy bump leaves it pointing at a version that is no\n   longer installed and the next install fails or silently skips the patch.\n   Remove the entry now and re-create it in step 5 once you know whether it is\n   still needed.\n4. **Bump all of them to the same versions**, then `pnpm install`. Nothing may\n   be left behind — a single stale companion reintroduces the second `effect`.\n5. **Decide the patch** (see below): typecheck without it, and only re-create\n   it against the new version if upstream still needs the fix.\n6. **`pnpm typecheck`.** Expect real API breakage; see the classes below. Note\n   that turbo stops at the first failing package, so run `pnpm exec tsc\n   --noEmit` per package to see the true scope.\n7. **`pnpm check:npm-effect-resolution`** (after building the two public\n   packages). This is the consumer-facing proof.\n8. **The E2E deploy jobs are the real bar.** An alchemy upgrade changes the\n   deploy engine; a green typecheck says very little about it.\n\n## Pinning an unreleased alchemy build\n\nThe repo is on registry releases: `alchemy` and `@alchemy.run/prisma` 2.0.0-beta.87, `@distilled.cloud/prisma` 1.0.0-rc.20, and `effect` with its companions at 4.1.4. History: Composer pinned a preview of alchemy-run/alchemy#3101 until beta.87 released it together with alchemy-run/distilled#1076. Those two changes let `PrismaEnvironment` and Distilled's `Credentials` omit the token, which `prisma deploy` needs to send every request through the engine's client. Use a preview only when you need a fix that no release contains yet.\n\nalchemy publishes a preview of every commit on `main`, and of each pull request's head as `pr:<number>:<short sha>`. Pin it by commit, never by branch, in the `catalog:` block of `pnpm-workspace.yaml`:\n\n```yaml\nalchemy: https://pkg.alchemy.run/alchemy/<commit sha>\n'@alchemy.run/prisma': https://pkg.alchemy.run/@alchemy.run/prisma/<commit sha>\n```\n\n- **No release while a pin is a URL.** `check:publish-deps` (run by the publish workflow on every push to `main`) fails on any URL, git or `file:` dependency in a published package. Swap the pins for a registry release before merging to `main` expecting a publish.\n\n- **The commit URL is immutable.** It redirects to a content-addressed tarball (`/alchemy/-/<sha256>.tgz`). The lockfile records the commit URL and the tarball's integrity.\n- **Pin `alchemy` and every `@alchemy.run/*` package at the same commit.** They are built together.\n- **A preview's own dependencies are content-addressed URLs too.** `@alchemy.run/prisma` depends on `@distilled.cloud/prisma` by a `/-/<sha256>.tgz` URL. Pin our `@distilled.cloud/prisma` to that exact URL (read it from the tarball's `package.json`), or pnpm and npm install a second copy and `Credentials` stops matching. The commit URL for the same package does not dedupe with it.\n- **The `alchemy` peer of `@alchemy.run/prisma` is a tarball URL.** For a commit preview it may name a different tarball hash than the commit URL resolves to; the two differ only in an embedded URL in `package.json`, and npm accepts our copy. For a pull request preview (`pr:<n>:<sha>`) the peer names the same tarball the PR URL redirects to, but npm compares the specs and `npm ls` reports our `alchemy` invalid, so `check:npm-effect-resolution` fails. Pin `alchemy` to the peer's exact tarball URL then.\n- **Not every package has a preview.** `@alchemy.run/test` returns 404 at every commit, so nothing may depend on it (see the breakage classes).\n- **Read the source at the commit**, not the docs: `git clone https://github.com/alchemy-run/alchemy && git checkout <sha>`, or extract the tarball into a gitignored `wip/` folder.\n- **Move back to a registry version** once a release contains the commit: `npm view alchemy dist-tags`, then compare the release date with the commit date.\n\n## The effect-family packages a consumer installs are pinned in the public packages\n\nalchemy's `effect`-family ranges float past what its code supports (the upstream `TaggedErrorClass` drift), and a floater whose newest release names an `effect` peer that does not exist yet sends npm into hours of backtracking instead of an error (2026-09-11: `@effect/*@4.0.0-rc.114` published ahead of `effect`). Consumers carry no overrides block. Instead, the rule is:\n\n**Pin exactly, in a public package's `dependencies`, every `effect`-family package that a consumer's install will contain.** A package is in the install when it is a regular dependency of `alchemy` or `@alchemy.run/prisma`, an optional peer that one of them loads at runtime, or a package Composer's own code imports. An optional peer that nothing loads is not installed by npm at all, so it gets no pin: pinning it would install it, and everything it depends on, for every consumer.\n\nToday that is:\n\n- `@prisma/composer` — `effect` itself.\n- `@prisma/composer-prisma-cloud` — `@effect/platform-bun` and `@effect/platform-node`, which alchemy loads at runtime (`alchemy/Util/PlatformServices`, `alchemy/Http`; Composer's provider wiring also imports `@effect/platform-node`), and `@effect/platform-node-shared`, which both depend on. It also depends on `@distilled.cloud/prisma`, whose `Credentials` the provider wiring imports; keep it at the exact version `@alchemy.run/prisma` depends on (a tarball URL for a preview) so npm installs one copy.\n\nTo apply the rule on an upgrade, read `dependencies` and `peerDependenciesMeta` in both `alchemy/package.json` and `@alchemy.run/prisma/package.json`, and grep the built `dist/` of the public packages and the installed `lib/` of both for imports of each `@effect/*` package.\n\nHistory: beta.83 listed `@effect/sql-d1` and `@effect/sql-sqlite-do` as regular dependencies, so `@prisma/composer` pinned them, along with `@effect/vitest`, which it pinned on its own. Beta.84 no longer depends on the two SQL packages, and `@effect/vitest` is an optional peer that only `alchemy/Test/Vitest` loads. All three pins were dropped with the beta.84 bump. Dropping `@effect/vitest` also removed `vitest` and `vite` from every consumer's install.\n\n`check-npm-effect-resolution` installs the tarballs bare and fails when the install backtracks or resolves a second `effect`. It installs once more with npm 10, the npm that Node 22 bundles, because npm 10 has crashed on packages the tree once contained (`vitest@4.1.x`); the shape stays as a guard for Node 22 users. The only case left to a consumer's own `overrides` is an app that pins a different `effect` itself (documented in `docs/guides/deploying.md`).\n\n## Breakage classes seen in practice\n\n- **Removed `effect` combinators.** `Schedule.both`/`Schedule.either`\n  (intersection/union) disappeared at beta.97. `Schedule.both(spaced(x),\n  during(y))` becomes `Schedule.spaced(x).pipe(Schedule.upTo({ duration: y }))`;\n  `Schedule.max`/`Schedule.min` are the general replacements.\n- **Stable Effect HTTP imports.** Effect 4 uses `effect/http/*`, replacing `effect/unstable/http/*`.\n- **Alchemy lifecycle identity.** Since beta.82, provider fixtures supply `ResourceContext` (`logicalId`, `fqn`, `instanceId`, `type`) instead of `InstanceId`. Local Database, App and Bucket attributes also need `logicalId`; use `null` because local dev creates no platform rows.\n- **Vitest 5 type tests.** Stable `@effect/vitest` requires Vitest 5. Type-only files need a registered test; keep ambient declarations outside its callback or use definite-assignment fixtures inside it.\n- **Providers moved out of `alchemy` (2.0.0-beta.84).** `alchemy/Prisma` is now the separate package `@alchemy.run/prisma` (`alchemy/Prisma/Types` becomes `@alchemy.run/prisma/Types`). Add it to every package that imports it, including `@prisma/composer-prisma-cloud`, which bundles them. `alchemy` itself no longer depends on `@distilled.cloud/*` or the `@effect/sql-*` packages.\n- **`alchemy/Test/Core` is gone (2.0.0-beta.84).** It moved to `@alchemy.run/test`, which is not published. Provider tests use `scratchStack` and `runScratch` from `@internal/lowering/scratch-stack`, a port of the parts we used.\n- **Real network calls in provider tests.** At the 2.0.0-beta.84 preview, `Prisma.CustomDomain` waits for the hostname's CNAME on its authoritative nameservers before it registers a domain. Tests stub `node:dns/promises` so the wait is skipped.\n- **New adoption advice in engine or provider messages.** `withComposerAdvice` in the CLI rewrites Alchemy's `--adopt` and \"explicit adoption\" advice; its tests read every such message from the installed `alchemy` (`Plan.ts`, `Apply.ts`) and `@alchemy.run/prisma` sources and fail on one it does not rewrite. Add the new message to the rewrite list.\n- **Typed provider errors (2.0.0-beta.87).** Every lifecycle method of a `ProviderService` must fail with `Provider.ProviderError` (`{ _tag: string; message?: string }`), not `unknown`. `Effect.tryPromise` sites pass `catch: toProviderError` from `@internal/core/deploy`, which keeps an error that already has a `_tag` and wraps any other in a `ProviderFailure` with the same message and the original as `cause`. The deploy reports a wrapped error as the error it wraps.\n- **`PrismaEnvironment` holds an Effect (2.0.0-beta.87).** Alchemy runs it on every Management API request. Provide `Layer.succeed(Prisma.PrismaEnvironment, Effect.succeed({ ... }))`.\n- **New required fields on alchemy's resource-handler context** (e.g. `fqn`).\n  These surface only in the test fixtures that build the context by hand.\n- **`exactOptionalPropertyTypes` vs alchemy's types.** See the patch section.\n- **Error counts that go *up* after a fix.** TypeScript stops at the first bad\n  argument, so repairing it exposes the next one. Rising counts mid-upgrade are\n  normal, not a sign the fix was wrong.\n\n## The alchemy patch\n\n`patches/alchemy@<version>.patch` fixes one upstream type declaration:\n`ResourceClassLike.Aliases` is `readonly string[]` (exact-optional) while\n`ResourceClass.Aliases` is `readonly string[] | undefined`. Under this repo's\n`exactOptionalPropertyTypes`, the second is not assignable to the first, so\n**every** `Provider.effect` and `Provider.collection` call fails to compile —\n45 errors across three packages at the time of writing. alchemy carries\n`@ts-expect-error` at its own equivalent call sites, so this is upstream's\ninconsistency, not our misuse.\n\n**Do not work around it at the call sites.** That was tried: it needs a cast at\nroughly twenty sites, and narrowing the argument type also destroys inference\nfor the second argument, which surfaces a fresh wave of errors. Adding\n`| undefined` to the optional property fixes all of them at the source.\n\nOn every upgrade, check whether upstream has fixed it. With the\n`pnpm.patchedDependencies` entry already removed in step 3:\n\n```bash\npnpm install && (cd packages/1-prisma-cloud/0-lowering/lowering && pnpm exec tsc --noEmit)\n```\n\nClean means the patch is obsolete: delete `patches/alchemy@<old>.patch` and\nleave the config entry out. Still failing means re-create it against the new\nversion:\n\n```bash\npnpm patch alchemy@<version>   # edit lib/Resource.d.ts, then patch-commit\n```\n\nHistory: alchemy 2.0.0-beta.67 needed the patch (`lowering` alone reported 17\nerrors without it); upstream fixed the declaration by 2.0.0-beta.74 and the\npatch was deleted with that bump. The check above stays — the inconsistency\ncould regress in a future release.\n\n## The @alchemy.run/node-utils patch\n\n**Resolved — the patch was deleted with the beta.74 bump**: alchemy no longer\nships a file-lock module at all (`@alchemy.run/node-utils` 2.x exports only\n`ignore`), so there is nothing left to patch. The history and the standing\ncheck below stay, because the property it protected still matters.\n\nThe patch was\n[alchemy-run/node-utils#6](https://github.com/alchemy-run/node-utils/pull/6)\n(\"fix(lockfile): scope exit hooks to owned locks\"), vendored against\nnode-utils 0.0.5. Without it, `lib/lockfile.js` called `exitHook(...)` at module scope, so merely\nimporting `alchemy` registered a SIGINT, a SIGTERM, and an `exit` listener on\nthe process. Composer's commands run inside the Prisma CLI engine, and the\nengine owns the whole signal policy: the first Ctrl-C aborts the command and\nwaits for teardown, a second one force-exits. A stray SIGINT listener that\ncalls `process.exit(130)` on its own pre-empts that, killing the process while\nthe engine's cleanup is still running. The engine's family test suite asserts\nthat after a composer command's config evaluation the engine is the sole\nSIGINT/SIGTERM listener, and that assertion is what fails if a stray listener\nis ever reintroduced.\n\nOn every alchemy bump, re-run the standing check (the CLI's signal-listeners\ntest suite runs the same probe):\n\n```bash\ncd packages/9-public/composer-prisma-cloud && node --input-type=module -e 'const c=()=>process.listenerCount(\"SIGINT\")+process.listenerCount(\"SIGTERM\");const b=c();await import(\"alchemy\");await import(\"@alchemy.run/prisma\");console.log(c()-b,\"listeners registered by a bare import (must be 0)\")'\n```\n\n## Keeping the regression check honest\n\n`scripts/check-npm-effect-resolution.mjs` has three shapes: two healthy\ninstalls and one adversarial tree where alchemy resolves an `effect` we did not\npin. Two things about it are easy to get wrong after an upgrade:\n\n- **Do not assert the presence of a specific combinator.** That only ever stood\n  in for \"alchemy can run on this `effect`\", and it breaks the moment upstream\n  removes it for good reasons. `importAlchemy` answers the same question\n  directly: it imports alchemy's root, `Output`, `Provider` and `Stack` entries\n  from the installed app, which must succeed in the healthy shapes and fail in\n  the adversarial one.\n- **`WRONG_EFFECT` must stay a published version other than the pin.** The\n  adversarial shape used to depend on a release whose peer sat *above* our pin;\n  that stopped existing once the pin reached the newest beta, and the shape\n  quietly stopped being adversarial. It now sets the version with an npm\n  `override` instead, so it does not depend on what the registry publishes.\n\n## Gotchas\n\n- **A clean install before believing a failure.** Switching branches around a\n  dependency change leaves stale `node_modules` that produce failures unrelated\n  to the diff. `rm -rf node_modules && pnpm install` before diagnosing.\n- **Compare against `main` before blaming the upgrade.** Some suites fail only\n  under the fully parallel `turbo run test` and pass in isolation, on `main`\n  too; and `@internal/streams` reports a large pre-existing typecheck error\n  count from a third-party package's own source.\n- **`pnpm dedupe` after the pins move**, so stale peer-resolution keys do not\n  linger in the lockfile — but commit it separately, since it touches\n  resolutions beyond the ones being upgraded.\n- **`@prisma/composer`'s `dependencies.effect` must stay an exact version.**\n  `check:npm-effect-resolution` reads it and fails on a range.\n\n## What this skill does NOT do\n\n- **Decide when to upgrade.** alchemy is pre-1.0 and moves fast; this is the\n  procedure, not a schedule.\n- **Upgrade unrelated dependencies.** Keep the constellation bump its own\n  change so a deploy regression has one obvious suspect.\n- **Publish.** See [`publish-npm-version`](../publish-npm-version/SKILL.md).\n","skills-contrib/upstream-alchemy-distilled/SKILL.md":"---\nname: upstream-alchemy-distilled\ndescription: >-\n  How Prisma Composer, the Prisma Cloud target, Alchemy's Prisma provider (`@alchemy.run/prisma`), the Distilled Prisma SDK (`@distilled.cloud/prisma`) and the Prisma Management API (prisma/pdp-control-plane and its OpenAPI spec) depend on each other, and how to get a change through alchemy-run/alchemy or alchemy-run/distilled as an outside contributor without the maintainers rewriting or rejecting it. Use this whenever work will change or plans to change either upstream repository, how a `Prisma.*` Alchemy resource behaves or what it accepts (as opposed to how Composer uses it), the generated Prisma SDK, or a Management API behaviour that Composer's deploy depends on; whenever a Prisma pull request is open in either upstream repository; and to decide which repository a change belongs in before any code is written, even if the request only says \"the provider\", \"the SDK\", \"upstream\" or \"the Alchemy PR\". For moving Composer to a new Alchemy release, use `upgrade-alchemy-effect` instead.\n---\n\n# Changing Alchemy and Distilled from Prisma's side\n\n## Audience\n\nAn agent or engineer on the Prisma side whose work needs something from Alchemy's Prisma provider or the Distilled Prisma SDK. Both repositories belong to the Alchemy team. We are outside contributors there, and we maintain only the Prisma parts.\n\nIf you are about to edit a file in either repository from a Composer session, stop and read \"Work inside their repository, in its own session\" first.\n\nWhy this skill exists: between May and November 2026, Prisma's pull requests to these two repositories drew dozens of objections, rewrites and rejections from the maintainers, and several of their contributor rules were written within hours of one of ours. Almost all of it came from a few causes: working without their guidance loaded, inventing where they wanted a copy of an existing pattern, putting a change in the wrong repository, and treating their repositories as ours.\n\n## The pieces\n\n- **Alchemy** is an infrastructure-as-code engine written with Effect. A program declares *resources*; Alchemy plans and applies them. Composer turns an app into Alchemy resources, and Alchemy runs inside the `prisma` CLI to deploy them.\n- A **provider** is a package of resources for one cloud. Alchemy's Prisma provider, `@alchemy.run/prisma`, holds the `Prisma.*` resources that call Prisma's API. A resource may also have **bindings**: the runtime client a deployed app uses to reach it.\n- **Distilled** generates a typed Effect client (an SDK) for each cloud from that cloud's published API description. A **patch** in Distilled is a small JSON file that corrects the description before generation. Nobody edits the generated code.\n- **PDP** is Prisma's platform, in the private repository prisma/pdp-control-plane. Its **Management API** is what all of the above call, and it publishes its own OpenAPI description.\n- Composer's **Prisma Cloud target** and its **lowering** are the code in this repository that map an app's nodes to provider resources. `docs/design/05-prisma-cloud/alchemy-lowering.md` and the glossary (`docs/design/03-domain-model/glossary.md`) define the rest.\n\n## The chain, and who owns each link\n\nChecked 2026-11-27. Each cell says where to check it again.\n\n| Link | Where it lives | Owner | How a change leaves it |\n| --- | --- | --- | --- |\n| 1. Management API | prisma/pdp-control-plane | Prisma | Deployed to production |\n| 2. OpenAPI spec | Published by the API itself (the mirror's fetch script has the URL) | Prisma | Changes when link 1 deploys |\n| 3. Spec mirror | A git repository the Alchemy team runs, named in Distilled's `.gitmodules` | Alchemy team | Copies the published spec on a schedule (its workflow file has the schedule; daily when checked) |\n| 4. Distilled Prisma SDK | alchemy-run/distilled, the Prisma package: generated code plus patches | Alchemy team; we contribute to the Prisma package | A pull request moves the mirror pin, regenerates, and adds or prunes patches |\n| 5. Alchemy Prisma provider | alchemy-run/alchemy, the Prisma package. Alchemy takes Distilled as a git submodule pinned to one Distilled commit (its `.gitmodules`) | Alchemy team; we contribute to the Prisma package | A pull request, then an Alchemy release |\n| 6. Composer | This repository. Versions are pinned in `pnpm-workspace.yaml` | Prisma | A pin bump, then a Composer release |\n\nEach link is built from the one before it. Composer is the exception to \"only talks to its neighbour\": it also uses the Distilled SDK's credentials type directly and calls the Management API itself for a few things, so a Distilled change can reach Composer without an Alchemy change, and Composer's Distilled pin has to match the one the provider depends on.\n\nWhat follows from this shape:\n\n- **Composer implements no Management API resources itself.** It composes the upstream provider's resources and writes its own only where upstream has none or no API exists behind them. That is a recorded decision: read `docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md` before proposing anything that changes it.\n- **Composer depends on two Alchemy things**: the engine (`alchemy`) and the Prisma provider. A fault in the engine or in another provider is their code, not ours. Describe it to the operator as an issue to raise with them; do not fix it.\n- **Distilled reflects the published spec.** A patch states only what their current rule accepts as evidence (the spec, a real response, the provider's own docs or client). The maintainers' position, on one of our pull requests: \"you work at Prisma, if consumers of the api need to know ... that should go in the API, not a patch in our SDK that adds a value the spec doesn't have.\"\n- **Alchemy calls the cloud only through Distilled.** No hand-written client and no status-code checks in the provider. A missing operation or error type is a Distilled change.\n- **The spec's own markings travel down the chain.** For example, operations the spec marks experimental have been moved to a separate module of the SDK, which changes the imports of every provider file that uses them once Alchemy takes that version.\n- **A change moves only as fast as its slowest link.** The mirror has its schedule, each upstream pull request waits for a maintainer, and Composer can only pin a release or a preview build. Plan the order before starting and tell the operator how many upstream pull requests it means, counted by their rules. Each costs the maintainers a review. An instruction from our side to keep it to one does not change their rule: say what count their rules produce and why, before starting.\n- **Links 1 and 2 are the only ones we control.** When something is hard to express downstream, the cheapest correct fix is usually in our own API or spec.\n\n## Decide where the change belongs\n\nWork this out before writing code, from the top of the chain down. The first link where the needed fact is missing is where the change starts.\n\nWhichever case it is: before offering any opinion on how a platform resource should be modelled, read that resource's design documents in prisma/pdp-control-plane (its `docs/` folder). They define the lifecycle you will model. Code on its `main` is not the design, and states that look like defects, such as a resource that stays pending, are often intended.\n\n**The API must behave differently, or expose something it does not.** Start in prisma/pdp-control-plane. Ship to production, wait for the mirror, then a Distilled pull request, then an Alchemy pull request, then an Alchemy release, then Composer's pins. If the change would break the provider that is already released, ship it so the old behaviour keeps working, have the operator tell the maintainers before it ships, and remove the old behaviour only after an Alchemy release carries the new provider. The maintainers once discovered on their own that a platform change had broken a feature for every Alchemy user.\n\n**The API already does it and the spec says so, but the SDK is older than the spec.** A Distilled pull request that moves the mirror pin and regenerates; their repository has a skill for it. Check their `main` first, because maintainers regenerate too. A regeneration carries every spec change since the old mirror pin, not only the one you came for: say in the description what else it brings.\n\n**The API does it but the spec does not say so** (an undeclared error response, a field that can be null). Prefer fixing the spec in pdp-control-plane: we own it and every consumer benefits. The SDK still has to be regenerated from the new spec afterwards, by the maintainers' own regeneration or by ours, so check their `main` before opening one. A Distilled patch is for a gap we cannot close quickly, with the evidence their rules ask for.\n\n**The SDK's own runtime code for Prisma must change** (its credentials layer, a hand-maintained module in the Prisma package). A Distilled pull request of its own; by their rule it does not share one with a spec fix or a regeneration.\n\n**Only the provider's behaviour or shape must change.** An Alchemy pull request. A change to what a resource accepts or returns is breaking for every Alchemy user, not only Composer, and their conventions say how to mark and explain that. Composer's lowering and its local stand-in providers bind the same resource classes, so they change with it.\n\n**The Alchemy change needs Distilled code newer than Alchemy's pinned commit.** See \"The Distilled pin\" below before doing anything.\n\n**Only Composer needs something to be different.** First try to meet the need in Composer: build a different Layer, wrap the resource, or write a Composer-owned resource where the recorded decision allows one. An option added upstream to serve our embedding has been refused (\"The user shouldn't provide them. If they want to override them, they can construct a new layer.\"). Go upstream only when the need would exist for any Alchemy user.\n\n**You need an upstream change that is not released, or not merged, to check the Composer side.** Alchemy publishes preview builds of commits and of pull request heads. The `upgrade-alchemy-effect` skill covers pinning one and what it blocks.\n\n**It is none of these.** A change to Distilled's shared core or generator, or to Alchemy's engine, for a need only Prisma has, fits nowhere above; Distilled's written rule is that one provider's rule stays in that provider. Describe the need to the operator as a scenario and say which link you think it belongs to.\n\n## What is ours and what is not\n\nIn both repositories we own the Prisma package and its tests, docs and examples. Everything else belongs to the maintainers. Offering to do their upkeep is not a courtesy: it puts our name on changes to code we do not maintain, and it spends the operator's time and machine on work they do anyway.\n\nTheir guidance (as read in November 2026) is written for their own agents, who own the whole repository. So it tells its reader to do some things that an outside contributor should not do unasked. On these, the limits here hold, because each comes from what happened when we did it. If their guidance ever addresses outside contributors directly on one of them, theirs wins and this skill needs a fix.\n\n- **Moving the Distilled pin past our own change.** Their instruction to move it to the merged commit we follow as written. Moving it further, or testing what a move does to other providers, is theirs. See the next section.\n- **Checking the whole repository.** Their guidance says to type-check the whole workspace before a commit. Run the type check for the Prisma package and the test files your change touches. Their CI checks everything else on the pull request, so read it. A whole-workspace run on the operator's machine reports errors in other people's code that we will not fix.\n- **Opening early drafts that carry a status report.** Their own agents do this for work in progress. Our drafts have been finished by a maintainer, merged before we were done, or left to rot. Open a pull request when the work is complete.\n- **Rebasing at checkpoints.** Once a branch has a pull request, merge their `main` into it and never force-push: maintainers push to our branches, and a force-push discards their commits and their place in the review.\n\nAlso not ours: other providers' code, shared core, the generator, the engine, repository-wide configuration, and the lockfile beyond what our own dependency change requires.\n\nWhen a previous session's handover lists upstream work, check each step against this section before doing it. A handover is a predecessor's plan, not the operator's approval. That covers its working copies and its open pull requests too.\n\n### The Distilled pin\n\nAlchemy pins one Distilled commit for the whole repository. An Alchemy change that needs newer Distilled code cannot build until that pin includes it.\n\nTheir skill for provider work tells its reader to land the Distilled change first, then move the pin to the merged commit and commit it. We follow that as written, without asking first, until a maintainer tells us otherwise (the operator's decision, 2026-11-27): the move is from one of their commits to another of their commits, and it is what their own guidance asks for. If a maintainer does say otherwise, do what they say, and add it to this section with its date.\n\nWhat stays theirs is everything beyond that one step. Move the pin to the exact commit our Distilled change merged as, and nothing later: when one of ours moved it further, it pulled in other providers' SDK changes and broke two of their type checks, and a maintainer re-pinned it himself. Do not test or fix other providers against the new pin. A pin pointed at a commit that exists only on our fork cannot be fetched by anyone else, so it can never merge.\n\nThese steps apply the same way to a pull request that is already open.\n\n1. Open the Distilled pull request complete. Build and test the Alchemy change locally by checking the Distilled branch out in your working copy of the submodule without committing the pointer, and keep it on a fork branch with no pull request. Their rules ask a breaking Distilled change to link the Alchemy change that adapts to it: link the fork branch and say its pull request opens once the Distilled change has merged. An Alchemy pull request that cannot build is unfinished work, so it is opened early only if a maintainer asks for it, and then as a draft that says so.\n2. Once the Distilled change merges, move the pin to that exact merged commit, in a commit of its own, and say so in the description with the commit's hash. If the pin has to pass over other Distilled commits to get there, check that the Prisma package still builds and its touched tests pass, and name in the description anything in that range that changes the Prisma SDK.\n3. Then open the Alchemy pull request. If their CI fails in other providers because of the pin, report that to the operator; do not fix other providers.\n4. A pull request that already carries a pointer to our fork is repaired with a new commit that restores their pin, never a force-push.\n\n## Work inside their repository, in its own session\n\nDo not edit an upstream repository from a clone inside a Composer worktree, and do not send subagents from a Composer session to work there. An agent gets a repository's instructions in full only when its session starts in that repository. From anywhere else it gets Composer's rules plus whatever fragments of theirs it happens to search for. That is how a reviewer came to judge Alchemy code against Composer's review checklist, and how Distilled's contributor rules were first read one minute before a pull request was opened.\n\n**How.** Start a new agent session whose working directory is a checkout of the upstream repository, with whatever your harness offers for that, or ask the operator to open one and hand them the brief to paste as its first message. If you can do neither, stop and ask; a subagent pointed at the folder is not a substitute, because it inherits this session's instructions.\n\n**Where.** A clone of the fork we push from, outside every Composer worktree, where the operator keeps such clones (ask once). One checkout per agent: the installed dependency tree is shared state, and two agents in one checkout have broken each other's runs.\n\n**Distilled is its own repository.** Alchemy vendors Distilled as a submodule and its own guidance has its agents patch and regenerate there. For us a Distilled change runs in a session started in a Distilled checkout, so Distilled's contributor rules are loaded. Do not install dependencies inside Alchemy's copy of Distilled: Alchemy's workspace supplies them, and a second install there has broken the checkout.\n\n**Work already in the wrong place.** If a predecessor left clones with commits inside a Composer worktree, move the work, do not continue it there: push its branch to the fork and start the upstream session on that branch. If that branch already has a pull request, push the unfinished work under a new branch name instead, so nothing unfinished lands on a branch a maintainer may merge.\n\n**\"Just do it here.\"** A message that hands you a clone inside the worktree, or says \"do that\", was written before the operator heard the concern, so it is not yet their decision. Say once what goes wrong without their instructions loaded, offer to write the brief for an upstream session, and ask. Then do what they decide. If they decide on in place, read that repository's guidance in full by hand before touching anything, and say in your report that it was done that way.\n\n**Reading is not editing.** A Composer session may read upstream source, guidance, issues and pull requests to work out which link a change belongs in. It does not edit there and does not propose a resource's shape.\n\n**Two repositories, two sessions.** When a change needs both, the Composer session coordinates: the Distilled session first, then the Alchemy session against the Distilled branch. Record in the project's plan where each checkout is and which session owns it, so a successor does not ask the operator again.\n\n**What stays in the Composer session:** what the work is for, what Composer needs from upstream, the project record under `.drive/`, and the brief. It does not recommend a resource's shape to the operator: what an upstream resource looks like to an Alchemy user is proposed by the upstream session, after its reading, and goes to the operator before it is built. A recommendation made from the platform's side alone has had to be reversed once the existing Alchemy pattern was read.\n\n**The brief** for the upstream session says:\n\n- What the change is for, and the design as our best effort: the purpose is fixed, the mechanism is open to challenge against their code and conventions.\n- Where the platform's design documents for the resource are, and that it reads them before modelling a lifecycle.\n- The absolute path of this skill's folder, and that it reads `SKILL.md` there. Composer's skills are not installed in their repository.\n- The limits in \"What is ours and what is not\".\n- That a change to what users declare or see goes back to the operator before it is built.\n- That rules meant for pull requests in our own repositories do not carry over: our description style, any line naming the agent, auto-merge, and merging it ourselves. Upstream, the maintainers merge. An independent review before the pull request opens is still worth having, judged against their guidance and not our own review checklist.\n\n**The first things the upstream session does**, before any design opinion or code:\n\n1. Read the repository's agent guidance in full, not by searching it: the root instruction file, what it links for outside contributors, the pull request template if there is one, and the repository's own skills for the kind of change in hand. These files change often. They are the authority on how code, tests, names, commits and descriptions look in their repository, and they win over this skill on all of that.\n2. Find where the repository already does the same job (another provider's resource of the same kind, a binding, a test fixture, a credentials layer) and read it. Copy its names, shape and mechanism.\n3. Search their open issues and pull requests for the same problem. We once built something they already had an open issue for, and they shipped their own design within days.\n4. Check that their `main` has not already fixed it, and check again each time you merge their `main`.\n\n## What the maintainers hold to\n\nThese have held across the record so far. Each has its reason, so you can judge a case their files do not cover.\n\n- **Follow what exists; invent nothing.** They value a consistent repository over a locally better idea (\"I prefer the repo to be consistent\"; \"This isn't something we typically do\"). A concept, name, option or branch that no other provider has will be rewritten. When you believe a departure is right, say in the description why the existing way is not enough, before they ask.\n- **A resource is not finished when it deploys.** They have expected its runtime bindings, and for compute an Effect-native form, in the same piece of work. Find out from their guidance what the resource kind requires and count it before telling the operator the size.\n- **Alchemy provider changes are proven by deploying real resources.** No fakes, mocked responses or direct lifecycle calls. Our tests were rewritten as live tests on six pull requests, five of them by the maintainers' own commits, and the live versions found provider bugs on at least four. A failure the real platform cannot be made to produce comes from a fixture that misbehaves, or is not tested. Distilled's testing rules are different; read each repository's own.\n- **Live tests need a test account.** Ask the operator for a token to a workspace used only for tests, and where it is kept; never print it; get it before the pull request opens. Do not assume a deploy token you already have points at such a workspace. Their guidance has an account-wide teardown for leaked test resources. Run it only against that test workspace, and only with the operator's yes.\n- **A provider leaves alone what the stack did not declare or create.** Omitted props mean \"not managed\", not \"reset to a default\". A resource the provider finds but cannot prove it created is not owned until the user adopts it. Nothing a provider provides may change what other providers in the same stack see.\n- **Effect throughout**, in source, docs and examples alike, because examples teach users.\n- **One change per pull request, by each repository's own definition.** Distilled's is written and narrow: a spec fix and a runtime change are two. A correct fix of ours was lost there because it shared a pull request with a rejected feature, and a description that says it breaks a rule on purpose is read as exactly that. In Alchemy a resource with its bindings, tests and docs has been one change, and one piece of work opened as three pull requests was joined into one by its author soon after.\n- **Descriptions are short and say what the user can now do.** In both, the pattern they kept when rewriting ours was one plain sentence, then a code or diff block, a few bullets, and a marked breaking change. They cut status reports, test logs, file lists, long justifications and agent name lines. Use the format their current guidance and template give; the two repositories differ (in November 2026 Distilled had a template with a checklist and required a signed note on anything an agent wrote, while Alchemy forbade checklists, test sections and large headings), so do not carry one's format to the other. Have a reader with none of our context check the description against their conventions before it goes up.\n- **Names are theirs.** Name a resource after the platform's own product name. A name suggested as a question is a request: act on it or answer it in the next push.\n- **Their decision is the decision.** When a maintainer says they are solving it another way, ask how to fit into their design, then close ours with a line saying why, or redo it on theirs. Restating our case has not changed an outcome so far, and they have shipped their own version within hours. A real technical reason, stated once and plainly, has been accepted.\n\n## How their pull requests move\n\nPlan around what they do, not around what a pull request's state suggests.\n\n- **So far no maintainer has submitted an approving review on one of ours.** They comment, push commits to our branch, rewrite the description, and merge. Keep maintainer edits allowed.\n- **A draft is a signal, not a lock.** A maintainer has taken one of our drafts out of draft and merged it minutes later, at a commit we meant to add to. Every commit pushed to a branch that has a pull request must be safe to merge as it stands. If more is coming, it is in the pull request before it opens, or it is a separate change. Unfinished work lives on a fork branch that has no pull request; pushing there is yours to do.\n- **They read, run and fix drafts,** and do not chase. Good small changes have merged in under an hour; ones that needed work waited weeks with one comment or none.\n- **Keep it mergeable and green.** Merge their `main` when it conflicts. Take their side for every file our change does not own, then check the diff for files we never meant to touch; a merge of ours once silently deleted features from their `main`. Fetch before every push.\n\nSomeone has to know when a maintainer acts. Watch each open upstream pull request for comments, pushes, state changes, merges, failed checks and conflicts with their `main`, with whatever your harness offers. Write the watched pull requests into the project's plan, so a session that restarts finds them and sets the watch up again (background commands do not survive a restart). Tell the operator who did what, including when a merge happened with no review.\n\n## Speaking to the maintainers\n\nA maintainer here means someone who merges in that repository. Check who a commenter is before weighing what they say.\n\nOpening, editing, marking ready, commenting on or closing an upstream pull request speaks to another team in the operator's name. Those steps are the operator's, or need their explicit yes each time. Never turn on auto-merge or merge upstream.\n\n- Find out which GitHub account your shell acts as before planning these steps. Work out the whole sequence of operator steps once, in order, as commands that are safe to run twice and that say where to run them, and ask once.\n- After any GitHub write that reports an error, read the state back from GitHub before saying what happened.\n- When a maintainer asks or requests something, bring the operator the question and a finished draft answer in one message the same day, in the format their rules require for text an agent wrote. A question of ours that went unanswered got its pull request closed, and others waited a week or more. Where the request is a code change inside the agreed design, such as a rename, push it without waiting and say so in the draft. Do not post it yourself.\n\n## When the operator's request and this skill pull apart\n\nThe operator may ask for the very thing this skill warns against: finish it in the clone here, keep it to one pull request, make sure nothing else breaks, defend the option, add it to the SDK anyway. They may not have the earlier incidents in mind when they ask. Say once, briefly, what happened the last time and what you would do instead, and ask. Their answer decides anything on our side: where the work is done, how much we check, what we propose. It does not change the maintainers' rules or decisions. Where the request is something a maintainer has already refused, the next step is the operator raising it with them, not a pull request that tries it again.\n\n## After it merges\n\nA merged upstream pull request changes nothing in Composer until Alchemy releases and Composer's pins move. The `upgrade-alchemy-effect` skill covers the bump. Update the project's plan in the Composer pull request that consumes the release, and tell the platform's owners when a removal there was waiting on the provider.\n\n## Before asking the operator to open or mark ready an upstream pull request\n\n- The work was done in a session started in that repository, with its current guidance read in full in that session.\n- It touches only the Prisma package, or each file outside it copies an existing shape and is explained in the description.\n- The Distilled pin is at the exact commit our Distilled change merged as (or where a maintainer said to put it), in a commit of its own, and nothing points at a commit that exists only on our fork.\n- Alchemy: every behaviour is covered by a test that deployed for real, and you ran the ones your change touches. Distilled: each patch has its evidence.\n- It is one change by that repository's definition.\n- The description follows their current format, and a fresh reader has checked it against their conventions.\n- Nothing in it is unfinished, and every commit on the branch is safe to merge today.\n- The pull request is written into the project's plan, and a watch on it is in place.\n\n## What this skill does not cover\n\n- Moving Composer to a new Alchemy release or a preview build: `upgrade-alchemy-effect`.\n- How to write a provider, a patch or a test in their repositories: their own guidance and skills, loaded by working there.\n- Reviewing an outside contributor's pull request to our own repositories.\n- Design decisions inside Composer or the platform: each repository's design documents.\n","skills/README.md":"# Prisma Composer skills\n\nAgent skills for [Prisma Composer](https://github.com/prisma/composer) — one\n`SKILL.md` that teaches an LLM agent how to write, test, and deploy a Prisma\nApp without re-deriving the API from documentation each time.\n\n## What's in the box\n\nOne skill, `prisma-composer-core-concepts`, covering the whole story: the mental model\n(Modules, `compute()`, `service.load()`), RPC contracts, databases, reusable\nmodules (cron/storage/streams), config params, secrets, testing\n(`mockService`/`bootstrapService`), deploying (`prisma deploy`,\nenvironments, removing an app or an environment), and the production pitfalls. Composer's surface is small\nenough for one skill; there is no router or per-topic cluster.\n\n## Install\n\nThe skill ships inside the `@prisma/composer` tarball, so installing the\npackage is what brings it in. `prisma skills sync` (from the `prisma` CLI)\ncopies it out of `node_modules` into the skill directories the agent runtimes\nread — `.claude/skills/`, `.cursor/skills/`, `.agents/skills/`,\n`.windsurf/skills/`:\n\n```bash\npnpm add @prisma/composer\npnpm add -D prisma\npnpm prisma skills sync\n```\n\nAdd it to your project's `postinstall` so an upgrade brings the matching skill\nwith it:\n\n```jsonc\n// package.json\n\"scripts\": {\n  \"postinstall\": \"prisma skills sync || exit 0\"\n}\n```\n\nIn a monorepo (a pnpm, npm or Yarn workspace), put the hook in the `package.json` at the workspace root (the directory with `pnpm-workspace.yaml`, or the `package.json` that lists `workspaces`), not in a workspace package's: hooks in several packages run at the same time and can leave the skill copy at the root missing a file. The root's sync installs the skills of every workspace package. List `prisma` there as a dev dependency, at the version your packages use, so the root's hook can find the command. If `prisma` warns with `SKILLS.MEMBER_LEFTOVER`, a workspace package still has something an earlier `prisma` put there: move the hook to the root, and delete the other files the warning names, such as old skill copies.\n\nThe version you read is then always the version you installed: the skill's\nfrontmatter carries `metadata.library: \"@prisma/composer\"` and a\n`metadata.library_version` stamped by the release that built the tarball\n([`scripts/set-version.ts`](../scripts/set-version.ts);\n[`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs)\nproves it against the packed artifact).\n\n### Without installing the package\n\nThe GitHub source stays available for anyone who wants the skill without\n`@prisma/composer` in their project:\n\n```bash\nnpx skills add prisma/composer\n```\n\nThe [`skills` CLI](https://npmjs.com/package/skills) installs it at the\nproject level for the agent runtimes it detects (`-a <agent>` to pick one).\nNothing keeps this copy in step with your packages, so pick the git ref\nmatching your `@prisma/composer` version by hand and re-do it on every\nupgrade.\n\n## Authoring rules\n\nThe skill is the agent-condensed mirror of the human guides in\n[`docs/guides/`](../docs/guides/) — the guides are canonical for humans; a\nsurface change lands in both. For anyone editing the skill:\n\n- **Verify every claim while drafting, not in a final pass.** Every import\n  must resolve against a `packages/9-public/*` export map, and every CLI\n  flag/command against `packages/0-framework/3-tooling/cli/`. If ripgrep finds\n  nothing, the surface doesn't ship — name it under *What Composer doesn't do\n  yet* instead of extrapolating.\n- **The skill must be self-contained.** It gets installed into other repos, so\n  no link may resolve outside `skills/prisma-composer-core-concepts/`. Repo\n  docs may be\n  named in prose (\"`docs/design/10-domains/testing.md` in the prisma/composer\n  repo\"), never linked relatively.\n- **Teach concepts, not procedures.** Name the moving parts and the command\n  that reveals each piece of state; reserve numbered steps for one-safe-path\n  operations.\n- **Leave the `metadata` stamp alone.** `metadata.library` names the npm\n  package the skill ships inside, and `metadata.library_version` is rewritten\n  by [`scripts/set-version.ts`](../scripts/set-version.ts) on every release —\n  hand-editing the version, or dropping either key, breaks the release script\n  and [`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs).\n  They live under `metadata` because the Agent Skills spec defines the\n  top-level keys and reserves that map (string → string) for publisher\n  extensions. A new skill needs both keys, with any placeholder version.\n- **Folder name and frontmatter `name` must match** — the runtimes key on the\n  frontmatter, humans on the folder.\n\nMaintainer-facing skills (release process, commit conventions) live in\n[`../skills-contrib/`](../skills-contrib/), not here.\n","skills/prisma-composer-core-concepts/SKILL.md":"---\nname: prisma-composer-core-concepts\nmetadata:\n  library: \"@prisma/composer\"\n  library_version: \"0.41.2\"\n  version: 2026.9.1\ndescription: >-\n  Use when deploying or managing an app that uses Prisma Composer\n  (`@prisma/composer`): wiring its services and Modules, running it locally,\n  testing composed services, or standing up / tearing down an environment.\n  Triggers on \"prisma composer\", \"@prisma/composer\", \"prisma app\",\n  `prisma deploy`, `prisma dev`, `compute()`, `appRoot()`, `module()`, `contract()`,\n  `service.load()`, `mockService`, `bootstrapService`.\n---\n\n# Prisma Composer core concepts\n\nA **Prisma App** is a tree of typed declarations composed in TypeScript and\nhanded to the `prisma` CLI, whose two main Composer commands are `prisma deploy`\nand `prisma dev`. Removing a whole app is `prisma project delete`. Removing\none environment and reading logs are not commands; they are the `destroy` and `log`\noperations of `@prisma/composer/control`, called from a script.\nThis file covers structures, hierarchies, relationships, and workflows: the\nconcepts you cannot observe from the code or the CLI's help output. It is not\na CLI reference; discover each command's flags with `prisma <command> --help`\nrather than inferring them. The Prisma platform moves fast, so treat this file as the\nstable conceptual core and find current, fuller documentation at\n<https://www.prisma.io/docs>. For working code, read `examples/` in the\nprisma/composer repo.\n\nTwo principles govern everything and are binding\n(`docs/design/01-principles/`):\n\n1. **Your code never reads environment variables.** Dependencies, configuration,\n   credentials, and the port all arrive through the service node, typed.\n   `process.env` is never the answer.\n2. **Composer never bundles or transforms your code.** You build with your own\n   bundler; the framework assembles the built output by deterministic steps\n   and hands it to the configured deploy target.\n\n## Declarations are data\n\nEverything you author is a declaration: plain data describing a piece of the\napp, executing nothing when imported. Three node kinds exist:\n\n| Kind | Declared with | Purpose |\n| --- | --- | --- |\n| Service | `compute()` | A running unit of your code; atomic, Composer sees only its boundary |\n| Resource | `rawPostgres()`, `bucket()` | A stateful managed dependency |\n| Resource: public URL | `publicUrl()` | Makes one service reachable from the internet at one hostname; depends on the service's exposed HTTP interface and exposes nothing |\n| Module | `module()` | A grouping boundary; runs no code of its own, depends on and exposes typed interfaces; its builder receives `deps`, `input`, `environment` and `provision` |\n| App root | `appRoot()` | The outermost module, the entry's default export; no `deps` or `expose`, and nothing can provision it; its builder receives `input`, `environment` and `provision` |\n\nNodes connect through typed **interfaces**: `deps` declares what a node depends on, `expose` declares what it exposes. Wiring happens in a Module's builder via `provision()`, and the app root, built with `appRoot()` and handed to the CLI, is the App:\n\n```ts\n// module.ts\nimport { appRoot } from '@prisma/composer';\n\nexport default appRoot('store', ({ provision }) => {\n  const catalog = provision(catalogModule);\n  provision(storefrontService, { deps: { catalog: catalog.rpc } });\n});\n```\n\nBecause interfaces are typed, **the compiler verifies every wire**. A dependency wired to the wrong producer, a missing RPC handler, a literal input value of the wrong shape: all of it fails `tsc`, not the deploy. Values from outside the code are the exception: a root input field exists only at deploy, and a platform variable only on the platform, so a schema refinement the type does not carry and a missing platform variable a service needs surface as early deploy-time refusals instead (see Two channels below). Typecheck, then build, then deploy; don't use the cloud to find out whether the wiring is correct.\n\nComposer itself is target-agnostic: `@prisma/composer` carries authoring, testing, and the CLI, coupled to no platform. A deploy target is an extension registered in the deploy config; `@prisma/composer-prisma-cloud` is the Prisma Cloud target and the one this skill's deploy sections assume. Its root exports `compute`, `rawPostgres`, `bucket`, `publicUrl`, `variable`, `generatedParam` and `serviceOrigin`; the ORM vocabulary (`postgres`, `dataContract`) lives under the `/orm` subpath, alongside the shared `/cron`, `/storage`, `/streams`, `/auth`, and `/email` modules. These are the only two Composer packages a basic Prisma Cloud app needs, and nothing installs them for you: a fresh project starts with neither, so add both as dependencies first. An extension adds its own `prisma-composer-*` package alongside them. Compose an existing Module before implementing a capability yourself; wiring one in is a couple of lines.\n\nWithin the entry graph (everything reachable from `module.ts`), write\nrelative imports with explicit `.ts` extensions (`./service.ts`, with\n`allowImportingTsExtensions` in tsconfig): that form resolves everywhere.\n`prisma deploy` and `prisma dev` also map `./service.js` and extensionless\n`./service` to the `.ts` source, but other tools may not.\n\n## The service node is the only doorway\n\nYour runtime code receives everything from the service declaration it\nimports:\n\n1. `service.load()`: dependencies (typed RPC clients, database bindings).\n2. `service.input()`: the whole input as one schema-validated object;\n   credentials in it are redacting `SecretString` boxes.\n3. `service.port()`: the reserved port to bind (default 3000).\n\nA service declaration is pure data; the server entry is what your build\nproduces and the platform boots:\n\n```ts\n// service.ts\nexport default compute({\n  name: 'auth',\n  deps: { db: rawPostgres() },\n  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),\n  expose: { rpc: authContract },\n});\n\n// server.ts\nconst { db } = service.load(); // { url }: you construct your own client\nconst handler = serve(service, {\n  rpc: { verify: async ({ token }) => ({ ok: token.length > 0 }) },\n});\nBun.serve({ port: service.port(), hostname: '0.0.0.0', fetch: handler });\n```\n\nThe consumer declares `deps: { auth: rpc(authContract) }` and gets a typed\nclient back from `load()`.\n\n## Two channels: dependencies and input\n\n| The value is… | Declare | Provide | Read |\n| --- | --- | --- | --- |\n| produced by another node | `deps: { db: rawPostgres() }` | wire at `provision()` | `load()` |\n| anything else (config or credential) | one field of the `input` schema | bind at `provision()`: literal, root input field, platform variable node's value, or a `resolve()` value | `input()` |\n\nThe service declares its whole incoming configuration, plain values and credentials together, as **one [Standard Schema](https://standardschema.dev)** (arktype is the house choice). A credential is a field typed as `secretString()` from `@prisma/composer/arktype` (or `@prisma/composer/zod` for a Zod schema; the app installs `arktype` 2 or `zod` 4 itself, and Composer uses that copy); conditional legality (\"no stripe key unless billing is on\") is an ordinary schema union. The binding at `provision()` mirrors the schema's shape.\n\nA value you supply, rather than write in code, arrives in one of two ways:\n\n- **A value the deploy reads** is a **root input field**: a field of the app root's `input` schema, filled by the `config` adapters (by default the deploying shell), checked by the root's schema before anything is created. The root passes it on by name. Only these can be listed in `resolve()` or put in a resource's props.\n- **A value the service reads at boot** is a **platform variable node**, provisioned in the app root: `provision(variable({ name: 'EMAIL_FROM' }))` for a plain value, `provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }))` for a secret. `provision()` returns the value with `id`, the node's address, on it; pass it down through module inputs to the services that read it. The node names the variable and never carries its value; the operator sets the value on the platform.\n\n```ts\nexport default appRoot('shop', { input: type({ EMAIL_FROM: 'string' }) }, ({ input, provision }) => {\n  const stripeKey = provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }));\n  provision(billing, { input: { from: input.EMAIL_FROM, stripeKey } });\n});\n```\n\n**Only `appRoot()` can provision a platform variable node.** A variable's name is one space per deployed app, and the root is the app. In a `module()` body (a nested module or a `module()` root) `provision(variable(…))` fails to compile, with an error naming `appRoot()`. A module that needs the value declares a field in its `input`. The node creates nothing on the platform and stays out of the application topology and the deploy report; the loaded graph lists it and, in `graph.valueReads`, each service that reads it. Its default id is the name in camel case (`EMAIL_FROM` is `shop.emailFrom`); two nodes whose names give one id fail with an error naming both, so pass `{ id }`.\n\nRules that bite:\n\n1. **Secretness is checked by the binding's type and by the deploy.** A `provision()` binding, a service's or a module's, is typed from the schema: a literal or a `SecretBox` where the schema expects `SecretString`, or a platform secret's value in a text field, fails to compile, and the deploy refuses it where the schema has no types. An ArkType schema with a `SecretString` field cannot also transform its input: a morph anywhere in it (`'string.trim'`, `.pipe()`, `field(type('string.integer.parse'))`) or `'+': 'delete'` copies the input, the copied secret loses its value, and the deploy refuses it. Transform in the service code instead; a Zod schema keeps the box.\n2. **A plain platform variable's value is known only at boot: text, or the type its `schema` declares.** Bind it to a field wrapped with `field()`. A platform variable's value goes into a field of an `input` only. A compute service has one per-key param, the reserved `port`, which takes a literal or a root input field and no source, because the deploy needs the port before the service exists; every other value is a field of its `input`. A field of a narrower type, such as `email()`'s `deliveryMode`, takes a root input field declared with that type instead, for `email()` from the exported `emailDeliveryModes`; the deploy reads a root input field from the app configuration on every deploy and writes its value into the input document. A platform secret fits a `secretString()` field only. A platform variable's value always lives on the platform. The operator sets it there with `prisma project env add 'NAME=<value>' --project <id> --role production`. Use `--role preview` for every preview environment, or `--branch <environment>` for one. The deploy does not copy local values (`.env`, the shell) to platform variables. The deploy fails only when a variable that a service's schema requires has no value. The error names the variable and the command that sets it. The other variables with no value print under `Platform variables with no value:`. Prisma Cloud reports a service that exits at boot as running and promotes it; read the error with `prisma service logs <service>`.\n3. **The schema decides whether a field may be absent.** A field bound to a platform variable that is unset or empty is left out at boot. That is allowed only if the schema allows it, for example with an optional field or a union member. An optional root input field that the adapters do not supply is left out at deploy. The deploy report prints the serialized input document (each secret shown as `$platform VAR`) and every key that resolved absent. On Prisma Cloud the deploy writes the input document into the service's artifact, not into a `COMPOSER_*` variable, so it is not limited to a variable's 8 KB, and a changed document redeploys exactly that service.\n4. **The reserved `port` is outside the schema.** Read it through\n   `service.port()`, never `process.env`. The framework also exports `PORT`\n   for Next.js standalone, which binds it itself.\n5. **A Module passes a secret on without learning the platform name.** Declare a `secretString()` field in the Module's `input` and pass `input.<field>` on as a binding leaf; the app root provisions `variable.secret({ name: 'NAME' })` and binds its value. A module has no `params` or `secrets` slots: `module()` and `provision()` refuse both, naming `input`. A service's `params` stay.\n6. `input.apiKey.expose()` is the only way to a secret's value; the box\n   redacts everywhere else (logs, JSON, errors).\n7. **Platform variable names are upper case**: `^[A-Z][A-Z0-9_]*$`. `COMPOSER_…`, `DATABASE_URL`, `DATABASE_URL_POOLED`, `PORT`, `PATH` and `HOME` are reserved, each name is declared by one node, and one name cannot be both a platform variable and a root input field. A node's value bound as a service's whole input is refused too. Each fails before anything is created, naming the variable and the addresses.\n8. **A field bound to a plain platform variable, `serviceOrigin()` or a plain `generatedParam()` is wrapped**: `field(type('string'))`. At deploy the schema sees a pointer, and a plain `'string'` field refuses it: a compile error in a service's or a module's binding, and a deploy error where the schema has no types. `service.input()` and `mockService`'s input double read the field as its inner type.\n9. **A platform variable holds text; `schema` says what the text means.** `variable({ name: 'SMTP_PORT', schema: type('number') })` (any Standard JSON Schema library: ArkType, Zod) gives a runtime value of type `number`, which fits `field(type('number'))` and not `field(type('string'))`; without `schema` the value is the text and the reverse holds. An object schema fits a `field()` of the same object type. A schema that accepts only text gives the text exactly, untrimmed; any other schema reads the text as JSON (`587`, `true`, `{\"host\":\"h\"}`, `null` under `number | null`). A schema that accepts both, such as `string | number`, `z.unknown()` or `string | null`, is refused when the root body runs; for an optional text variable declare the text type and make the service's field optional. `variable.secret()` takes no schema.\n10. **Boot decodes and validates the text against the variable's JSON Schema, then the service's schema runs.** A failure fails boot, not the deploy: read it with `prisma service logs <service>`. Messages name the variable and never hold its text: `The platform variable \"SMTP_PORT\" does not hold a number. Its schema is not a text type, so its text must be JSON, such as 587.`, `... does not fit its schema: it fails \"minimum\" at #/minimum.` A whole number above 9007199254740991 is refused: keep an identifier as text. A value nested more than 100 levels deep is refused too. `prisma dev` runs the same check before any service starts and adds `prisma dev cannot start, because service \"<address>\" reads it.`\n11. **No library code runs on a variable's value; only the JSON Schema the library emits is checked.** A transform or a default the JSON Schema shows (`.transform()`, `string.numeric.parse`, a default inside an object) is refused at the root body; put defaults on the service's field. ArkType throws for `.narrow()` and `string.url`. Zod drops `.refine()`, and `.trim()`, `.toLowerCase()`, `z.coerce`, `z.preprocess()` and `.catch()` are accepted and do not run. An undeclared object key is not removed (`z.object()`, ArkType `'+': 'delete'`) and reaches the service's field. Regex flags are dropped and a pattern must be valid under the `u` flag (no `\\-` outside a character class). `format` is checked for `date`, `time`, `date-time`, `duration`, `uri`, `uri-reference`, `uri-template`, `url`, `email`, `hostname`, `ipv4`, `ipv6`, `regex`, `uuid` and the three JSON Pointer formats; others, such as `z.jwt()`, are unchecked. `z.number().optional()` does not fit `field(z.number())`: make the service's field optional. A hand-written schema that contradicts itself fails every boot. Put any other check or change in the service's own schema.\n\n### Values that differ per environment\n\nThe graph is the same in every environment; only configuration may differ.\n\n- A module declares `input` (one Standard Schema) as a service does; `provision(module, { input })` binds it, and the body receives `input`, a dictionary of values: it passes each field on by name into a binding or, for a plain field, lists it in `resolve()`. Passing the whole `input` on fails to compile, and the deploy refuses it. A root's `input` is the app configuration, and a module's `input` takes every source a service's does.\n- `field(inner)` from `@prisma/composer/arktype` or `@prisma/composer/zod` wraps one field's schema (`field(type('string'))`, `field(z.string())`) so it also accepts a plain pointer, which is what a value known only at boot such as `serviceOrigin()` is at deploy. In the body the field is `Value<string | Pointer<string>>`: pass it into another wrapped field or a service's input, never a plain `string` field (compile error). A wrapped field holds the whole value one source supplies, which may be an object or array when a platform variable's schema says so, so `field(type({ host: 'string' }))` is fine. An ArkType default goes outside: `field(type('string')).default('x')`. Other schema libraries: `Pointer`, `PlainPointer`, `isPlainPointer()` (narrows to `PlainPointer`) and `isSecretPointer()` from `@prisma/composer`. Wrap every field of a reusable module's schema other than a `secretString()` field, unless a `resolve()` lists it; keep a root's fields plain. `field(secretString())` is wrong: it accepts a plain pointer into a secret field, and the service fails at boot.\n- `composer({ config: [...], secrets: [...] })` lists config adapters; each gets the environment's name and returns values, later wins by top-level key. Both default to `[environmentVariables()]` (the shell); a list you write replaces the default. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local`, later wins. The app configuration fills the root's input (under `prisma dev` it also gives each plain platform variable a service reads its value, under the variable's name); pass the root's input fields on by name, as every module does; its whole `input` would be the whole app configuration, by default every shell variable. The app secrets give `prisma dev` its secrets; a deploy reads them only to redact. It does not fill a platform variable from them, and never reads them as the root's input. Both import from `@prisma/composer/config`. Credentials (`PRISMA_SERVICE_TOKEN`) still come from the shell. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local` through `dotenv-flow` (no `.env.local` for `test`); remove `import 'dotenv/config'` when you list it. Composer redacts the values under the names of the graph's platform secrets, in either list; the lists' other values are not secrets and print as they are, apart from values that look like credentials. Under `prisma deploy` the engine's output is redacted too; under `prisma dev` it is not yet.\n- A field exists only under a plain object: a path into a string, an array or a secret, such as `input.tags[0]`, fails the deploy naming the path.\n- A truthiness check such as `if (input.enabled)` is not caught: the field is an object, so the branch always runs, in every environment. A module's structure cannot depend on its input; to provision something only sometimes, let the parent decide whether to provision it.\n- The module body receives `environment`; `environment.name` is a value standing for the name `--environment` gave (`production` for `prisma deploy`, `dev` for `prisma dev` by default).\n- `resolve([deps], ([values]) => …)` from `@prisma/composer` returns a computed value; `fn` receives the dependencies' real values as one tuple.\n- A value is accepted as a leaf of a service's or a module's `input` binding, at any depth, as a service param (a deploy-time value only), as one of a `resource()` node's `props`, or as a public URL's `url`. Never as a provision id or a `deps` entry.\n- A value is opaque in the body: you cannot read, compare or branch on it. List it as a `resolve()` dependency instead.\n- Calling `provision()` inside `fn` fails the load: `fn` computes configuration, never graph structure.\n- `fn` is pure and synchronous and returns plain data (no `undefined`, Promise, value or source); a deploy and `destroy` both run it, in two processes. To retire an environment, keep its case in every `fn` until `destroy` for it has finished.\n- Sources are values. `resolve([input.X], ([x]) => …)` over a root input field receives its data. A dependency must be a deploy-time value: a platform variable's value, `generatedParam()`, `serviceOrigin()`, a field wrapped with `field()` and a `secretString()` field cannot be listed (a compile error saying so; for a field typed `unknown` or a cast, the deploy fails naming the field). Bind those directly; to compute with a field, declare it plain. For a different secret per environment, use one name with a different value on each environment.\n\n## Contracts and RPC\n\nAn RPC contract is the typed interface through which services communicate. It\nlives with the service that owns it, typed by any Standard Schema validator,\nand both provider (`serve()`, exhaustive over the contract's methods at\ncompile time) and consumer (`rpc(contract)`) reference the same value. Calls\ntravel as RPC over HTTP. Two behaviours are provisioned for you and must not\nbe reimplemented:\n\n1. **Service keys.** At deploy, Composer mints a distinct unguessable key per\n   consumer→provider binding; `serve()` returns `401` to anything else before\n   the handler runs. Nothing in your code declares it. Consequences: don't\n   build your own service-to-service auth, and don't `curl` a deployed\n   `/rpc/<method>` to check it works. An unwired caller always gets `401`,\n   which looks like a broken deploy and isn't. Debug through a consumer, or\n   locally, where nothing is enforced. Keys are per binding (one leaking\n   can't impersonate another consumer), service-scoped (any valid key\n   reaches every method; split services to gate separately), rotated only by\n   removing the binding or destroying the stack and redeploying, and stored\n   in deploy-owned `COMPOSER_*` variables you never hand-edit.\n2. **Idempotency and retries.** Every generated-client call carries an\n   `Idempotency-Key`; dropped calls retry with backoff, and `serve()` runs\n   one call per key, replaying the completed answer to late retries. Every\n   method is therefore safely retryable and no contract declares anything\n   about it (there is no \"is this idempotent\" flag; don't invent one). A\n   handler may take an optional third argument `(input, deps, ctx)` and read\n   `ctx.idempotencyKey` (`string | undefined`) if it needs exactly-once\n   beyond one instance's memory; most don't. Locally and in tests nothing is\n   provisioned, so `serve()` passes every call through: never supply a key\n   in test inputs.\n\n## Raw HTTP connections\n\nFor a server Composer does not generate (a reverse proxy's upstreams, a\nNext.js app, a static file server), import `rawHttp` and `rawHttpContract`\nfrom `@prisma/composer/http`. The provider declares\n`expose: { http: rawHttpContract }`; the caller declares\n`deps: { site: rawHttp() }`; the Module wires\n`provision(gateway, { deps: { site: siteRef.http } })`. `gateway.load().site`\nis `{ url, fetch(path, init) }`, where `fetch` resolves `path` against `url`.\nThe client never leaves its provider's origin by itself: `fetch` rejects a\npath that resolves to another host (`//other.example/x`, an absolute URL), and\nreturns redirects to the caller instead of following them, unless `init` sets\n`redirect: 'follow'`.\n\nComposer checks only that the provider declared an HTTP port: TypeScript and\nLoad reject a bare service ref or a port of another kind. The caller is\nresponsible for knowing the provider's paths, methods and headers. Raw HTTP\nhas no service key, retry or idempotency key; authentication, if needed, is\nthe app's. Each dependency shows in the application topology as a call, also\nthrough module boundaries; a URL passed as `input` (`serviceOrigin()`)\ndoes not, so declare a dependency for every service you call. The auth\nmodule's `api` port is a raw HTTP port: wire it with `rawHttp()`.\n\n**Public URLs.** A service is reachable from the internet only through a\npublic URL the app declares:\n`provision(publicUrl({ id: 'site', url, target: web.http }))`, where `id`\nsets the address (`shop.site`) and changing it replaces the URL, and where\n`web` exposes `http: rawHttpContract` (an RPC interface as `target` fails\n`tsc`; a module's forwarded HTTP interface lands on the service inside it).\n`url` is required and is one of two strategies: `publicUrl.prismaBuild()`\nserves at the service's `prisma.build` hostname and creates nothing;\n`publicUrl.hostname('shop.com')`, or the bare string `'shop.com'`, attaches\nthat hostname to the service as a custom domain. One hostname per public URL.\nA per-environment `url` is a `resolve()` value returning either strategy or a\nstring; anything else fails deploy and dev before any of the app's resources\nare created or changed. Before\na deploy names a hostname, the TXT record `_prisma-verification.<hostname>`\nand a CNAME to the platform must be published, or the deploy fails with the\nplatform's error (`domain-ownership-required` for the TXT record); don't\nwork around it, publish the records or use `publicUrl.prismaBuild()` there. A\nchange from a serving hostname to one that is not ready fails the deploy and\nthe old hostname keeps serving. `prisma dev` ignores a named hostname and\nwarns once per public URL that names a hostname. A service with no public URL is still reachable at\nits `prisma.build` hostname today.\n\n## Builds are yours\n\nYou build, the framework assembles. For a plain server process, `entry`\npoints at the ESM file your build produced. By default\n(`dependencies: 'bundled'`) deploy copies exactly that and never ships\n`node_modules`, so everything except runtime built-ins (`bun`, `bun:*`,\n`node:*`) must be inlined, or it fails at boot, not at deploy. Rules that\nbite:\n\n1. **Two services in one package means two separate builds**, one per entry.\n   A single multi-entry build splits shared code into a chunk neither output\n   contains.\n2. **A directory build uses `dir` + `entry`** (`dir` relative to the service\n   module, `entry` a file inside `dir`; `../` is an error). The tree is\n   copied verbatim, so the server must resolve siblings against\n   `import.meta.url`, not the working directory. The tree must contain no\n   symlinks: the packager rejects them, names the link, and assembly fails.\n3. **A build that leaves packages external sets `dependencies: 'external'`**\n   (either form). Deploy then traces `entry` and stages the installed\n   packages it imports, which can take minutes on a large build. Astro's Node\n   adapter, SvelteKit's `adapter-node` and React Router's server build leave\n   packages external by default. The default, `'bundled'`, copies exactly\n   what was built. A service that fails to start with\n   `Cannot find package 'x'` needs `x` bundled, or `dependencies: 'external'`.\n4. **Next.js**: `next build` with `output: 'standalone'` is the whole build;\n   `nextjs({ module, appDir })` names the app root. Any page or action that\n   calls `load()` needs `export const dynamic = 'force-dynamic'`, because\n   the runtime environment variables don't exist at build time and Next ignores\n   runtime env for prerendered routes. `prisma dev` needs no build for it: it\n   runs `next dev` instead (see Local development).\n5. **Always build before `deploy`, and before `dev` for a service without a\n   dev server.** Neither builds for you. `node({ ..., dev: ['bun', '--watch',\n   'server.ts'] })` gives a node service a dev server: `prisma dev` runs that\n   command (in the authoring module's directory, nothing appended; it must\n   listen on `PORT`) instead of the built `entry`.\n\nDeploy configuration is the `composer` section of `prisma.config.ts`, and\nnothing else. It names the entry module, the file whose default export is the\napp root (`entry`, relative to the config file; `--entry <path>` overrides it\nfor one run), and registers extensions (`prismaCloud()`, `nodeBuild()`,\n`nextjsBuild()` when the app has a Next.js service) and the deploy-state\nbackend (`prismaState()`):\n\n```ts\n// prisma.config.ts\nimport { defineConfig as composer } from '@prisma/composer/config';\nimport { nodeBuild } from '@prisma/composer/node/control';\nimport { prismaCloud, prismaState } from '@prisma/composer-prisma-cloud/control';\nimport { definePrismaConfig } from 'prisma/config';\n\nexport default definePrismaConfig({\n  composer: composer({\n    entry: './module.ts',\n    extensions: [prismaCloud(), nodeBuild()],\n    state: prismaState(),\n  }),\n});\n```\n\nThe commands find `prisma.config.ts` from the directory they run in, walking up\nto the repository root; the nearest file that declares `composer` wins, and its\nsection is used whole, never merged key by key. Only `entry`, `extensions` and `state`\nare allowed; any other key is an error. App code never imports the file.\n\nA separate `prisma-composer.config.ts` is no longer read, and the old setup is\nrefused, never silently ignored: `CONFIG.SECTION_MISSING` when no loaded\n`prisma.config.ts` declares a `composer` section, `CONFIG.FIELD_RETIRED` when\nthe section still has `configPath`, `CONFIG.FILE_RETIRED` when a\n`prisma-composer.config.*` sits next to the declaring `prisma.config.ts`; all\nthree under the CLI's `CLI.CONFIG_SECTION_INVALID`. `SECTION_MISSING` is fixed by\nadding the `composer` section to `prisma.config.ts`. `FIELD_RETIRED` and\n`FILE_RETIRED` are fixed by moving the old file's `extensions` and `state` into\nthe section, then removing `configPath` or deleting the old file.\n`@prisma/composer-cli/family` no longer exports `ComposerSection`; the\nsection's type is `PrismaAppConfig` from `@prisma/composer/config`.\n\n## Databases and migrations\n\nTwo kinds of Postgres dependency:\n\n1. **`rawPostgres()`**: the binding is `{ url }` and the app owns its client.\n2. **`postgres(...)`**: a Prisma-ORM-typed database. The binding is\n   `{ url, connection, client, clientWith }` (ADR-0040, ADR-0055): the raw\n   connection URL, the connection pool, the typed client Composer constructs\n   from your data contract lazily on first access, and `clientWith(options)`,\n   which builds a typed client with Prisma ORM runtime options. Queries go\n   through `binding.client` and are compile-time checked. Both `postgres` and `dataContract` import from\n   `@prisma/composer-prisma-cloud/orm`, not the package root. The app's\n   `package.json` lists `@prisma/orm-postgres` and the four ORM packages it\n   is built from (`@prisma/orm-framework`, `@prisma/orm-family-sql`,\n   `@prisma/orm-target-postgres`, `@prisma/orm-toolchain`), all at the exact\n   version Composer names, plus `pg`, `@types/pg` and `temporal-polyfill`; the ORM's packages are\n   peers of each other, so the app's list decides the one copy installed. One\n   `dataContract`-wrapped value (emitted from `contract.prisma` by\n   `prisma contract emit`) is referenced by both the dependency end\n   (`deps: { db: postgres(catalogData) }`) and the resource end, which also\n   names the `prisma.config.ts` path so the deploy's migration step can\n   reload the emitted `contract.json` and find `migrations/`, and the required\n   `targetRef`, the ref every deploy migrates the database to (below).\n   Client options never go on the dependency declaration. A contract that\n   uses an extension type (for example `pgvector.Vector(length: 1024)`)\n   needs the pack's runtime extension when the client is built:\n   `export const orm = db.clientWith({ extensions: [pgvectorRuntime] })`,\n   where `pgvectorRuntime` is the default export of\n   `@prisma/orm-extension-pgvector/runtime`; other runtime options, such as\n   `middleware`, go in the same object. Install the pack at exactly the\n   `@prisma/orm-postgres` version: the pack names the ORM's packages as\n   peers at its own version, so with a mismatch npm refuses the install and\n   pnpm, Yarn and Bun only warn, and the client rejects the extension's\n   values. Composer never looks extensions up itself;\n   with `binding.client` instead, the first access throws\n   \"Contract requires extension pack(s) 'pgvector'\".\n\n**Every deploy and every `prisma dev` converge runs the ORM's migrate** for each ORM database: the equivalent of `prisma db migrate --to <targetRef>` against the database Composer provisioned, whether or not anything changed. The ORM decides what is pending; with nothing pending it applies nothing and no service is redeployed. A deploy only migrates: it never runs `db update`, `db init` or `db sign`, and never creates schema from the contract.\n\n`targetRef` is required on the resource end. It takes a ref name (a committed `migrations/app/refs/<name>.json`) or `@contract`, the contract this commit emits. An app that deploys to environments computes it from the environment name:\n\n```ts\npostgres({\n  name: 'database',\n  contract: catalogData,\n  config: './prisma.config.ts',\n  targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n});\n```\n\n`@empty`, `@db`, a contract hash or a migration directory name is refused. A Module that provisions its own ORM database targets `'@contract'`: its migrations ship inside its package, so the app cannot commit refs for it, and a Module that copies the app's `resolve([environment.name], …)` pattern makes the app's first `production` deploy fail with the ORM's `MIGRATION.UNKNOWN_REF`. The `prisma.config.ts` names no database (no `db.connection`); the deploy passes the ORM the one it provisioned. Per-PR environments need one ref rule for all of them (such as a shared `preview` ref, or `'@contract'`); an environment with no ref file fails with the ORM's `MIGRATION.UNKNOWN_REF`.\n\nThe loop for every schema change, including a new database's first schema:\n\n1. Edit `contract.prisma`.\n2. `prisma contract emit` regenerates `contract.json` + `contract.d.ts`.\n3. `prisma migration plan --name <slug>` authors the migration (on an empty graph this authors the baseline).\n4. `prisma migration ref set <environment> <newest migration directory>` for each environment the change should reach.\n5. Commit `migrations/`, then deploy. A fresh database replays the whole path from empty.\n\nUnder `prisma dev`, plan a migration for each contract change: a local database moved with `prisma db update` to a contract no migration ends at is refused on every rebuild with the ORM's `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, although it is at the target, until a migration ending at that contract exists. This is a current Prisma ORM bug. Plan a migration that ends at the contract; do not reset the database or edit its contract signature to get past it.\n\nA deploy moves the database to its ref, not to the code: a ref may trail the contract on purpose, and moving it is the user's job in the pull request that changes the contract. Every service that uses the database deploys only after its migration completes: a failed migration means the new code does not ship. The old code serves against the new schema until the new deployment is live, so keep each migration compatible with the code it replaces.\n\nA failed migration fails the deploy with one Composer line, `<address>: Composer ran prisma db migrate --to <targetRef> on this database.`, and the ORM's own structured error under it: code, summary, `why`, next actions and docs link. Follow the ORM's advice; Composer adds none. Its advised commands repeat `--to <targetRef>`. Composer raises its own errors only before the ORM runs: the emitted contract `prisma.config.ts` names is missing or unreadable, has no storage hash, or differs from the declared `dataContract(...)` value.\n\nWhen a ref declares policies that differ from the database's (a new database has the ORM's defaults), every deploy fails with the ORM's `MIGRATION.POLICY_MISMATCH` and changes nothing. A deploy never changes policies. Applying them is a decision for whoever administers the database, made by hand: `prisma db migrate --to <ref> --permit-policy-change --db <url>`, with the URL from the Prisma Console, from `prisma postgres connection create @<environment>:<address> --name <name> --json` (its output holds a secret shown once), or locally from `prisma dev url <address>` while `prisma dev` runs. A ref's policies are the `policies` field of its JSON file, edited by hand: the pinned Prisma ORM version has no command for them. Do not run that command, or edit a ref's policies, to get a deploy past the refusal: say what the ORM reported and leave the decision to whoever administers the database.\n\nUpgrading an app from before `targetRef` was required: add `targetRef` to each `postgres({ ... })`, commit a ref per deployed environment with `prisma migration ref set <environment> <newest migration directory>`, and remove placeholder `db.connection` entries from `prisma.config.ts`. See `examples/orm-demo` for an app and `examples/store/modules/catalog` for a Module.\n\n## Deploy model: converge, don't script\n\nDeploy compares the declared topology against recorded deploy state and\napplies only the difference. Re-deploying with nothing changed is a no-op;\nremoving a node removes its deployed resource. `prisma deploy` needs a signed-in\nidentity: `prisma auth login` stores a session on a developer machine, and\n`PRISMA_SERVICE_TOKEN` overrides it in CI. The `/control` operations, and so\na destroy script, never use that session: `deploy` and `destroy` read\n`PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` from environment variables (both\nin the workspace's Console settings); `dev` and `log` read neither. The\n`prisma` bin starts under Node; use `pnpm prisma …` or `npx prisma …` by\ndefault. Composer starts Alchemy with Node, but Alchemy's launcher moves to\nBun under `bunx` or `bun run`: `bunx prisma` gives Node then Bun,\n`bunx --bun prisma` Bun then Bun. When the modules `module.ts` imports use\nBun APIs, `bun node_modules/prisma/dist/prisma.js deploy` from a\nshell runs `prisma` under Bun with Alchemy on Node.\n\nA node's **address** is the app name followed by the provision ids down to it\n(`shop.auth.api`); the root's address is the app name, or `--name` when given.\nEvery surface uses this full form: `serviceOrigin('shop.api')`,\n`prisma dev url shop.api`, the `log` operation's `address`, errors and reports.\nServices, managed Postgres databases and buckets record their address as\n`logicalId` on their Branch. Console uses that address to match topology nodes\nto resources and compare them with main. Existing environments receive the\nidentity on their next deploy. A deploy interrupted after creating a resource\nresumes on the next deploy, which finds the resource by its address. Local dev\ncreates no platform rows. Changing a node's address (its name without an\nexplicit `id`, its `id`, or its module) makes a new entity: the next deploy\ndeletes the old rows, and a database's or bucket's data with them.\n\n**Progress.** `prisma deploy` prints each step as it starts and finishes, with its duration (`✔ assemble web (3m 42s)`), and ends with the real total (`Deployed <app> to <environment> in 5m 25s.`). Steps: load config and app, one assemble per service, connect to project and branch, check environment variables, plan and apply (one step: alchemy does both in one process), record result. A slow assemble is usually a Node service with `dependencies: 'external'`, whose runtime dependencies are being traced. With `--json`, each step is a `step-started`/`step-finished` line whose `data` holds `durationMs` plus whatever the build adapter or deploy target reported; those extra fields vary, so don't parse them as a stable format. The `deploy` operation's `onEvent` receives the same steps, its result's `durationMs` is the total, and its `summary.findings` lists the platform variables with no value.\n\n**Environments.** An environment is a named place the app runs, chosen with\n`--environment` at deploy time, never written in the topology. The identical\ngraph deploys everywhere. `prisma deploy` without the flag deploys\n`production`; `prisma dev` runs as `dev` and takes no flag. On the Prisma Cloud\ntarget, a Prisma App is one Project and an environment is a Branch of it, with\nits own running services, its own empty database, its own configuration:\n`production` is the Project's default Branch, any other name is the Branch\nwith that `gitName`, created if absent. The default Branch's own name (such as\n`main`) is refused, since it would be production under a second name. A name\nmust be a valid git ref name, or the deploy fails with\n`DEPLOY.ENVIRONMENT_INVALID`.\n\n**Seeing what is deployed.** `prisma deploy list [--environment <name>]` lists every\nnode of the topology the last deploy recorded, with its kind, platform ID and,\nfor a service, its URL; the root's ID is the Project's, and a module has none.\nIt finds the app as `deploy` does (`--name`, `--entry`) and fails with\n`DEPLOY.TARGET_NOT_FOUND` when the environment has nothing deployed. Piped:\naddress, kind, platform ID, URL per line; `--json`: `[{ address, kind, platformId, url }]`. It needs\na `prisma` CLI release that includes it; 8.0.0-rc.26 does not.\n\n**Using an address with platform commands.** A `prisma project|service|postgres|bucket`\ncommand takes `@<environment>:<address>` in place of the platform ID\n(`prisma service logs @pr-42:shop.api`); no environment means production. It\nacts on that one row. Deleting a service, database or bucket this way leaves\nthe deploy state alone, so the next deploy recreates it; deleting the Project\nremoves its deploy state too. It needs a `prisma` CLI release newer than\n8.0.0-rc.28.\n\n**Removing an app** with every environment is a platform command: find the Project\nid with `prisma project list`, then `prisma project delete <id> --confirm <id>`,\nand check `prisma project list` again to confirm it is gone. It works while the\napp's services are running. Don't write a script for this.\n\n**Destroying one environment** is the `destroy` operation, and its\n`environment` is required, even for production; it has no default and a call\nwithout it fails with `DEPLOY.ENVIRONMENT_REQUIRED`:\n\n```ts\nawait destroy({ entry: 'module.ts', environment: 'pr-42', config });\nawait destroy({ entry: 'module.ts', environment: 'production', config });\n```\n\nDestroying any environment other than production\ndeletes its Branch after removing its resources. Destroying production\nremoves only the resources inside the production Branch, never the Branch\nitself directly; once the Project is empty it is deleted too, and that\ndeletion takes the production Branch with it. A Project still holding\nanother environment's resources is kept. Destroy never creates anything:\ndestroying a\nnever-deployed environment fails rather than standing one up.\n\n**Upgrading from stages.** `--stage <name>` is now `--environment <name>`;\n`destroy({ target })` is now `destroy({ environment })`, with production as\n`'production'`; the `--report` file's `stage` field is now `environment`, at\n`version` 2. Keep `@prisma/composer-prisma-cloud` on the same Composer version\nas the Composer that runs the deploy. An older extension would read every\nenvironment as production, so deploy and destroy refuse it with\n`DEPS.EXTENSION_INCOMPATIBLE`.\n\n**The engine underneath is alchemy.** Convergence is executed by [alchemy](https://alchemy.run), a third-party infrastructure-as-code engine that arrives as an ordinary, exactly-pinned npm dependency of `@prisma/composer` (2.0.0-beta.87 at this library version). Your code never imports or configures it; consult alchemy's own docs for the engine itself. What matters operationally:\n\n`prisma deploy` runs alchemy inside the `prisma` process through alchemy's programmatic API: no generated file and no child process. Its progress prints as one step per resource, and a failure is `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, with credentials redacted, or `DEPLOY.INTERRUPTED` after Ctrl-C, which releases the environment's lease. `prisma dev` runs alchemy in the `prisma` process too, each converge in a new worker thread, so an edit to your app definition applies on the next rebuild. Three kinds of edit need `prisma dev` restarted, and it says so: adding or removing a node, making the root pass on an input field it did not pass on at start, and changing which platform variables the app reads. The `destroy` operation runs alchemy inside the process that calls it, the same way as deploy. The alchemy that runs is the one installed beside the app's `@prisma/composer`, so the app needs no direct `alchemy` dependency, and no global Alchemy installation is needed.\n\n1. No command writes a stack file or starts the alchemy CLI. An engine failure surfaces as `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, credentials redacted, for deploy and destroy alike. A structured error, such as the ORM's, keeps its code, `why`, next actions, docs link and the structured error it was caused by: they print in the CLI's error layout, and its next actions stay `{ kind, label, command?, … }` objects, and are data in `failure.meta.reasons`, in the `--report` file's `failure.reasons` and on `prisma dev`'s `converge-failed` events. Only the copy sent to the Prisma Cloud build is shortened, to 5000 characters, by cutting the middle of the longest `why`.\n2. Destroy runs the same preparation as deploy, assembly included, so **an app must be built before it can be torn down**.\n3. alchemy is why the `effect` pin exists: it resolves the `effect`\n   constellation, and a hoisted newer `effect` halts every command (failure\n   mode 1 below).\n\n**The deploy report** ends with the app's own topology: authored names, the\nplatform resource each became, and public URLs. Read ids out of it rather\nthan hunting in the Console. A URL appears only where the address is\ngenuinely public: a service prints one, a database never does, and a\nnode whose product is secret material reports no resource line at all.\n\n**Connection contract refusals.** A connection declares the values it needs\nby name; a producer that omits one fails the deploy, naming the edge, the\nparam, and what the producer did supply:\n\n```text\nConnection input \"auth.db\" declares param \"url\", but its producer \"db\" did not\nsupply it — the producer's outputs carry [host].\n```\n\nThis is a deploy-time refusal, not a broken deploy, and it can appear on an\napp whose code didn't change (the gap used to pass silently as `undefined`\nand crash the consumer at boot). Fix whichever end is wrong; don't mark the\nparam `optional` unless absent really is legal. Only reachable if you\nauthored the connection or an extension on one side.\n\n**Driving deploys from code.** A script imports only\n`@prisma/composer/control`; the extensions' `/control` entries are imported\nonly by `prisma.config.ts` (ADR-0017). `@prisma/composer/control` exposes typed\n`deploy`, `destroy`, `dev`, `devUrl`, `devStop`, and `log` returning structured\nresults; `prisma deploy`, `prisma dev`, `prisma dev url` and `prisma dev stop`\nrender `deploy`, `dev`, `devUrl` and `devStop`. Each takes\na required `config: { value, file }` (`ComposerConfigSource`): the `composer`\nexport of your `prisma.config.ts` and that file's path; a relative `file`\nresolves against `cwd`, so build it from `import.meta.url`. The operations\nnever look for a config file, but refuse what the CLI refuses before any work\nstarts (`CONFIG.FIELD_UNKNOWN` for the whole export instead of its `composer`\nproperty, `CONFIG.FILE_RETIRED`, `CONFIG.FILE_MISSING`); the deploy re-imports\n`file`, so `value` must be its `composer` export. Failures come back as\n`{ ok: false, failure }` with a dotted `failure.code` from a closed registry\n(e.g. `ASSEMBLE.BUILD_FAILED`, `DEPLOY.ENGINE_FAILED`,\n`DEPS.EXECUTOR_UNLOADABLE`); branch on the code, not the message. A\nnon-structured rejection out of an operation is a bug in composer, not an\nexpected failure.\n\n## Local development\n\n`prisma dev` runs the whole app on this machine, wired as it deploys,\nagainst local emulators. No cloud credentials are needed or read. Concepts\nthat surprise:\n\n1. It runs the same pipeline as deploy, so **build first**, exactly like\n   deploy, except for a service that runs a dev server (below). It watches\n   built output and restarts a service when its build changes.\n   **Dev servers.** A service whose build adapter declares one runs it in\n   place of its artifact, with no flag: every `nextjs()` service runs\n   `next dev` (the app's own `next`, resolved from `appDir`), and a `node()`\n   service runs its `dev` argv when it has one. It runs on the service's\n   instance and URL, with the deployment's environment variables: `service.load()`,\n   `service.input()` and `service.port()` work exactly as deployed, so never add a\n   `process.env` fallback for plain `next dev`. It also keeps the shell's\n   environment variables; Composer's values win. `dev` prints ``<address>: runs\n   `<command>` in <dir>`` before the app comes up and streams the dev\n   server's output prefixed `[<address>]` (other services' logs are not\n   streamed). Source edits are the dev server's own hot reload; `dev` watches\n   the entry and every app file it imports, applies an edit to them on the\n   next rebuild (adding or removing a node, passing on a new root input field, or changing which platform variables the app reads needs `dev` restarted, and it says so), and restarts a dev server only when its environment variables changed\n   (``<address>: its environment changed; `<command>` restarted``). It has no\n   terminal (no colours or key shortcuts). The standalone build is not run\n   locally, so a standalone-only\n\n<!-- [TRUNCATED AT 50KB] -->"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","isInternal":false,"tokens":602,"sizeBytes":2449},{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","content":"# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## A layer does not know what is built on it\n\nThis is an\n[architectural principle](docs/design/01-principles/architectural-principles.md#a-layer-does-not-know-what-is-built-on-it),\nand it is the one agents most often break without noticing. It comes up as a\nshortcut: code in a higher layer needs a value, the only thing it holds is a\nlower layer's interface, and one more member on that interface is the shortest\nway. Stop there and read the principle.\n\nIf the member would exist for one kind of Connection, one deployment target or\none Module, do not build it. Do not offer it to the operator as an option\neither, whether the idea is yours or a subagent's: the operator would have to\ncatch the problem themselves, and the gap in the design you found would go\nunreported. Report the gap instead: what the higher layer needs, and why\nnothing that exists carries it.\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n","isInternal":false,"tokens":806,"sizeBytes":3316},{"name":"convex_rules.mdc","path":"docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc","title":"Cursor Rule: convex_rules","category":"cursor-rule","format":"mdc","content":"---\ndescription: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples\nglobs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx\n---\n\n# Convex guidelines\n## Function guidelines\n### New function syntax\n- ALWAYS use the new function syntax for Convex functions. For example:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\nexport const f = query({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n    // Function body\n    },\n});\n```\n\n### Http endpoint syntax\n- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:\n```typescript\nimport { httpRouter } from \"convex/server\";\nimport { httpAction } from \"./_generated/server\";\nconst http = httpRouter();\nhttp.route({\n    path: \"/echo\",\n    method: \"POST\",\n    handler: httpAction(async (ctx, req) => {\n    const body = await req.bytes();\n    return new Response(body, { status: 200 });\n    }),\n});\n```\n- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.\n\n### Validators\n- Below is an example of an array validator:\n```typescript\nimport { mutation } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport default mutation({\nargs: {\n    simpleArray: v.array(v.union(v.string(), v.number())),\n},\nhandler: async (ctx, args) => {\n    //...\n},\n});\n```\n- Below is an example of a schema with validators that codify a discriminated union type:\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n    results: defineTable(\n        v.union(\n            v.object({\n                kind: v.literal(\"error\"),\n                errorMessage: v.string(),\n            }),\n            v.object({\n                kind: v.literal(\"success\"),\n                value: v.number(),\n            }),\n        ),\n    )\n});\n```\n- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport const exampleQuery = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n      console.log(\"This query returns a null value\");\n      return null;\n  },\n});\n```\n- Here are the valid Convex types along with their respective validators:\nConvex Type  | TS/JS type  |  Example Usage         | Validator for argument validation and schemas  | Notes                                                                                                                                                                                                 |\n| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Id          | string      | `doc._id`              | `v.id(tableName)`                              |                                                                                                                                                                                                       |\n| Null        | null        | `null`                 | `v.null()`                                     | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead.                             |\n| Int64       | bigint      | `3n`                   | `v.int64()`                                    | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers.                                                                                              |\n| Float64     | number      | `3.1`                  | `v.number()`                                   | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings.                                                                      |\n| Boolean     | boolean     | `true`                 | `v.boolean()`                                  |\n| String      | string      | `\"abc\"`                | `v.string()`                                   | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8.                                                         |\n| Bytes       | ArrayBuffer | `new ArrayBuffer(8)`   | `v.bytes()`                                    | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types.                                                     |\n| Array       | Array       | `[1, 3.2, \"abc\"]`      | `v.array(values)`                              | Arrays can have at most 8192 values.                                                                                                                                                                  |\n| Object      | Object      | `{a: \"abc\"}`           | `v.object({property: value})`                  | Convex only supports \"plain old JavaScript objects\" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with \"$\" or \"_\". |\n| Record      | Record      | `{\"a\": \"1\", \"b\": \"2\"}` | `v.record(keys, values)`                       | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with \"$\" or \"_\".                                                               |\n\n### Function registration\n- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.\n- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.\n- You CANNOT register a function through the `api` or `internal` objects.\n- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.\n- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.\n\n### Function calling\n- Use `ctx.runQuery` to call a query from a query, mutation, or action.\n- Use `ctx.runMutation` to call a mutation from a mutation or action.\n- Use `ctx.runAction` to call an action from an action.\n- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.\n- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.\n- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.\n- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,\n```\nexport const f = query({\n  args: { name: v.string() },\n  returns: v.string(),\n  handler: async (ctx, args) => {\n    return \"Hello \" + args.name;\n  },\n});\n\nexport const g = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const result: string = await ctx.runQuery(api.example.f, { name: \"Bob\" });\n    return null;\n  },\n});\n```\n\n### Function references\n- Function references are pointers to registered Convex functions.\n- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.\n- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.\n- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.\n- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.\n- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.\n\n### Api design\n- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.\n- Use `query`, `mutation`, and `action` to define public functions.\n- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.\n\n### Pagination\n- Paginated queries are queries that return a list of results in incremental pages.\n- You can define pagination using the following syntax:\n\n```ts\nimport { v } from \"convex/values\";\nimport { query, mutation } from \"./_generated/server\";\nimport { paginationOptsValidator } from \"convex/server\";\nexport const listWithExtraArg = query({\n    args: { paginationOpts: paginationOptsValidator, author: v.string() },\n    handler: async (ctx, args) => {\n        return await ctx.db\n        .query(\"messages\")\n        .withIndex(\"by_author\", (q) => q.eq(\"author\", args.author))\n        .order(\"desc\")\n        .paginate(args.paginationOpts);\n    },\n});\n```\nNote: `paginationOpts` is an object with the following properties:\n- `numItems`: the maximum number of documents to return (the validator is `v.number()`)\n- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)\n- A query that ends in `.paginate()` returns an object that has the following properties:\n- page (contains an array of documents that you fetches)\n- isDone (a boolean that represents whether or not this is the last page of documents)\n- continueCursor (a string that represents the cursor to use to fetch the next page of documents)\n\n\n## Validator guidelines\n- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.\n- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.\n\n## Schema guidelines\n- Always define your schema in `convex/schema.ts`.\n- Always import the schema definition functions from `convex/server`.\n- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.\n- Always include all index fields in the index name. For example, if an index is defined as `[\"field1\", \"field2\"]`, the index name should be \"by_field1_and_field2\".\n- Index fields must be queried in the same order they are defined. If you want to be able to query by \"field1\" then \"field2\" and by \"field2\" then \"field1\", you must create separate indexes.\n\n## Typescript guidelines\n- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.\n- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:\n```ts\nimport { query } from \"./_generated/server\";\nimport { Doc, Id } from \"./_generated/dataModel\";\n\nexport const exampleQuery = query({\n    args: { userIds: v.array(v.id(\"users\")) },\n    returns: v.record(v.id(\"users\"), v.string()),\n    handler: async (ctx, args) => {\n        const idToUsername: Record<Id<\"users\">, string> = {};\n        for (const userId of args.userIds) {\n            const user = await ctx.db.get(\"users\", userId);\n            if (user) {\n                idToUsername[user._id] = user.username;\n            }\n        }\n\n        return idToUsername;\n    },\n});\n```\n- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.\n- Always use `as const` for string literals in discriminated union types.\n- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`\n- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`\n- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.\n\n## Full text search guidelines\n- A query for \"10 messages in channel '#general' that best match the query 'hello hi' in their body\" would look like:\n\nconst messages = await ctx.db\n  .query(\"messages\")\n  .withSearchIndex(\"search_body\", (q) =>\n    q.search(\"body\", \"hello hi\").eq(\"channel\", \"#general\"),\n  )\n  .take(10);\n\n## Query guidelines\n- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.\n- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.\n- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.\n- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.\n### Ordering\n- By default Convex always returns documents in ascending `_creationTime` order.\n- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.\n- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.\n\n\n## Mutation guidelines\n- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })`\n- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })`\n\n## Action guidelines\n- Always add `\"use node\";` to the top of files containing actions that use Node.js built-in modules.\n- Never use `ctx.db` inside of an action. Actions don't have access to the database.\n- Below is an example of the syntax for an action:\n```ts\nimport { action } from \"./_generated/server\";\n\nexport const exampleAction = action({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        console.log(\"This action does not return anything\");\n        return null;\n    },\n});\n```\n\n## Scheduling guidelines\n### Cron guidelines\n- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.\n- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.\n- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,\n```ts\nimport { cronJobs } from \"convex/server\";\nimport { internal } from \"./_generated/api\";\nimport { internalAction } from \"./_generated/server\";\n\nconst empty = internalAction({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    console.log(\"empty\");\n  },\n});\n\nconst crons = cronJobs();\n\n// Run `internal.crons.empty` every two hours.\ncrons.interval(\"delete inactive users\", { hours: 2 }, internal.crons.empty, {});\n\nexport default crons;\n```\n- You can register Convex functions within `crons.ts` just like any other file.\n- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file.\n\n\n## File storage guidelines\n- Convex includes file storage for large files like images, videos, and PDFs.\n- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.\n- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.\n\nInstead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<\"_storage\">`.\n```\nimport { query } from \"./_generated/server\";\nimport { Id } from \"./_generated/dataModel\";\n\ntype FileMetadata = {\n    _id: Id<\"_storage\">;\n    _creationTime: number;\n    contentType?: string;\n    sha256: string;\n    size: number;\n}\n\nexport const exampleQuery = query({\n    args: { fileId: v.id(\"_storage\") },\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        const metadata: FileMetadata | null = await ctx.db.system.get(\"_storage\", args.fileId);\n        console.log(metadata);\n        return null;\n    },\n});\n```\n- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.\n\n\n# Examples:\n## Example: chat-app\n\n### Task\n```\nCreate a real-time chat application backend with AI responses. The app should:\n- Allow creating users with names\n- Support multiple chat channels\n- Enable users to send messages to channels\n- Automatically generate AI responses to user messages\n- Show recent message history\n\nThe backend should provide APIs for:\n1. User management (creation)\n2. Channel management (creation)\n3. Message operations (sending, listing)\n4. AI response generation using OpenAI's GPT-4\n\nMessages should be stored with their channel, author, and content. The system should maintain message order\nand limit history display to the 10 most recent messages per channel.\n\n```\n\n### Analysis\n1. Task Requirements Summary:\n- Build a real-time chat backend with AI integration\n- Support user creation\n- Enable channel-based conversations\n- Store and retrieve messages with proper ordering\n- Generate AI responses automatically\n\n2. Main Components Needed:\n- Database tables: users, channels, messages\n- Public APIs for user/channel management\n- Message handling functions\n- Internal AI response generation system\n- Context loading for AI responses\n\n3. Public API and Internal Functions Design:\nPublic Mutations:\n- createUser:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({userId: v.id(\"users\")})\n  - purpose: Create a new user with a given name\n- createChannel:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({channelId: v.id(\"channels\")})\n  - purpose: Create a new channel with a given name\n- sendMessage:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), authorId: v.id(\"users\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Send a message to a channel and schedule a response from the AI\n\nPublic Queries:\n- listMessages:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n    }))\n  - purpose: List the 10 most recent messages from a channel in descending creation order\n\nInternal Functions:\n- generateResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.null()\n  - purpose: Generate a response from the AI for a given channel\n- loadContext:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }))\n- writeAgentResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Write an AI response to a given channel\n\n4. Schema Design:\n- users\n  - validator: { name: v.string() }\n  - indexes: <none>\n- channels\n  - validator: { name: v.string() }\n  - indexes: <none>\n- messages\n  - validator: { channelId: v.id(\"channels\"), authorId: v.optional(v.id(\"users\")), content: v.string() }\n  - indexes\n    - by_channel: [\"channelId\"]\n\n5. Background Processing:\n- AI response generation runs asynchronously after each user message\n- Uses OpenAI's GPT-4 to generate contextual responses\n- Maintains conversation context using recent message history\n\n\n### Implementation\n\n#### package.json\n```typescript\n{\n  \"name\": \"chat-app\",\n  \"description\": \"This example shows how to build a chat app without authentication.\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"convex\": \"^1.31.2\",\n    \"openai\": \"^4.79.0\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.7.3\"\n  }\n}\n```\n\n#### tsconfig.json\n```typescript\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"exclude\": [\"convex\"],\n  \"include\": [\"**/src/**/*.tsx\", \"**/src/**/*.ts\", \"vite.config.ts\"]\n}\n```\n\n#### convex/index.ts\n```typescript\nimport {\n  query,\n  mutation,\n  internalQuery,\n  internalMutation,\n  internalAction,\n} from \"./_generated/server\";\nimport { v } from \"convex/values\";\nimport OpenAI from \"openai\";\nimport { internal } from \"./_generated/api\";\n\n/**\n * Create a user with a given name.\n */\nexport const createUser = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"users\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"users\", { name: args.name });\n  },\n});\n\n/**\n * Create a channel with a given name.\n */\nexport const createChannel = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"channels\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"channels\", { name: args.name });\n  },\n});\n\n/**\n * List the 10 most recent messages from a channel in descending creation order.\n */\nexport const listMessages = query({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      _id: v.id(\"messages\"),\n      _creationTime: v.number(),\n      channelId: v.id(\"channels\"),\n      authorId: v.optional(v.id(\"users\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n    return messages;\n  },\n});\n\n/**\n * Send a message to a channel and schedule a response from the AI.\n */\nexport const sendMessage = mutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    authorId: v.id(\"users\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const user = await ctx.db.get(args.authorId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      authorId: args.authorId,\n      content: args.content,\n    });\n    await ctx.scheduler.runAfter(0, internal.index.generateResponse, {\n      channelId: args.channelId,\n    });\n    return null;\n  },\n});\n\nconst openai = new OpenAI();\n\nexport const generateResponse = internalAction({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const context = await ctx.runQuery(internal.index.loadContext, {\n      channelId: args.channelId,\n    });\n    const response = await openai.chat.completions.create({\n      model: \"gpt-4o\",\n      messages: context,\n    });\n    const content = response.choices[0].message.content;\n    if (!content) {\n      throw new Error(\"No content in response\");\n    }\n    await ctx.runMutation(internal.index.writeAgentResponse, {\n      channelId: args.channelId,\n      content,\n    });\n    return null;\n  },\n});\n\nexport const loadContext = internalQuery({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      role: v.union(v.literal(\"user\"), v.literal(\"assistant\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n\n    const result = [];\n    for (const message of messages) {\n      if (message.authorId) {\n        const user = await ctx.db.get(message.authorId);\n        if (!user) {\n          throw new Error(\"User not found\");\n        }\n        result.push({\n          role: \"user\" as const,\n          content: `${user.name}: ${message.content}`,\n        });\n      } else {\n        result.push({ role: \"assistant\" as const, content: message.content });\n      }\n    }\n    return result;\n  },\n});\n\nexport const writeAgentResponse = internalMutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      content: args.content,\n    });\n    return null;\n  },\n});\n```\n\n#### convex/schema.ts\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n  channels: defineTable({\n    name: v.string(),\n  }),\n\n  users: defineTable({\n    name: v.string(),\n  }),\n\n  messages: defineTable({\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }).index(\"by_channel\", [\"channelId\"]),\n});\n```\n\n#### convex/tsconfig.json\n```typescript\n{\n  /* This TypeScript project config describes the environment that\n   * Convex functions run in and is used to typecheck them.\n   * You can modify it, but some settings required to use Convex.\n   */\n  \"compilerOptions\": {\n    /* These settings are not required by Convex and can be modified. */\n    \"allowJs\": true,\n    \"strict\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"jsx\": \"react-jsx\",\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n\n    /* These compiler options are required by Convex */\n    \"target\": \"ESNext\",\n    \"lib\": [\"ES2021\", \"dom\"],\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*\"],\n  \"exclude\": [\"./_generated\"]\n}\n```\n\n#### src/App.tsx\n```typescript\nexport default function App() {\n  return <div>Hello World</div>;\n}\n```\n","isInternal":false,"tokens":6446,"sizeBytes":27925},{"name":"README.md","path":".agents/rules/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/.agents/rules/README.md","title":"Rules Skill","category":"anthropic-skill","format":"markdown","content":"# Agent Rules Index\n\nCurated rules for agents and developers — quick, actionable guidance.\n\n## Canonical home & sync\n\nEvery rule has a single canonical home: `.agents/rules/<name>.mdc` — the only\ngit-tracked copy. Rule files must use the `.mdc` extension; the harnesses load\n`.mdc` only, so a `.md` rule is silently dead (`pnpm lint:rules:symlinks`\nrejects them). The `.cursor/rules/` and `.claude/rules/` trees are git-ignored\npresentation mirrors containing nothing but relative symlinks back into\n`.agents/rules/`.\n\n```bash\npnpm rules:sync           # Consolidate stray rules + (re)generate the symlink trees\npnpm lint:rules:symlinks  # Fail if a tree is out of sync with canonical (runs in CI)\n```\n\n`rules:sync` also runs from `prepare`, so `pnpm install` rebuilds the trees\nautomatically. **Add or edit rules at the canonical path** (`.agents/rules/`);\na rule dropped only into `.cursor/rules` is git-ignored and will be lost.\n","isInternal":false,"tokens":242,"sizeBytes":936},{"name":"SKILL.md","path":"skills-contrib/multiline-commit-messages/SKILL.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills-contrib/multiline-commit-messages/SKILL.md","title":"multiline-commit-messages","category":"anthropic-skill","format":"markdown","content":"---\nname: multiline-commit-messages\ndescription: >-\n  Use single-quoted strings for multiline git commit messages in the Shell tool.\n  Prevents heredoc escaping failures that produce garbled commit messages.\n---\n\n# Multiline commit messages\n\nThe Shell tool sends commands as a single string. Heredoc syntax (`<<'EOF'`) inside `$(cat ...)` is fragile and can fail silently — the literal `$(cat <<'EOF' ...` ends up as the commit message instead of the intended text.\n\n## Rule\n\nPrefer single-quoted strings with embedded newlines over `$(cat <<'EOF' ...)`:\n\n```bash\ngit commit -s -m 'short summary line\n\nLonger body paragraph explaining why the change exists.\nAdditional context if needed.'\n```\n\n## Why heredocs are fragile\n\nThe Shell tool passes the command as a single string argument. When you write:\n\n```bash\ngit commit -m \"$(cat <<'EOF'\nmessage\nEOF\n)\"\n```\n\nthe `EOF` delimiter, newlines, and nested quoting can interact unpredictably, and the result is the raw `$(cat <<'EOF' ...` text appearing as the commit message.\n\nSingle-quoted strings with literal newlines are simple, portable, and always work. If the message itself must contain a single quote, close and reopen the quote (`'\\''`) or fall back to a temp file passed via `-F`.\n\n## Sign off\n\nEvery commit still needs its `Signed-off-by` trailer — see [git-staging](../../../.cursor/rules/git-staging.mdc). Pass `-s` on the same `git commit` invocation.\n","frontmatter":{"name":"multiline-commit-messages","description":"Use single-quoted strings for multiline git commit messages in the Shell tool. Prevents heredoc escaping failures that produce garbled commit messages."},"isInternal":false,"tokens":336,"sizeBytes":1417},{"name":"SKILL.md","path":"skills-contrib/publish-npm-version/SKILL.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills-contrib/publish-npm-version/SKILL.md","title":"publish-npm-version","category":"anthropic-skill","format":"markdown","content":"---\nname: publish-npm-version\ndescription: >-\n  Cuts the next minor release of Prisma Composer: bumps the root\n  package.json version, propagates it to every workspace package in lockstep,\n  and opens a PR titled \"chore(release): v<next-version>\". When a maintainer\n  merges the PR, the `Publish to npm` workflow runs automatically and publishes\n  the new version to npm under dist-tag `next`, plus a matching GitHub Release\n  with auto-generated notes; users get it when a maintainer promotes it to\n  `latest`. Use when a maintainer asks to \"cut the next minor\",\n  \"bump to the next version\", \"open a release PR\", or \"prepare a publish PR\".\n---\n\n# Publish next npm version\n\n## Audience\n\nMaintainers who can push branches and open PRs. Invoke this **locally**, not as a\nGitHub Action — a PR opened by a workflow's `GITHUB_TOKEN` does not trigger CI,\nwhich defeats the point of a reviewable release.\n\n## Background reading\n\nRead [`docs/oss/versioning.md`](../../docs/oss/versioning.md) first — it is the\npolicy this skill mechanises: the root-`package.json` source of truth, the\nlockstep guarantee, the dist-tag convention, and the full procedure (this skill\nis the \"open the bump PR\" step; **merging the PR is the publish trigger** — there\nis no separate dispatch step).\n\n## Pre-flight\n\nConfirm you can fetch from `origin` (`git fetch origin main` succeeds). The skill\nworks in a fresh worktree off `origin/main`, so your current worktree is left\nundisturbed.\n\n## Steps\n\n1. **Fresh worktree off `origin/main`:**\n   ```bash\n   git fetch origin main\n   git worktree add -b chore/release-vNEXT ../release-vNEXT origin/main\n   cd ../release-vNEXT\n   pnpm install --frozen-lockfile\n   ```\n2. **Bump.** `pnpm bump-minor` reads the root version at `HEAD`, computes the next\n   minor (`0.2.0` → `0.3.0`), stamps every workspace `package.json` in\n   lockstep (rewriting internal `workspace:` deps to the new version), and\n   regenerates `pnpm-lock.yaml` to match.\n3. **Sanity-check** the bump is clean and complete. The diff must include\n   `pnpm-lock.yaml` — CI installs with `--frozen-lockfile`, so a bump without the\n   lockfile fails every CI job at the install step:\n   ```bash\n   git diff --stat                      # every workspace package.json + pnpm-lock.yaml\n   pnpm check:publish-deps              # no workspace:/catalog: leaks, exact internal pins\n   ```\n4. **Commit** with the release title and dual DCO sign-off, then push and open the PR:\n   ```bash\n   git commit -am \"chore(release): v<version>\"\n   git push -u origin chore/release-vNEXT\n   gh pr create --base main --title \"chore(release): v<version>\" \\\n     --body \"Release v<version>. Merging this triggers the Publish to npm workflow.\"\n   ```\n5. **Hand off.** Tell the maintainer the PR is open and that **merging it** publishes `<version>` to npm under `next` (via OIDC trusted publishing) and cuts a GitHub Release with auto-generated notes. Users get the release only once a maintainer promotes it to `latest` with the `Promote a release to latest` workflow (versioning.md § Promote a release to `latest`). Do not merge it yourself unless asked.\n\n## What this skill does NOT do\n\n- **Patches / old minors.** There are no patch releases of older minors\n  (versioning.md § pre-1.0). This skill only advances the latest minor.\n- **The publish itself.** That is the `Publish to npm` workflow, triggered by the\n  merge — never run `pnpm publish` by hand for a normal release.\n- **Release notes authoring.** The GitHub Release notes are auto-generated\n  (`gh release create --generate-notes`) by the workflow; there is no committed\n  release-notes file to write.\n","frontmatter":{"name":"publish-npm-version","description":"Cuts the next minor release of Prisma Composer: bumps the root package.json version, propagates it to every workspace package in lockstep, and opens a PR titled \"chore(release): v<next-version>\". When a maintainer merges the PR, the `Publish to npm` workflow runs automatically and publishes the new version to npm under dist-tag `next`, plus a matching GitHub Release with auto-generated notes; users get it when a maintainer promotes it to `latest`. Use when a maintainer asks to \"cut the next minor\", \"bump to the next version\", \"open a release PR\", or \"prepare a publish PR\"."},"isInternal":false,"tokens":916,"sizeBytes":3637},{"name":"SKILL.md","path":"skills-contrib/upgrade-alchemy-effect/SKILL.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills-contrib/upgrade-alchemy-effect/SKILL.md","title":"upgrade-alchemy-effect","category":"anthropic-skill","format":"markdown","content":"---\nname: upgrade-alchemy-effect\ndescription: >-\n  How to upgrade `alchemy` and the `effect` constellation across this repo and\n  keep them consistent for consumers: which packages pin what, why `effect` and\n  every `@effect/*` companion move as one set, what breaks in a typical\n  upgrade, and how to verify a standalone `npm install` still resolves a single\n  `effect`. Use when asked to upgrade or bump alchemy or effect, when a deploy\n  dies inside an alchemy provider with a `TypeError` naming a missing\n  combinator, when `check:npm-effect-resolution` fails, or when deciding\n  whether the alchemy patch is still needed.\n---\n\n# Upgrade alchemy and effect\n\n## Audience\n\nMaintainers changing the `alchemy` or `effect` pins in this repo.\n\n## Read this first\n\n**Check what upstream ships before working around what we pin.** The pinned\nversion is not a constant, and treating it as one is expensive: TML-3158 was a\nlong chase through pinning, peer dependencies, and a CLI preflight (since\nretired), all to keep\na consumer's tree away from an `effect` that alchemy 2.0.0-beta.59 could not\nrun — while a newer alchemy that had already fixed it sat on the registry the\nwhole time. One command would have shown it:\n\n```bash\nnpm view alchemy dist-tags\nnpm view alchemy@<latest> peerDependencies\n```\n\nIf alchemy's `effect` peer range has moved past our pin, the upgrade *is* the\nfix. Reach for workarounds only after that check says otherwise.\n\n## Why the versions move as a set\n\n`effect` and its companions — `@effect/platform-node`, `@effect/platform-bun`,\n`@effect/platform-node-shared` — each declare a peer that is\n**floored at their own version**:\n\n```jsonc\n// @effect/platform-bun@4.0.0-rc.111\n\"peerDependencies\": { \"effect\": \"^4.0.0-rc.111\" }\n```\n\nThat caret is a range, not an exact pin: it accepts `4.0.0-rc.112` and stable\n`4.x`, but nothing below `4.0.0-rc.111`. So an `effect` **older** than any\ncompanion in the tree is unsatisfiable, and npm resolves that by installing a\n*second* `effect`. Pinning every package in this repo to the same release is the\nsimple way to stay above every floor at once. Treat them as one constellation,\nnever as individual bumps.\n\nalchemy sits on top with a deliberately loose range (`>=4.0.0-rc.115 || >=4.0.0` at beta.78). That range is what lets a stray dependency drag a different `effect` in.\n\n## Two audiences, two failure modes\n\n- **This workspace** uses pnpm, which only *warns* on a peer mismatch and keeps\n  our pinned copy. A broken constellation is therefore invisible in-repo — CI\n  and local dev stay green while consumers break.\n- **Consumers** use npm, which hoists a satisfying version to the root of\n  `node_modules`. alchemy imports whatever is at the root. Nothing we declare\n  prevents this: an exact `peerDependencies` entry does **not** make npm fail —\n  verified empirically, it warns, hoists the other copy anyway, and exits 0.\n  Only the consumer's own `overrides` can force alchemy's copy.\n\nThat asymmetry is why `scripts/check-npm-effect-resolution.mjs` installs real\ntarballs with real npm.\n\n## What a consumer sees when the tree is wrong\n\nComposer has no check of its own for a wrong `effect`. The app's\n`prisma.config.ts` imports the extensions' `/control` entries in its `composer`\nsection, and those import alchemy, so a wrong `effect` fails the moment the\nengine evaluates the config file, before any command runs. The error is the\nengine's `CLI.CONFIG_UNREADABLE`, naming the file and carrying the module error,\nfor example `prisma.config.ts could not be evaluated: Schema.TaggedError is not\na function`. Only the consumer's package manager can fix that tree, usually\nwith an `overrides` entry that forces our pinned `effect`\n(`docs/guides/deploying.md`). Keep the pins below exact and consistent so a bare\ninstall never gets there.\n\n## Steps\n\n1. **Pick the target.** Read alchemy's latest peer range, then choose the newest release where *every* companion publishes a matching version:\n\n   ```bash\n   npm view alchemy dist-tags\n   npm view alchemy@<version> peerDependencies\n   for p in effect @effect/platform-node @effect/platform-bun \\\n            @effect/platform-node-shared; do\n     echo \"$p $(npm view $p version)\"\n   done\n   ```\n\n   alchemy's floor is not a compatibility promise. alchemy 2.0.0-beta.75 to beta.77 accept `effect` rc.112 and later, but call `Config.string`, which rc.113 removed, so they crash on it. Pin the `effect` release alchemy was built against: the newest one published before that alchemy release (`npm view effect time`). Check the new alchemy's Prisma provider still loads from a plain npm install: in beta.79 it imports the optional peer `@alchemy.run/frontend-frameworks` and fails. Since beta.84 each provider is its own package, versioned in lockstep with `alchemy`: the Prisma provider is `@alchemy.run/prisma` (formerly the `alchemy/Prisma` module), and only `@prisma/composer-prisma-cloud` and the Prisma Cloud internals depend on it. Bump it with `alchemy`.\n\n2. **Find every pin.** `alchemy`, `@alchemy.run/prisma`, `@distilled.cloud/prisma`, `effect` and the `@effect/platform-*` packages are pinned once, in the `catalog:` block of `pnpm-workspace.yaml`; every manifest says `catalog:`, and `pnpm pack` writes the resolved version into the published manifest. Check nothing outside the catalog pins them:\n\n   ```bash\n   grep -rln '\"alchemy\"\\|\"@alchemy.run/\\|\"@distilled.cloud/\\|@effect/\\|\"effect\"' --include=package.json . | grep -v node_modules\n   ```\n\n3. **Clear the patch key first.** `pnpm.patchedDependencies` is keyed by the\n   exact version, so an alchemy bump leaves it pointing at a version that is no\n   longer installed and the next install fails or silently skips the patch.\n   Remove the entry now and re-create it in step 5 once you know whether it is\n   still needed.\n4. **Bump all of them to the same versions**, then `pnpm install`. Nothing may\n   be left behind — a single stale companion reintroduces the second `effect`.\n5. **Decide the patch** (see below): typecheck without it, and only re-create\n   it against the new version if upstream still needs the fix.\n6. **`pnpm typecheck`.** Expect real API breakage; see the classes below. Note\n   that turbo stops at the first failing package, so run `pnpm exec tsc\n   --noEmit` per package to see the true scope.\n7. **`pnpm check:npm-effect-resolution`** (after building the two public\n   packages). This is the consumer-facing proof.\n8. **The E2E deploy jobs are the real bar.** An alchemy upgrade changes the\n   deploy engine; a green typecheck says very little about it.\n\n## Pinning an unreleased alchemy build\n\nThe repo is on registry releases: `alchemy` and `@alchemy.run/prisma` 2.0.0-beta.87, `@distilled.cloud/prisma` 1.0.0-rc.20, and `effect` with its companions at 4.1.4. History: Composer pinned a preview of alchemy-run/alchemy#3101 until beta.87 released it together with alchemy-run/distilled#1076. Those two changes let `PrismaEnvironment` and Distilled's `Credentials` omit the token, which `prisma deploy` needs to send every request through the engine's client. Use a preview only when you need a fix that no release contains yet.\n\nalchemy publishes a preview of every commit on `main`, and of each pull request's head as `pr:<number>:<short sha>`. Pin it by commit, never by branch, in the `catalog:` block of `pnpm-workspace.yaml`:\n\n```yaml\nalchemy: https://pkg.alchemy.run/alchemy/<commit sha>\n'@alchemy.run/prisma': https://pkg.alchemy.run/@alchemy.run/prisma/<commit sha>\n```\n\n- **No release while a pin is a URL.** `check:publish-deps` (run by the publish workflow on every push to `main`) fails on any URL, git or `file:` dependency in a published package. Swap the pins for a registry release before merging to `main` expecting a publish.\n\n- **The commit URL is immutable.** It redirects to a content-addressed tarball (`/alchemy/-/<sha256>.tgz`). The lockfile records the commit URL and the tarball's integrity.\n- **Pin `alchemy` and every `@alchemy.run/*` package at the same commit.** They are built together.\n- **A preview's own dependencies are content-addressed URLs too.** `@alchemy.run/prisma` depends on `@distilled.cloud/prisma` by a `/-/<sha256>.tgz` URL. Pin our `@distilled.cloud/prisma` to that exact URL (read it from the tarball's `package.json`), or pnpm and npm install a second copy and `Credentials` stops matching. The commit URL for the same package does not dedupe with it.\n- **The `alchemy` peer of `@alchemy.run/prisma` is a tarball URL.** For a commit preview it may name a different tarball hash than the commit URL resolves to; the two differ only in an embedded URL in `package.json`, and npm accepts our copy. For a pull request preview (`pr:<n>:<sha>`) the peer names the same tarball the PR URL redirects to, but npm compares the specs and `npm ls` reports our `alchemy` invalid, so `check:npm-effect-resolution` fails. Pin `alchemy` to the peer's exact tarball URL then.\n- **Not every package has a preview.** `@alchemy.run/test` returns 404 at every commit, so nothing may depend on it (see the breakage classes).\n- **Read the source at the commit**, not the docs: `git clone https://github.com/alchemy-run/alchemy && git checkout <sha>`, or extract the tarball into a gitignored `wip/` folder.\n- **Move back to a registry version** once a release contains the commit: `npm view alchemy dist-tags`, then compare the release date with the commit date.\n\n## The effect-family packages a consumer installs are pinned in the public packages\n\nalchemy's `effect`-family ranges float past what its code supports (the upstream `TaggedErrorClass` drift), and a floater whose newest release names an `effect` peer that does not exist yet sends npm into hours of backtracking instead of an error (2026-09-11: `@effect/*@4.0.0-rc.114` published ahead of `effect`). Consumers carry no overrides block. Instead, the rule is:\n\n**Pin exactly, in a public package's `dependencies`, every `effect`-family package that a consumer's install will contain.** A package is in the install when it is a regular dependency of `alchemy` or `@alchemy.run/prisma`, an optional peer that one of them loads at runtime, or a package Composer's own code imports. An optional peer that nothing loads is not installed by npm at all, so it gets no pin: pinning it would install it, and everything it depends on, for every consumer.\n\nToday that is:\n\n- `@prisma/composer` — `effect` itself.\n- `@prisma/composer-prisma-cloud` — `@effect/platform-bun` and `@effect/platform-node`, which alchemy loads at runtime (`alchemy/Util/PlatformServices`, `alchemy/Http`; Composer's provider wiring also imports `@effect/platform-node`), and `@effect/platform-node-shared`, which both depend on. It also depends on `@distilled.cloud/prisma`, whose `Credentials` the provider wiring imports; keep it at the exact version `@alchemy.run/prisma` depends on (a tarball URL for a preview) so npm installs one copy.\n\nTo apply the rule on an upgrade, read `dependencies` and `peerDependenciesMeta` in both `alchemy/package.json` and `@alchemy.run/prisma/package.json`, and grep the built `dist/` of the public packages and the installed `lib/` of both for imports of each `@effect/*` package.\n\nHistory: beta.83 listed `@effect/sql-d1` and `@effect/sql-sqlite-do` as regular dependencies, so `@prisma/composer` pinned them, along with `@effect/vitest`, which it pinned on its own. Beta.84 no longer depends on the two SQL packages, and `@effect/vitest` is an optional peer that only `alchemy/Test/Vitest` loads. All three pins were dropped with the beta.84 bump. Dropping `@effect/vitest` also removed `vitest` and `vite` from every consumer's install.\n\n`check-npm-effect-resolution` installs the tarballs bare and fails when the install backtracks or resolves a second `effect`. It installs once more with npm 10, the npm that Node 22 bundles, because npm 10 has crashed on packages the tree once contained (`vitest@4.1.x`); the shape stays as a guard for Node 22 users. The only case left to a consumer's own `overrides` is an app that pins a different `effect` itself (documented in `docs/guides/deploying.md`).\n\n## Breakage classes seen in practice\n\n- **Removed `effect` combinators.** `Schedule.both`/`Schedule.either`\n  (intersection/union) disappeared at beta.97. `Schedule.both(spaced(x),\n  during(y))` becomes `Schedule.spaced(x).pipe(Schedule.upTo({ duration: y }))`;\n  `Schedule.max`/`Schedule.min` are the general replacements.\n- **Stable Effect HTTP imports.** Effect 4 uses `effect/http/*`, replacing `effect/unstable/http/*`.\n- **Alchemy lifecycle identity.** Since beta.82, provider fixtures supply `ResourceContext` (`logicalId`, `fqn`, `instanceId`, `type`) instead of `InstanceId`. Local Database, App and Bucket attributes also need `logicalId`; use `null` because local dev creates no platform rows.\n- **Vitest 5 type tests.** Stable `@effect/vitest` requires Vitest 5. Type-only files need a registered test; keep ambient declarations outside its callback or use definite-assignment fixtures inside it.\n- **Providers moved out of `alchemy` (2.0.0-beta.84).** `alchemy/Prisma` is now the separate package `@alchemy.run/prisma` (`alchemy/Prisma/Types` becomes `@alchemy.run/prisma/Types`). Add it to every package that imports it, including `@prisma/composer-prisma-cloud`, which bundles them. `alchemy` itself no longer depends on `@distilled.cloud/*` or the `@effect/sql-*` packages.\n- **`alchemy/Test/Core` is gone (2.0.0-beta.84).** It moved to `@alchemy.run/test`, which is not published. Provider tests use `scratchStack` and `runScratch` from `@internal/lowering/scratch-stack`, a port of the parts we used.\n- **Real network calls in provider tests.** At the 2.0.0-beta.84 preview, `Prisma.CustomDomain` waits for the hostname's CNAME on its authoritative nameservers before it registers a domain. Tests stub `node:dns/promises` so the wait is skipped.\n- **New adoption advice in engine or provider messages.** `withComposerAdvice` in the CLI rewrites Alchemy's `--adopt` and \"explicit adoption\" advice; its tests read every such message from the installed `alchemy` (`Plan.ts`, `Apply.ts`) and `@alchemy.run/prisma` sources and fail on one it does not rewrite. Add the new message to the rewrite list.\n- **Typed provider errors (2.0.0-beta.87).** Every lifecycle method of a `ProviderService` must fail with `Provider.ProviderError` (`{ _tag: string; message?: string }`), not `unknown`. `Effect.tryPromise` sites pass `catch: toProviderError` from `@internal/core/deploy`, which keeps an error that already has a `_tag` and wraps any other in a `ProviderFailure` with the same message and the original as `cause`. The deploy reports a wrapped error as the error it wraps.\n- **`PrismaEnvironment` holds an Effect (2.0.0-beta.87).** Alchemy runs it on every Management API request. Provide `Layer.succeed(Prisma.PrismaEnvironment, Effect.succeed({ ... }))`.\n- **New required fields on alchemy's resource-handler context** (e.g. `fqn`).\n  These surface only in the test fixtures that build the context by hand.\n- **`exactOptionalPropertyTypes` vs alchemy's types.** See the patch section.\n- **Error counts that go *up* after a fix.** TypeScript stops at the first bad\n  argument, so repairing it exposes the next one. Rising counts mid-upgrade are\n  normal, not a sign the fix was wrong.\n\n## The alchemy patch\n\n`patches/alchemy@<version>.patch` fixes one upstream type declaration:\n`ResourceClassLike.Aliases` is `readonly string[]` (exact-optional) while\n`ResourceClass.Aliases` is `readonly string[] | undefined`. Under this repo's\n`exactOptionalPropertyTypes`, the second is not assignable to the first, so\n**every** `Provider.effect` and `Provider.collection` call fails to compile —\n45 errors across three packages at the time of writing. alchemy carries\n`@ts-expect-error` at its own equivalent call sites, so this is upstream's\ninconsistency, not our misuse.\n\n**Do not work around it at the call sites.** That was tried: it needs a cast at\nroughly twenty sites, and narrowing the argument type also destroys inference\nfor the second argument, which surfaces a fresh wave of errors. Adding\n`| undefined` to the optional property fixes all of them at the source.\n\nOn every upgrade, check whether upstream has fixed it. With the\n`pnpm.patchedDependencies` entry already removed in step 3:\n\n```bash\npnpm install && (cd packages/1-prisma-cloud/0-lowering/lowering && pnpm exec tsc --noEmit)\n```\n\nClean means the patch is obsolete: delete `patches/alchemy@<old>.patch` and\nleave the config entry out. Still failing means re-create it against the new\nversion:\n\n```bash\npnpm patch alchemy@<version>   # edit lib/Resource.d.ts, then patch-commit\n```\n\nHistory: alchemy 2.0.0-beta.67 needed the patch (`lowering` alone reported 17\nerrors without it); upstream fixed the declaration by 2.0.0-beta.74 and the\npatch was deleted with that bump. The check above stays — the inconsistency\ncould regress in a future release.\n\n## The @alchemy.run/node-utils patch\n\n**Resolved — the patch was deleted with the beta.74 bump**: alchemy no longer\nships a file-lock module at all (`@alchemy.run/node-utils` 2.x exports only\n`ignore`), so there is nothing left to patch. The history and the standing\ncheck below stay, because the property it protected still matters.\n\nThe patch was\n[alchemy-run/node-utils#6](https://github.com/alchemy-run/node-utils/pull/6)\n(\"fix(lockfile): scope exit hooks to owned locks\"), vendored against\nnode-utils 0.0.5. Without it, `lib/lockfile.js` called `exitHook(...)` at module scope, so merely\nimporting `alchemy` registered a SIGINT, a SIGTERM, and an `exit` listener on\nthe process. Composer's commands run inside the Prisma CLI engine, and the\nengine owns the whole signal policy: the first Ctrl-C aborts the command and\nwaits for teardown, a second one force-exits. A stray SIGINT listener that\ncalls `process.exit(130)` on its own pre-empts that, killing the process while\nthe engine's cleanup is still running. The engine's family test suite asserts\nthat after a composer command's config evaluation the engine is the sole\nSIGINT/SIGTERM listener, and that assertion is what fails if a stray listener\nis ever reintroduced.\n\nOn every alchemy bump, re-run the standing check (the CLI's signal-listeners\ntest suite runs the same probe):\n\n```bash\ncd packages/9-public/composer-prisma-cloud && node --input-type=module -e 'const c=()=>process.listenerCount(\"SIGINT\")+process.listenerCount(\"SIGTERM\");const b=c();await import(\"alchemy\");await import(\"@alchemy.run/prisma\");console.log(c()-b,\"listeners registered by a bare import (must be 0)\")'\n```\n\n## Keeping the regression check honest\n\n`scripts/check-npm-effect-resolution.mjs` has three shapes: two healthy\ninstalls and one adversarial tree where alchemy resolves an `effect` we did not\npin. Two things about it are easy to get wrong after an upgrade:\n\n- **Do not assert the presence of a specific combinator.** That only ever stood\n  in for \"alchemy can run on this `effect`\", and it breaks the moment upstream\n  removes it for good reasons. `importAlchemy` answers the same question\n  directly: it imports alchemy's root, `Output`, `Provider` and `Stack` entries\n  from the installed app, which must succeed in the healthy shapes and fail in\n  the adversarial one.\n- **`WRONG_EFFECT` must stay a published version other than the pin.** The\n  adversarial shape used to depend on a release whose peer sat *above* our pin;\n  that stopped existing once the pin reached the newest beta, and the shape\n  quietly stopped being adversarial. It now sets the version with an npm\n  `override` instead, so it does not depend on what the registry publishes.\n\n## Gotchas\n\n- **A clean install before believing a failure.** Switching branches around a\n  dependency change leaves stale `node_modules` that produce failures unrelated\n  to the diff. `rm -rf node_modules && pnpm install` before diagnosing.\n- **Compare against `main` before blaming the upgrade.** Some suites fail only\n  under the fully parallel `turbo run test` and pass in isolation, on `main`\n  too; and `@internal/streams` reports a large pre-existing typecheck error\n  count from a third-party package's own source.\n- **`pnpm dedupe` after the pins move**, so stale peer-resolution keys do not\n  linger in the lockfile — but commit it separately, since it touches\n  resolutions beyond the ones being upgraded.\n- **`@prisma/composer`'s `dependencies.effect` must stay an exact version.**\n  `check:npm-effect-resolution` reads it and fails on a range.\n\n## What this skill does NOT do\n\n- **Decide when to upgrade.** alchemy is pre-1.0 and moves fast; this is the\n  procedure, not a schedule.\n- **Upgrade unrelated dependencies.** Keep the constellation bump its own\n  change so a deploy regression has one obvious suspect.\n- **Publish.** See [`publish-npm-version`](../publish-npm-version/SKILL.md).\n","frontmatter":{"name":"upgrade-alchemy-effect","description":"How to upgrade `alchemy` and the `effect` constellation across this repo and keep them consistent for consumers: which packages pin what, why `effect` and every `@effect/*` companion move as one set, what breaks in a typical upgrade, and how to verify a standalone `npm install` still resolves a single `effect`. Use when asked to upgrade or bump alchemy or effect, when a deploy dies inside an alchemy provider with a `TypeError` naming a missing combinator, when `check:npm-effect-resolution` fails, or when deciding whether the alchemy patch is still needed."},"isInternal":false,"tokens":5214,"sizeBytes":20860},{"name":"SKILL.md","path":"skills-contrib/upstream-alchemy-distilled/SKILL.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills-contrib/upstream-alchemy-distilled/SKILL.md","title":"upstream-alchemy-distilled","category":"anthropic-skill","format":"markdown","content":"---\nname: upstream-alchemy-distilled\ndescription: >-\n  How Prisma Composer, the Prisma Cloud target, Alchemy's Prisma provider (`@alchemy.run/prisma`), the Distilled Prisma SDK (`@distilled.cloud/prisma`) and the Prisma Management API (prisma/pdp-control-plane and its OpenAPI spec) depend on each other, and how to get a change through alchemy-run/alchemy or alchemy-run/distilled as an outside contributor without the maintainers rewriting or rejecting it. Use this whenever work will change or plans to change either upstream repository, how a `Prisma.*` Alchemy resource behaves or what it accepts (as opposed to how Composer uses it), the generated Prisma SDK, or a Management API behaviour that Composer's deploy depends on; whenever a Prisma pull request is open in either upstream repository; and to decide which repository a change belongs in before any code is written, even if the request only says \"the provider\", \"the SDK\", \"upstream\" or \"the Alchemy PR\". For moving Composer to a new Alchemy release, use `upgrade-alchemy-effect` instead.\n---\n\n# Changing Alchemy and Distilled from Prisma's side\n\n## Audience\n\nAn agent or engineer on the Prisma side whose work needs something from Alchemy's Prisma provider or the Distilled Prisma SDK. Both repositories belong to the Alchemy team. We are outside contributors there, and we maintain only the Prisma parts.\n\nIf you are about to edit a file in either repository from a Composer session, stop and read \"Work inside their repository, in its own session\" first.\n\nWhy this skill exists: between May and November 2026, Prisma's pull requests to these two repositories drew dozens of objections, rewrites and rejections from the maintainers, and several of their contributor rules were written within hours of one of ours. Almost all of it came from a few causes: working without their guidance loaded, inventing where they wanted a copy of an existing pattern, putting a change in the wrong repository, and treating their repositories as ours.\n\n## The pieces\n\n- **Alchemy** is an infrastructure-as-code engine written with Effect. A program declares *resources*; Alchemy plans and applies them. Composer turns an app into Alchemy resources, and Alchemy runs inside the `prisma` CLI to deploy them.\n- A **provider** is a package of resources for one cloud. Alchemy's Prisma provider, `@alchemy.run/prisma`, holds the `Prisma.*` resources that call Prisma's API. A resource may also have **bindings**: the runtime client a deployed app uses to reach it.\n- **Distilled** generates a typed Effect client (an SDK) for each cloud from that cloud's published API description. A **patch** in Distilled is a small JSON file that corrects the description before generation. Nobody edits the generated code.\n- **PDP** is Prisma's platform, in the private repository prisma/pdp-control-plane. Its **Management API** is what all of the above call, and it publishes its own OpenAPI description.\n- Composer's **Prisma Cloud target** and its **lowering** are the code in this repository that map an app's nodes to provider resources. `docs/design/05-prisma-cloud/alchemy-lowering.md` and the glossary (`docs/design/03-domain-model/glossary.md`) define the rest.\n\n## The chain, and who owns each link\n\nChecked 2026-11-27. Each cell says where to check it again.\n\n| Link | Where it lives | Owner | How a change leaves it |\n| --- | --- | --- | --- |\n| 1. Management API | prisma/pdp-control-plane | Prisma | Deployed to production |\n| 2. OpenAPI spec | Published by the API itself (the mirror's fetch script has the URL) | Prisma | Changes when link 1 deploys |\n| 3. Spec mirror | A git repository the Alchemy team runs, named in Distilled's `.gitmodules` | Alchemy team | Copies the published spec on a schedule (its workflow file has the schedule; daily when checked) |\n| 4. Distilled Prisma SDK | alchemy-run/distilled, the Prisma package: generated code plus patches | Alchemy team; we contribute to the Prisma package | A pull request moves the mirror pin, regenerates, and adds or prunes patches |\n| 5. Alchemy Prisma provider | alchemy-run/alchemy, the Prisma package. Alchemy takes Distilled as a git submodule pinned to one Distilled commit (its `.gitmodules`) | Alchemy team; we contribute to the Prisma package | A pull request, then an Alchemy release |\n| 6. Composer | This repository. Versions are pinned in `pnpm-workspace.yaml` | Prisma | A pin bump, then a Composer release |\n\nEach link is built from the one before it. Composer is the exception to \"only talks to its neighbour\": it also uses the Distilled SDK's credentials type directly and calls the Management API itself for a few things, so a Distilled change can reach Composer without an Alchemy change, and Composer's Distilled pin has to match the one the provider depends on.\n\nWhat follows from this shape:\n\n- **Composer implements no Management API resources itself.** It composes the upstream provider's resources and writes its own only where upstream has none or no API exists behind them. That is a recorded decision: read `docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md` before proposing anything that changes it.\n- **Composer depends on two Alchemy things**: the engine (`alchemy`) and the Prisma provider. A fault in the engine or in another provider is their code, not ours. Describe it to the operator as an issue to raise with them; do not fix it.\n- **Distilled reflects the published spec.** A patch states only what their current rule accepts as evidence (the spec, a real response, the provider's own docs or client). The maintainers' position, on one of our pull requests: \"you work at Prisma, if consumers of the api need to know ... that should go in the API, not a patch in our SDK that adds a value the spec doesn't have.\"\n- **Alchemy calls the cloud only through Distilled.** No hand-written client and no status-code checks in the provider. A missing operation or error type is a Distilled change.\n- **The spec's own markings travel down the chain.** For example, operations the spec marks experimental have been moved to a separate module of the SDK, which changes the imports of every provider file that uses them once Alchemy takes that version.\n- **A change moves only as fast as its slowest link.** The mirror has its schedule, each upstream pull request waits for a maintainer, and Composer can only pin a release or a preview build. Plan the order before starting and tell the operator how many upstream pull requests it means, counted by their rules. Each costs the maintainers a review. An instruction from our side to keep it to one does not change their rule: say what count their rules produce and why, before starting.\n- **Links 1 and 2 are the only ones we control.** When something is hard to express downstream, the cheapest correct fix is usually in our own API or spec.\n\n## Decide where the change belongs\n\nWork this out before writing code, from the top of the chain down. The first link where the needed fact is missing is where the change starts.\n\nWhichever case it is: before offering any opinion on how a platform resource should be modelled, read that resource's design documents in prisma/pdp-control-plane (its `docs/` folder). They define the lifecycle you will model. Code on its `main` is not the design, and states that look like defects, such as a resource that stays pending, are often intended.\n\n**The API must behave differently, or expose something it does not.** Start in prisma/pdp-control-plane. Ship to production, wait for the mirror, then a Distilled pull request, then an Alchemy pull request, then an Alchemy release, then Composer's pins. If the change would break the provider that is already released, ship it so the old behaviour keeps working, have the operator tell the maintainers before it ships, and remove the old behaviour only after an Alchemy release carries the new provider. The maintainers once discovered on their own that a platform change had broken a feature for every Alchemy user.\n\n**The API already does it and the spec says so, but the SDK is older than the spec.** A Distilled pull request that moves the mirror pin and regenerates; their repository has a skill for it. Check their `main` first, because maintainers regenerate too. A regeneration carries every spec change since the old mirror pin, not only the one you came for: say in the description what else it brings.\n\n**The API does it but the spec does not say so** (an undeclared error response, a field that can be null). Prefer fixing the spec in pdp-control-plane: we own it and every consumer benefits. The SDK still has to be regenerated from the new spec afterwards, by the maintainers' own regeneration or by ours, so check their `main` before opening one. A Distilled patch is for a gap we cannot close quickly, with the evidence their rules ask for.\n\n**The SDK's own runtime code for Prisma must change** (its credentials layer, a hand-maintained module in the Prisma package). A Distilled pull request of its own; by their rule it does not share one with a spec fix or a regeneration.\n\n**Only the provider's behaviour or shape must change.** An Alchemy pull request. A change to what a resource accepts or returns is breaking for every Alchemy user, not only Composer, and their conventions say how to mark and explain that. Composer's lowering and its local stand-in providers bind the same resource classes, so they change with it.\n\n**The Alchemy change needs Distilled code newer than Alchemy's pinned commit.** See \"The Distilled pin\" below before doing anything.\n\n**Only Composer needs something to be different.** First try to meet the need in Composer: build a different Layer, wrap the resource, or write a Composer-owned resource where the recorded decision allows one. An option added upstream to serve our embedding has been refused (\"The user shouldn't provide them. If they want to override them, they can construct a new layer.\"). Go upstream only when the need would exist for any Alchemy user.\n\n**You need an upstream change that is not released, or not merged, to check the Composer side.** Alchemy publishes preview builds of commits and of pull request heads. The `upgrade-alchemy-effect` skill covers pinning one and what it blocks.\n\n**It is none of these.** A change to Distilled's shared core or generator, or to Alchemy's engine, for a need only Prisma has, fits nowhere above; Distilled's written rule is that one provider's rule stays in that provider. Describe the need to the operator as a scenario and say which link you think it belongs to.\n\n## What is ours and what is not\n\nIn both repositories we own the Prisma package and its tests, docs and examples. Everything else belongs to the maintainers. Offering to do their upkeep is not a courtesy: it puts our name on changes to code we do not maintain, and it spends the operator's time and machine on work they do anyway.\n\nTheir guidance (as read in November 2026) is written for their own agents, who own the whole repository. So it tells its reader to do some things that an outside contributor should not do unasked. On these, the limits here hold, because each comes from what happened when we did it. If their guidance ever addresses outside contributors directly on one of them, theirs wins and this skill needs a fix.\n\n- **Moving the Distilled pin past our own change.** Their instruction to move it to the merged commit we follow as written. Moving it further, or testing what a move does to other providers, is theirs. See the next section.\n- **Checking the whole repository.** Their guidance says to type-check the whole workspace before a commit. Run the type check for the Prisma package and the test files your change touches. Their CI checks everything else on the pull request, so read it. A whole-workspace run on the operator's machine reports errors in other people's code that we will not fix.\n- **Opening early drafts that carry a status report.** Their own agents do this for work in progress. Our drafts have been finished by a maintainer, merged before we were done, or left to rot. Open a pull request when the work is complete.\n- **Rebasing at checkpoints.** Once a branch has a pull request, merge their `main` into it and never force-push: maintainers push to our branches, and a force-push discards their commits and their place in the review.\n\nAlso not ours: other providers' code, shared core, the generator, the engine, repository-wide configuration, and the lockfile beyond what our own dependency change requires.\n\nWhen a previous session's handover lists upstream work, check each step against this section before doing it. A handover is a predecessor's plan, not the operator's approval. That covers its working copies and its open pull requests too.\n\n### The Distilled pin\n\nAlchemy pins one Distilled commit for the whole repository. An Alchemy change that needs newer Distilled code cannot build until that pin includes it.\n\nTheir skill for provider work tells its reader to land the Distilled change first, then move the pin to the merged commit and commit it. We follow that as written, without asking first, until a maintainer tells us otherwise (the operator's decision, 2026-11-27): the move is from one of their commits to another of their commits, and it is what their own guidance asks for. If a maintainer does say otherwise, do what they say, and add it to this section with its date.\n\nWhat stays theirs is everything beyond that one step. Move the pin to the exact commit our Distilled change merged as, and nothing later: when one of ours moved it further, it pulled in other providers' SDK changes and broke two of their type checks, and a maintainer re-pinned it himself. Do not test or fix other providers against the new pin. A pin pointed at a commit that exists only on our fork cannot be fetched by anyone else, so it can never merge.\n\nThese steps apply the same way to a pull request that is already open.\n\n1. Open the Distilled pull request complete. Build and test the Alchemy change locally by checking the Distilled branch out in your working copy of the submodule without committing the pointer, and keep it on a fork branch with no pull request. Their rules ask a breaking Distilled change to link the Alchemy change that adapts to it: link the fork branch and say its pull request opens once the Distilled change has merged. An Alchemy pull request that cannot build is unfinished work, so it is opened early only if a maintainer asks for it, and then as a draft that says so.\n2. Once the Distilled change merges, move the pin to that exact merged commit, in a commit of its own, and say so in the description with the commit's hash. If the pin has to pass over other Distilled commits to get there, check that the Prisma package still builds and its touched tests pass, and name in the description anything in that range that changes the Prisma SDK.\n3. Then open the Alchemy pull request. If their CI fails in other providers because of the pin, report that to the operator; do not fix other providers.\n4. A pull request that already carries a pointer to our fork is repaired with a new commit that restores their pin, never a force-push.\n\n## Work inside their repository, in its own session\n\nDo not edit an upstream repository from a clone inside a Composer worktree, and do not send subagents from a Composer session to work there. An agent gets a repository's instructions in full only when its session starts in that repository. From anywhere else it gets Composer's rules plus whatever fragments of theirs it happens to search for. That is how a reviewer came to judge Alchemy code against Composer's review checklist, and how Distilled's contributor rules were first read one minute before a pull request was opened.\n\n**How.** Start a new agent session whose working directory is a checkout of the upstream repository, with whatever your harness offers for that, or ask the operator to open one and hand them the brief to paste as its first message. If you can do neither, stop and ask; a subagent pointed at the folder is not a substitute, because it inherits this session's instructions.\n\n**Where.** A clone of the fork we push from, outside every Composer worktree, where the operator keeps such clones (ask once). One checkout per agent: the installed dependency tree is shared state, and two agents in one checkout have broken each other's runs.\n\n**Distilled is its own repository.** Alchemy vendors Distilled as a submodule and its own guidance has its agents patch and regenerate there. For us a Distilled change runs in a session started in a Distilled checkout, so Distilled's contributor rules are loaded. Do not install dependencies inside Alchemy's copy of Distilled: Alchemy's workspace supplies them, and a second install there has broken the checkout.\n\n**Work already in the wrong place.** If a predecessor left clones with commits inside a Composer worktree, move the work, do not continue it there: push its branch to the fork and start the upstream session on that branch. If that branch already has a pull request, push the unfinished work under a new branch name instead, so nothing unfinished lands on a branch a maintainer may merge.\n\n**\"Just do it here.\"** A message that hands you a clone inside the worktree, or says \"do that\", was written before the operator heard the concern, so it is not yet their decision. Say once what goes wrong without their instructions loaded, offer to write the brief for an upstream session, and ask. Then do what they decide. If they decide on in place, read that repository's guidance in full by hand before touching anything, and say in your report that it was done that way.\n\n**Reading is not editing.** A Composer session may read upstream source, guidance, issues and pull requests to work out which link a change belongs in. It does not edit there and does not propose a resource's shape.\n\n**Two repositories, two sessions.** When a change needs both, the Composer session coordinates: the Distilled session first, then the Alchemy session against the Distilled branch. Record in the project's plan where each checkout is and which session owns it, so a successor does not ask the operator again.\n\n**What stays in the Composer session:** what the work is for, what Composer needs from upstream, the project record under `.drive/`, and the brief. It does not recommend a resource's shape to the operator: what an upstream resource looks like to an Alchemy user is proposed by the upstream session, after its reading, and goes to the operator before it is built. A recommendation made from the platform's side alone has had to be reversed once the existing Alchemy pattern was read.\n\n**The brief** for the upstream session says:\n\n- What the change is for, and the design as our best effort: the purpose is fixed, the mechanism is open to challenge against their code and conventions.\n- Where the platform's design documents for the resource are, and that it reads them before modelling a lifecycle.\n- The absolute path of this skill's folder, and that it reads `SKILL.md` there. Composer's skills are not installed in their repository.\n- The limits in \"What is ours and what is not\".\n- That a change to what users declare or see goes back to the operator before it is built.\n- That rules meant for pull requests in our own repositories do not carry over: our description style, any line naming the agent, auto-merge, and merging it ourselves. Upstream, the maintainers merge. An independent review before the pull request opens is still worth having, judged against their guidance and not our own review checklist.\n\n**The first things the upstream session does**, before any design opinion or code:\n\n1. Read the repository's agent guidance in full, not by searching it: the root instruction file, what it links for outside contributors, the pull request template if there is one, and the repository's own skills for the kind of change in hand. These files change often. They are the authority on how code, tests, names, commits and descriptions look in their repository, and they win over this skill on all of that.\n2. Find where the repository already does the same job (another provider's resource of the same kind, a binding, a test fixture, a credentials layer) and read it. Copy its names, shape and mechanism.\n3. Search their open issues and pull requests for the same problem. We once built something they already had an open issue for, and they shipped their own design within days.\n4. Check that their `main` has not already fixed it, and check again each time you merge their `main`.\n\n## What the maintainers hold to\n\nThese have held across the record so far. Each has its reason, so you can judge a case their files do not cover.\n\n- **Follow what exists; invent nothing.** They value a consistent repository over a locally better idea (\"I prefer the repo to be consistent\"; \"This isn't something we typically do\"). A concept, name, option or branch that no other provider has will be rewritten. When you believe a departure is right, say in the description why the existing way is not enough, before they ask.\n- **A resource is not finished when it deploys.** They have expected its runtime bindings, and for compute an Effect-native form, in the same piece of work. Find out from their guidance what the resource kind requires and count it before telling the operator the size.\n- **Alchemy provider changes are proven by deploying real resources.** No fakes, mocked responses or direct lifecycle calls. Our tests were rewritten as live tests on six pull requests, five of them by the maintainers' own commits, and the live versions found provider bugs on at least four. A failure the real platform cannot be made to produce comes from a fixture that misbehaves, or is not tested. Distilled's testing rules are different; read each repository's own.\n- **Live tests need a test account.** Ask the operator for a token to a workspace used only for tests, and where it is kept; never print it; get it before the pull request opens. Do not assume a deploy token you already have points at such a workspace. Their guidance has an account-wide teardown for leaked test resources. Run it only against that test workspace, and only with the operator's yes.\n- **A provider leaves alone what the stack did not declare or create.** Omitted props mean \"not managed\", not \"reset to a default\". A resource the provider finds but cannot prove it created is not owned until the user adopts it. Nothing a provider provides may change what other providers in the same stack see.\n- **Effect throughout**, in source, docs and examples alike, because examples teach users.\n- **One change per pull request, by each repository's own definition.** Distilled's is written and narrow: a spec fix and a runtime change are two. A correct fix of ours was lost there because it shared a pull request with a rejected feature, and a description that says it breaks a rule on purpose is read as exactly that. In Alchemy a resource with its bindings, tests and docs has been one change, and one piece of work opened as three pull requests was joined into one by its author soon after.\n- **Descriptions are short and say what the user can now do.** In both, the pattern they kept when rewriting ours was one plain sentence, then a code or diff block, a few bullets, and a marked breaking change. They cut status reports, test logs, file lists, long justifications and agent name lines. Use the format their current guidance and template give; the two repositories differ (in November 2026 Distilled had a template with a checklist and required a signed note on anything an agent wrote, while Alchemy forbade checklists, test sections and large headings), so do not carry one's format to the other. Have a reader with none of our context check the description against their conventions before it goes up.\n- **Names are theirs.** Name a resource after the platform's own product name. A name suggested as a question is a request: act on it or answer it in the next push.\n- **Their decision is the decision.** When a maintainer says they are solving it another way, ask how to fit into their design, then close ours with a line saying why, or redo it on theirs. Restating our case has not changed an outcome so far, and they have shipped their own version within hours. A real technical reason, stated once and plainly, has been accepted.\n\n## How their pull requests move\n\nPlan around what they do, not around what a pull request's state suggests.\n\n- **So far no maintainer has submitted an approving review on one of ours.** They comment, push commits to our branch, rewrite the description, and merge. Keep maintainer edits allowed.\n- **A draft is a signal, not a lock.** A maintainer has taken one of our drafts out of draft and merged it minutes later, at a commit we meant to add to. Every commit pushed to a branch that has a pull request must be safe to merge as it stands. If more is coming, it is in the pull request before it opens, or it is a separate change. Unfinished work lives on a fork branch that has no pull request; pushing there is yours to do.\n- **They read, run and fix drafts,** and do not chase. Good small changes have merged in under an hour; ones that needed work waited weeks with one comment or none.\n- **Keep it mergeable and green.** Merge their `main` when it conflicts. Take their side for every file our change does not own, then check the diff for files we never meant to touch; a merge of ours once silently deleted features from their `main`. Fetch before every push.\n\nSomeone has to know when a maintainer acts. Watch each open upstream pull request for comments, pushes, state changes, merges, failed checks and conflicts with their `main`, with whatever your harness offers. Write the watched pull requests into the project's plan, so a session that restarts finds them and sets the watch up again (background commands do not survive a restart). Tell the operator who did what, including when a merge happened with no review.\n\n## Speaking to the maintainers\n\nA maintainer here means someone who merges in that repository. Check who a commenter is before weighing what they say.\n\nOpening, editing, marking ready, commenting on or closing an upstream pull request speaks to another team in the operator's name. Those steps are the operator's, or need their explicit yes each time. Never turn on auto-merge or merge upstream.\n\n- Find out which GitHub account your shell acts as before planning these steps. Work out the whole sequence of operator steps once, in order, as commands that are safe to run twice and that say where to run them, and ask once.\n- After any GitHub write that reports an error, read the state back from GitHub before saying what happened.\n- When a maintainer asks or requests something, bring the operator the question and a finished draft answer in one message the same day, in the format their rules require for text an agent wrote. A question of ours that went unanswered got its pull request closed, and others waited a week or more. Where the request is a code change inside the agreed design, such as a rename, push it without waiting and say so in the draft. Do not post it yourself.\n\n## When the operator's request and this skill pull apart\n\nThe operator may ask for the very thing this skill warns against: finish it in the clone here, keep it to one pull request, make sure nothing else breaks, defend the option, add it to the SDK anyway. They may not have the earlier incidents in mind when they ask. Say once, briefly, what happened the last time and what you would do instead, and ask. Their answer decides anything on our side: where the work is done, how much we check, what we propose. It does not change the maintainers' rules or decisions. Where the request is something a maintainer has already refused, the next step is the operator raising it with them, not a pull request that tries it again.\n\n## After it merges\n\nA merged upstream pull request changes nothing in Composer until Alchemy releases and Composer's pins move. The `upgrade-alchemy-effect` skill covers the bump. Update the project's plan in the Composer pull request that consumes the release, and tell the platform's owners when a removal there was waiting on the provider.\n\n## Before asking the operator to open or mark ready an upstream pull request\n\n- The work was done in a session started in that repository, with its current guidance read in full in that session.\n- It touches only the Prisma package, or each file outside it copies an existing shape and is explained in the description.\n- The Distilled pin is at the exact commit our Distilled change merged as (or where a maintainer said to put it), in a commit of its own, and nothing points at a commit that exists only on our fork.\n- Alchemy: every behaviour is covered by a test that deployed for real, and you ran the ones your change touches. Distilled: each patch has its evidence.\n- It is one change by that repository's definition.\n- The description follows their current format, and a fresh reader has checked it against their conventions.\n- Nothing in it is unfinished, and every commit on the branch is safe to merge today.\n- The pull request is written into the project's plan, and a watch on it is in place.\n\n## What this skill does not cover\n\n- Moving Composer to a new Alchemy release or a preview build: `upgrade-alchemy-effect`.\n- How to write a provider, a patch or a test in their repositories: their own guidance and skills, loaded by working there.\n- Reviewing an outside contributor's pull request to our own repositories.\n- Design decisions inside Composer or the platform: each repository's design documents.\n","frontmatter":{"name":"upstream-alchemy-distilled","description":"How Prisma Composer, the Prisma Cloud target, Alchemy's Prisma provider (`@alchemy.run/prisma`), the Distilled Prisma SDK (`@distilled.cloud/prisma`) and the Prisma Management API (prisma/pdp-control-plane and its OpenAPI spec) depend on each other, and how to get a change through alchemy-run/alchemy or alchemy-run/distilled as an outside contributor without the maintainers rewriting or rejecting it. Use this whenever work will change or plans to change either upstream repository, how a `Prisma.*` Alchemy resource behaves or what it accepts (as opposed to how Composer uses it), the generated Prisma SDK, or a Management API behaviour that Composer's deploy depends on; whenever a Prisma pull request is open in either upstream repository; and to decide which repository a change belongs in before any code is written, even if the request only says \"the provider\", \"the SDK\", \"upstream\" or \"the Alchemy PR\". For moving Composer to a new Alchemy release, use `upgrade-alchemy-effect` instead."},"isInternal":false,"tokens":6389,"sizeBytes":29751},{"name":"SKILL.md","path":"skills/prisma-composer-core-concepts/SKILL.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills/prisma-composer-core-concepts/SKILL.md","title":"prisma-composer-core-concepts","category":"anthropic-skill","format":"markdown","content":"---\nname: prisma-composer-core-concepts\nmetadata:\n  library: \"@prisma/composer\"\n  library_version: \"0.41.2\"\n  version: 2026.9.1\ndescription: >-\n  Use when deploying or managing an app that uses Prisma Composer\n  (`@prisma/composer`): wiring its services and Modules, running it locally,\n  testing composed services, or standing up / tearing down an environment.\n  Triggers on \"prisma composer\", \"@prisma/composer\", \"prisma app\",\n  `prisma deploy`, `prisma dev`, `compute()`, `appRoot()`, `module()`, `contract()`,\n  `service.load()`, `mockService`, `bootstrapService`.\n---\n\n# Prisma Composer core concepts\n\nA **Prisma App** is a tree of typed declarations composed in TypeScript and\nhanded to the `prisma` CLI, whose two main Composer commands are `prisma deploy`\nand `prisma dev`. Removing a whole app is `prisma project delete`. Removing\none environment and reading logs are not commands; they are the `destroy` and `log`\noperations of `@prisma/composer/control`, called from a script.\nThis file covers structures, hierarchies, relationships, and workflows: the\nconcepts you cannot observe from the code or the CLI's help output. It is not\na CLI reference; discover each command's flags with `prisma <command> --help`\nrather than inferring them. The Prisma platform moves fast, so treat this file as the\nstable conceptual core and find current, fuller documentation at\n<https://www.prisma.io/docs>. For working code, read `examples/` in the\nprisma/composer repo.\n\nTwo principles govern everything and are binding\n(`docs/design/01-principles/`):\n\n1. **Your code never reads environment variables.** Dependencies, configuration,\n   credentials, and the port all arrive through the service node, typed.\n   `process.env` is never the answer.\n2. **Composer never bundles or transforms your code.** You build with your own\n   bundler; the framework assembles the built output by deterministic steps\n   and hands it to the configured deploy target.\n\n## Declarations are data\n\nEverything you author is a declaration: plain data describing a piece of the\napp, executing nothing when imported. Three node kinds exist:\n\n| Kind | Declared with | Purpose |\n| --- | --- | --- |\n| Service | `compute()` | A running unit of your code; atomic, Composer sees only its boundary |\n| Resource | `rawPostgres()`, `bucket()` | A stateful managed dependency |\n| Resource: public URL | `publicUrl()` | Makes one service reachable from the internet at one hostname; depends on the service's exposed HTTP interface and exposes nothing |\n| Module | `module()` | A grouping boundary; runs no code of its own, depends on and exposes typed interfaces; its builder receives `deps`, `input`, `environment` and `provision` |\n| App root | `appRoot()` | The outermost module, the entry's default export; no `deps` or `expose`, and nothing can provision it; its builder receives `input`, `environment` and `provision` |\n\nNodes connect through typed **interfaces**: `deps` declares what a node depends on, `expose` declares what it exposes. Wiring happens in a Module's builder via `provision()`, and the app root, built with `appRoot()` and handed to the CLI, is the App:\n\n```ts\n// module.ts\nimport { appRoot } from '@prisma/composer';\n\nexport default appRoot('store', ({ provision }) => {\n  const catalog = provision(catalogModule);\n  provision(storefrontService, { deps: { catalog: catalog.rpc } });\n});\n```\n\nBecause interfaces are typed, **the compiler verifies every wire**. A dependency wired to the wrong producer, a missing RPC handler, a literal input value of the wrong shape: all of it fails `tsc`, not the deploy. Values from outside the code are the exception: a root input field exists only at deploy, and a platform variable only on the platform, so a schema refinement the type does not carry and a missing platform variable a service needs surface as early deploy-time refusals instead (see Two channels below). Typecheck, then build, then deploy; don't use the cloud to find out whether the wiring is correct.\n\nComposer itself is target-agnostic: `@prisma/composer` carries authoring, testing, and the CLI, coupled to no platform. A deploy target is an extension registered in the deploy config; `@prisma/composer-prisma-cloud` is the Prisma Cloud target and the one this skill's deploy sections assume. Its root exports `compute`, `rawPostgres`, `bucket`, `publicUrl`, `variable`, `generatedParam` and `serviceOrigin`; the ORM vocabulary (`postgres`, `dataContract`) lives under the `/orm` subpath, alongside the shared `/cron`, `/storage`, `/streams`, `/auth`, and `/email` modules. These are the only two Composer packages a basic Prisma Cloud app needs, and nothing installs them for you: a fresh project starts with neither, so add both as dependencies first. An extension adds its own `prisma-composer-*` package alongside them. Compose an existing Module before implementing a capability yourself; wiring one in is a couple of lines.\n\nWithin the entry graph (everything reachable from `module.ts`), write\nrelative imports with explicit `.ts` extensions (`./service.ts`, with\n`allowImportingTsExtensions` in tsconfig): that form resolves everywhere.\n`prisma deploy` and `prisma dev` also map `./service.js` and extensionless\n`./service` to the `.ts` source, but other tools may not.\n\n## The service node is the only doorway\n\nYour runtime code receives everything from the service declaration it\nimports:\n\n1. `service.load()`: dependencies (typed RPC clients, database bindings).\n2. `service.input()`: the whole input as one schema-validated object;\n   credentials in it are redacting `SecretString` boxes.\n3. `service.port()`: the reserved port to bind (default 3000).\n\nA service declaration is pure data; the server entry is what your build\nproduces and the platform boots:\n\n```ts\n// service.ts\nexport default compute({\n  name: 'auth',\n  deps: { db: rawPostgres() },\n  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),\n  expose: { rpc: authContract },\n});\n\n// server.ts\nconst { db } = service.load(); // { url }: you construct your own client\nconst handler = serve(service, {\n  rpc: { verify: async ({ token }) => ({ ok: token.length > 0 }) },\n});\nBun.serve({ port: service.port(), hostname: '0.0.0.0', fetch: handler });\n```\n\nThe consumer declares `deps: { auth: rpc(authContract) }` and gets a typed\nclient back from `load()`.\n\n## Two channels: dependencies and input\n\n| The value is… | Declare | Provide | Read |\n| --- | --- | --- | --- |\n| produced by another node | `deps: { db: rawPostgres() }` | wire at `provision()` | `load()` |\n| anything else (config or credential) | one field of the `input` schema | bind at `provision()`: literal, root input field, platform variable node's value, or a `resolve()` value | `input()` |\n\nThe service declares its whole incoming configuration, plain values and credentials together, as **one [Standard Schema](https://standardschema.dev)** (arktype is the house choice). A credential is a field typed as `secretString()` from `@prisma/composer/arktype` (or `@prisma/composer/zod` for a Zod schema; the app installs `arktype` 2 or `zod` 4 itself, and Composer uses that copy); conditional legality (\"no stripe key unless billing is on\") is an ordinary schema union. The binding at `provision()` mirrors the schema's shape.\n\nA value you supply, rather than write in code, arrives in one of two ways:\n\n- **A value the deploy reads** is a **root input field**: a field of the app root's `input` schema, filled by the `config` adapters (by default the deploying shell), checked by the root's schema before anything is created. The root passes it on by name. Only these can be listed in `resolve()` or put in a resource's props.\n- **A value the service reads at boot** is a **platform variable node**, provisioned in the app root: `provision(variable({ name: 'EMAIL_FROM' }))` for a plain value, `provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }))` for a secret. `provision()` returns the value with `id`, the node's address, on it; pass it down through module inputs to the services that read it. The node names the variable and never carries its value; the operator sets the value on the platform.\n\n```ts\nexport default appRoot('shop', { input: type({ EMAIL_FROM: 'string' }) }, ({ input, provision }) => {\n  const stripeKey = provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }));\n  provision(billing, { input: { from: input.EMAIL_FROM, stripeKey } });\n});\n```\n\n**Only `appRoot()` can provision a platform variable node.** A variable's name is one space per deployed app, and the root is the app. In a `module()` body (a nested module or a `module()` root) `provision(variable(…))` fails to compile, with an error naming `appRoot()`. A module that needs the value declares a field in its `input`. The node creates nothing on the platform and stays out of the application topology and the deploy report; the loaded graph lists it and, in `graph.valueReads`, each service that reads it. Its default id is the name in camel case (`EMAIL_FROM` is `shop.emailFrom`); two nodes whose names give one id fail with an error naming both, so pass `{ id }`.\n\nRules that bite:\n\n1. **Secretness is checked by the binding's type and by the deploy.** A `provision()` binding, a service's or a module's, is typed from the schema: a literal or a `SecretBox` where the schema expects `SecretString`, or a platform secret's value in a text field, fails to compile, and the deploy refuses it where the schema has no types. An ArkType schema with a `SecretString` field cannot also transform its input: a morph anywhere in it (`'string.trim'`, `.pipe()`, `field(type('string.integer.parse'))`) or `'+': 'delete'` copies the input, the copied secret loses its value, and the deploy refuses it. Transform in the service code instead; a Zod schema keeps the box.\n2. **A plain platform variable's value is known only at boot: text, or the type its `schema` declares.** Bind it to a field wrapped with `field()`. A platform variable's value goes into a field of an `input` only. A compute service has one per-key param, the reserved `port`, which takes a literal or a root input field and no source, because the deploy needs the port before the service exists; every other value is a field of its `input`. A field of a narrower type, such as `email()`'s `deliveryMode`, takes a root input field declared with that type instead, for `email()` from the exported `emailDeliveryModes`; the deploy reads a root input field from the app configuration on every deploy and writes its value into the input document. A platform secret fits a `secretString()` field only. A platform variable's value always lives on the platform. The operator sets it there with `prisma project env add 'NAME=<value>' --project <id> --role production`. Use `--role preview` for every preview environment, or `--branch <environment>` for one. The deploy does not copy local values (`.env`, the shell) to platform variables. The deploy fails only when a variable that a service's schema requires has no value. The error names the variable and the command that sets it. The other variables with no value print under `Platform variables with no value:`. Prisma Cloud reports a service that exits at boot as running and promotes it; read the error with `prisma service logs <service>`.\n3. **The schema decides whether a field may be absent.** A field bound to a platform variable that is unset or empty is left out at boot. That is allowed only if the schema allows it, for example with an optional field or a union member. An optional root input field that the adapters do not supply is left out at deploy. The deploy report prints the serialized input document (each secret shown as `$platform VAR`) and every key that resolved absent. On Prisma Cloud the deploy writes the input document into the service's artifact, not into a `COMPOSER_*` variable, so it is not limited to a variable's 8 KB, and a changed document redeploys exactly that service.\n4. **The reserved `port` is outside the schema.** Read it through\n   `service.port()`, never `process.env`. The framework also exports `PORT`\n   for Next.js standalone, which binds it itself.\n5. **A Module passes a secret on without learning the platform name.** Declare a `secretString()` field in the Module's `input` and pass `input.<field>` on as a binding leaf; the app root provisions `variable.secret({ name: 'NAME' })` and binds its value. A module has no `params` or `secrets` slots: `module()` and `provision()` refuse both, naming `input`. A service's `params` stay.\n6. `input.apiKey.expose()` is the only way to a secret's value; the box\n   redacts everywhere else (logs, JSON, errors).\n7. **Platform variable names are upper case**: `^[A-Z][A-Z0-9_]*$`. `COMPOSER_…`, `DATABASE_URL`, `DATABASE_URL_POOLED`, `PORT`, `PATH` and `HOME` are reserved, each name is declared by one node, and one name cannot be both a platform variable and a root input field. A node's value bound as a service's whole input is refused too. Each fails before anything is created, naming the variable and the addresses.\n8. **A field bound to a plain platform variable, `serviceOrigin()` or a plain `generatedParam()` is wrapped**: `field(type('string'))`. At deploy the schema sees a pointer, and a plain `'string'` field refuses it: a compile error in a service's or a module's binding, and a deploy error where the schema has no types. `service.input()` and `mockService`'s input double read the field as its inner type.\n9. **A platform variable holds text; `schema` says what the text means.** `variable({ name: 'SMTP_PORT', schema: type('number') })` (any Standard JSON Schema library: ArkType, Zod) gives a runtime value of type `number`, which fits `field(type('number'))` and not `field(type('string'))`; without `schema` the value is the text and the reverse holds. An object schema fits a `field()` of the same object type. A schema that accepts only text gives the text exactly, untrimmed; any other schema reads the text as JSON (`587`, `true`, `{\"host\":\"h\"}`, `null` under `number | null`). A schema that accepts both, such as `string | number`, `z.unknown()` or `string | null`, is refused when the root body runs; for an optional text variable declare the text type and make the service's field optional. `variable.secret()` takes no schema.\n10. **Boot decodes and validates the text against the variable's JSON Schema, then the service's schema runs.** A failure fails boot, not the deploy: read it with `prisma service logs <service>`. Messages name the variable and never hold its text: `The platform variable \"SMTP_PORT\" does not hold a number. Its schema is not a text type, so its text must be JSON, such as 587.`, `... does not fit its schema: it fails \"minimum\" at #/minimum.` A whole number above 9007199254740991 is refused: keep an identifier as text. A value nested more than 100 levels deep is refused too. `prisma dev` runs the same check before any service starts and adds `prisma dev cannot start, because service \"<address>\" reads it.`\n11. **No library code runs on a variable's value; only the JSON Schema the library emits is checked.** A transform or a default the JSON Schema shows (`.transform()`, `string.numeric.parse`, a default inside an object) is refused at the root body; put defaults on the service's field. ArkType throws for `.narrow()` and `string.url`. Zod drops `.refine()`, and `.trim()`, `.toLowerCase()`, `z.coerce`, `z.preprocess()` and `.catch()` are accepted and do not run. An undeclared object key is not removed (`z.object()`, ArkType `'+': 'delete'`) and reaches the service's field. Regex flags are dropped and a pattern must be valid under the `u` flag (no `\\-` outside a character class). `format` is checked for `date`, `time`, `date-time`, `duration`, `uri`, `uri-reference`, `uri-template`, `url`, `email`, `hostname`, `ipv4`, `ipv6`, `regex`, `uuid` and the three JSON Pointer formats; others, such as `z.jwt()`, are unchecked. `z.number().optional()` does not fit `field(z.number())`: make the service's field optional. A hand-written schema that contradicts itself fails every boot. Put any other check or change in the service's own schema.\n\n### Values that differ per environment\n\nThe graph is the same in every environment; only configuration may differ.\n\n- A module declares `input` (one Standard Schema) as a service does; `provision(module, { input })` binds it, and the body receives `input`, a dictionary of values: it passes each field on by name into a binding or, for a plain field, lists it in `resolve()`. Passing the whole `input` on fails to compile, and the deploy refuses it. A root's `input` is the app configuration, and a module's `input` takes every source a service's does.\n- `field(inner)` from `@prisma/composer/arktype` or `@prisma/composer/zod` wraps one field's schema (`field(type('string'))`, `field(z.string())`) so it also accepts a plain pointer, which is what a value known only at boot such as `serviceOrigin()` is at deploy. In the body the field is `Value<string | Pointer<string>>`: pass it into another wrapped field or a service's input, never a plain `string` field (compile error). A wrapped field holds the whole value one source supplies, which may be an object or array when a platform variable's schema says so, so `field(type({ host: 'string' }))` is fine. An ArkType default goes outside: `field(type('string')).default('x')`. Other schema libraries: `Pointer`, `PlainPointer`, `isPlainPointer()` (narrows to `PlainPointer`) and `isSecretPointer()` from `@prisma/composer`. Wrap every field of a reusable module's schema other than a `secretString()` field, unless a `resolve()` lists it; keep a root's fields plain. `field(secretString())` is wrong: it accepts a plain pointer into a secret field, and the service fails at boot.\n- `composer({ config: [...], secrets: [...] })` lists config adapters; each gets the environment's name and returns values, later wins by top-level key. Both default to `[environmentVariables()]` (the shell); a list you write replaces the default. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local`, later wins. The app configuration fills the root's input (under `prisma dev` it also gives each plain platform variable a service reads its value, under the variable's name); pass the root's input fields on by name, as every module does; its whole `input` would be the whole app configuration, by default every shell variable. The app secrets give `prisma dev` its secrets; a deploy reads them only to redact. It does not fill a platform variable from them, and never reads them as the root's input. Both import from `@prisma/composer/config`. Credentials (`PRISMA_SERVICE_TOKEN`) still come from the shell. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local` through `dotenv-flow` (no `.env.local` for `test`); remove `import 'dotenv/config'` when you list it. Composer redacts the values under the names of the graph's platform secrets, in either list; the lists' other values are not secrets and print as they are, apart from values that look like credentials. Under `prisma deploy` the engine's output is redacted too; under `prisma dev` it is not yet.\n- A field exists only under a plain object: a path into a string, an array or a secret, such as `input.tags[0]`, fails the deploy naming the path.\n- A truthiness check such as `if (input.enabled)` is not caught: the field is an object, so the branch always runs, in every environment. A module's structure cannot depend on its input; to provision something only sometimes, let the parent decide whether to provision it.\n- The module body receives `environment`; `environment.name` is a value standing for the name `--environment` gave (`production` for `prisma deploy`, `dev` for `prisma dev` by default).\n- `resolve([deps], ([values]) => …)` from `@prisma/composer` returns a computed value; `fn` receives the dependencies' real values as one tuple.\n- A value is accepted as a leaf of a service's or a module's `input` binding, at any depth, as a service param (a deploy-time value only), as one of a `resource()` node's `props`, or as a public URL's `url`. Never as a provision id or a `deps` entry.\n- A value is opaque in the body: you cannot read, compare or branch on it. List it as a `resolve()` dependency instead.\n- Calling `provision()` inside `fn` fails the load: `fn` computes configuration, never graph structure.\n- `fn` is pure and synchronous and returns plain data (no `undefined`, Promise, value or source); a deploy and `destroy` both run it, in two processes. To retire an environment, keep its case in every `fn` until `destroy` for it has finished.\n- Sources are values. `resolve([input.X], ([x]) => …)` over a root input field receives its data. A dependency must be a deploy-time value: a platform variable's value, `generatedParam()`, `serviceOrigin()`, a field wrapped with `field()` and a `secretString()` field cannot be listed (a compile error saying so; for a field typed `unknown` or a cast, the deploy fails naming the field). Bind those directly; to compute with a field, declare it plain. For a different secret per environment, use one name with a different value on each environment.\n\n## Contracts and RPC\n\nAn RPC contract is the typed interface through which services communicate. It\nlives with the service that owns it, typed by any Standard Schema validator,\nand both provider (`serve()`, exhaustive over the contract's methods at\ncompile time) and consumer (`rpc(contract)`) reference the same value. Calls\ntravel as RPC over HTTP. Two behaviours are provisioned for you and must not\nbe reimplemented:\n\n1. **Service keys.** At deploy, Composer mints a distinct unguessable key per\n   consumer→provider binding; `serve()` returns `401` to anything else before\n   the handler runs. Nothing in your code declares it. Consequences: don't\n   build your own service-to-service auth, and don't `curl` a deployed\n   `/rpc/<method>` to check it works. An unwired caller always gets `401`,\n   which looks like a broken deploy and isn't. Debug through a consumer, or\n   locally, where nothing is enforced. Keys are per binding (one leaking\n   can't impersonate another consumer), service-scoped (any valid key\n   reaches every method; split services to gate separately), rotated only by\n   removing the binding or destroying the stack and redeploying, and stored\n   in deploy-owned `COMPOSER_*` variables you never hand-edit.\n2. **Idempotency and retries.** Every generated-client call carries an\n   `Idempotency-Key`; dropped calls retry with backoff, and `serve()` runs\n   one call per key, replaying the completed answer to late retries. Every\n   method is therefore safely retryable and no contract declares anything\n   about it (there is no \"is this idempotent\" flag; don't invent one). A\n   handler may take an optional third argument `(input, deps, ctx)` and read\n   `ctx.idempotencyKey` (`string | undefined`) if it needs exactly-once\n   beyond one instance's memory; most don't. Locally and in tests nothing is\n   provisioned, so `serve()` passes every call through: never supply a key\n   in test inputs.\n\n## Raw HTTP connections\n\nFor a server Composer does not generate (a reverse proxy's upstreams, a\nNext.js app, a static file server), import `rawHttp` and `rawHttpContract`\nfrom `@prisma/composer/http`. The provider declares\n`expose: { http: rawHttpContract }`; the caller declares\n`deps: { site: rawHttp() }`; the Module wires\n`provision(gateway, { deps: { site: siteRef.http } })`. `gateway.load().site`\nis `{ url, fetch(path, init) }`, where `fetch` resolves `path` against `url`.\nThe client never leaves its provider's origin by itself: `fetch` rejects a\npath that resolves to another host (`//other.example/x`, an absolute URL), and\nreturns redirects to the caller instead of following them, unless `init` sets\n`redirect: 'follow'`.\n\nComposer checks only that the provider declared an HTTP port: TypeScript and\nLoad reject a bare service ref or a port of another kind. The caller is\nresponsible for knowing the provider's paths, methods and headers. Raw HTTP\nhas no service key, retry or idempotency key; authentication, if needed, is\nthe app's. Each dependency shows in the application topology as a call, also\nthrough module boundaries; a URL passed as `input` (`serviceOrigin()`)\ndoes not, so declare a dependency for every service you call. The auth\nmodule's `api` port is a raw HTTP port: wire it with `rawHttp()`.\n\n**Public URLs.** A service is reachable from the internet only through a\npublic URL the app declares:\n`provision(publicUrl({ id: 'site', url, target: web.http }))`, where `id`\nsets the address (`shop.site`) and changing it replaces the URL, and where\n`web` exposes `http: rawHttpContract` (an RPC interface as `target` fails\n`tsc`; a module's forwarded HTTP interface lands on the service inside it).\n`url` is required and is one of two strategies: `publicUrl.prismaBuild()`\nserves at the service's `prisma.build` hostname and creates nothing;\n`publicUrl.hostname('shop.com')`, or the bare string `'shop.com'`, attaches\nthat hostname to the service as a custom domain. One hostname per public URL.\nA per-environment `url` is a `resolve()` value returning either strategy or a\nstring; anything else fails deploy and dev before any of the app's resources\nare created or changed. Before\na deploy names a hostname, the TXT record `_prisma-verification.<hostname>`\nand a CNAME to the platform must be published, or the deploy fails with the\nplatform's error (`domain-ownership-required` for the TXT record); don't\nwork around it, publish the records or use `publicUrl.prismaBuild()` there. A\nchange from a serving hostname to one that is not ready fails the deploy and\nthe old hostname keeps serving. `prisma dev` ignores a named hostname and\nwarns once per public URL that names a hostname. A service with no public URL is still reachable at\nits `prisma.build` hostname today.\n\n## Builds are yours\n\nYou build, the framework assembles. For a plain server process, `entry`\npoints at the ESM file your build produced. By default\n(`dependencies: 'bundled'`) deploy copies exactly that and never ships\n`node_modules`, so everything except runtime built-ins (`bun`, `bun:*`,\n`node:*`) must be inlined, or it fails at boot, not at deploy. Rules that\nbite:\n\n1. **Two services in one package means two separate builds**, one per entry.\n   A single multi-entry build splits shared code into a chunk neither output\n   contains.\n2. **A directory build uses `dir` + `entry`** (`dir` relative to the service\n   module, `entry` a file inside `dir`; `../` is an error). The tree is\n   copied verbatim, so the server must resolve siblings against\n   `import.meta.url`, not the working directory. The tree must contain no\n   symlinks: the packager rejects them, names the link, and assembly fails.\n3. **A build that leaves packages external sets `dependencies: 'external'`**\n   (either form). Deploy then traces `entry` and stages the installed\n   packages it imports, which can take minutes on a large build. Astro's Node\n   adapter, SvelteKit's `adapter-node` and React Router's server build leave\n   packages external by default. The default, `'bundled'`, copies exactly\n   what was built. A service that fails to start with\n   `Cannot find package 'x'` needs `x` bundled, or `dependencies: 'external'`.\n4. **Next.js**: `next build` with `output: 'standalone'` is the whole build;\n   `nextjs({ module, appDir })` names the app root. Any page or action that\n   calls `load()` needs `export const dynamic = 'force-dynamic'`, because\n   the runtime environment variables don't exist at build time and Next ignores\n   runtime env for prerendered routes. `prisma dev` needs no build for it: it\n   runs `next dev` instead (see Local development).\n5. **Always build before `deploy`, and before `dev` for a service without a\n   dev server.** Neither builds for you. `node({ ..., dev: ['bun', '--watch',\n   'server.ts'] })` gives a node service a dev server: `prisma dev` runs that\n   command (in the authoring module's directory, nothing appended; it must\n   listen on `PORT`) instead of the built `entry`.\n\nDeploy configuration is the `composer` section of `prisma.config.ts`, and\nnothing else. It names the entry module, the file whose default export is the\napp root (`entry`, relative to the config file; `--entry <path>` overrides it\nfor one run), and registers extensions (`prismaCloud()`, `nodeBuild()`,\n`nextjsBuild()` when the app has a Next.js service) and the deploy-state\nbackend (`prismaState()`):\n\n```ts\n// prisma.config.ts\nimport { defineConfig as composer } from '@prisma/composer/config';\nimport { nodeBuild } from '@prisma/composer/node/control';\nimport { prismaCloud, prismaState } from '@prisma/composer-prisma-cloud/control';\nimport { definePrismaConfig } from 'prisma/config';\n\nexport default definePrismaConfig({\n  composer: composer({\n    entry: './module.ts',\n    extensions: [prismaCloud(), nodeBuild()],\n    state: prismaState(),\n  }),\n});\n```\n\nThe commands find `prisma.config.ts` from the directory they run in, walking up\nto the repository root; the nearest file that declares `composer` wins, and its\nsection is used whole, never merged key by key. Only `entry`, `extensions` and `state`\nare allowed; any other key is an error. App code never imports the file.\n\nA separate `prisma-composer.config.ts` is no longer read, and the old setup is\nrefused, never silently ignored: `CONFIG.SECTION_MISSING` when no loaded\n`prisma.config.ts` declares a `composer` section, `CONFIG.FIELD_RETIRED` when\nthe section still has `configPath`, `CONFIG.FILE_RETIRED` when a\n`prisma-composer.config.*` sits next to the declaring `prisma.config.ts`; all\nthree under the CLI's `CLI.CONFIG_SECTION_INVALID`. `SECTION_MISSING` is fixed by\nadding the `composer` section to `prisma.config.ts`. `FIELD_RETIRED` and\n`FILE_RETIRED` are fixed by moving the old file's `extensions` and `state` into\nthe section, then removing `configPath` or deleting the old file.\n`@prisma/composer-cli/family` no longer exports `ComposerSection`; the\nsection's type is `PrismaAppConfig` from `@prisma/composer/config`.\n\n## Databases and migrations\n\nTwo kinds of Postgres dependency:\n\n1. **`rawPostgres()`**: the binding is `{ url }` and the app owns its client.\n2. **`postgres(...)`**: a Prisma-ORM-typed database. The binding is\n   `{ url, connection, client, clientWith }` (ADR-0040, ADR-0055): the raw\n   connection URL, the connection pool, the typed client Composer constructs\n   from your data contract lazily on first access, and `clientWith(options)`,\n   which builds a typed client with Prisma ORM runtime options. Queries go\n   through `binding.client` and are compile-time checked. Both `postgres` and `dataContract` import from\n   `@prisma/composer-prisma-cloud/orm`, not the package root. The app's\n   `package.json` lists `@prisma/orm-postgres` and the four ORM packages it\n   is built from (`@prisma/orm-framework`, `@prisma/orm-family-sql`,\n   `@prisma/orm-target-postgres`, `@prisma/orm-toolchain`), all at the exact\n   version Composer names, plus `pg`, `@types/pg` and `temporal-polyfill`; the ORM's packages are\n   peers of each other, so the app's list decides the one copy installed. One\n   `dataContract`-wrapped value (emitted from `contract.prisma` by\n   `prisma contract emit`) is referenced by both the dependency end\n   (`deps: { db: postgres(catalogData) }`) and the resource end, which also\n   names the `prisma.config.ts` path so the deploy's migration step can\n   reload the emitted `contract.json` and find `migrations/`, and the required\n   `targetRef`, the ref every deploy migrates the database to (below).\n   Client options never go on the dependency declaration. A contract that\n   uses an extension type (for example `pgvector.Vector(length: 1024)`)\n   needs the pack's runtime extension when the client is built:\n   `export const orm = db.clientWith({ extensions: [pgvectorRuntime] })`,\n   where `pgvectorRuntime` is the default export of\n   `@prisma/orm-extension-pgvector/runtime`; other runtime options, such as\n   `middleware`, go in the same object. Install the pack at exactly the\n   `@prisma/orm-postgres` version: the pack names the ORM's packages as\n   peers at its own version, so with a mismatch npm refuses the install and\n   pnpm, Yarn and Bun only warn, and the client rejects the extension's\n   values. Composer never looks extensions up itself;\n   with `binding.client` instead, the first access throws\n   \"Contract requires extension pack(s) 'pgvector'\".\n\n**Every deploy and every `prisma dev` converge runs the ORM's migrate** for each ORM database: the equivalent of `prisma db migrate --to <targetRef>` against the database Composer provisioned, whether or not anything changed. The ORM decides what is pending; with nothing pending it applies nothing and no service is redeployed. A deploy only migrates: it never runs `db update`, `db init` or `db sign`, and never creates schema from the contract.\n\n`targetRef` is required on the resource end. It takes a ref name (a committed `migrations/app/refs/<name>.json`) or `@contract`, the contract this commit emits. An app that deploys to environments computes it from the environment name:\n\n```ts\npostgres({\n  name: 'database',\n  contract: catalogData,\n  config: './prisma.config.ts',\n  targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n});\n```\n\n`@empty`, `@db`, a contract hash or a migration directory name is refused. A Module that provisions its own ORM database targets `'@contract'`: its migrations ship inside its package, so the app cannot commit refs for it, and a Module that copies the app's `resolve([environment.name], …)` pattern makes the app's first `production` deploy fail with the ORM's `MIGRATION.UNKNOWN_REF`. The `prisma.config.ts` names no database (no `db.connection`); the deploy passes the ORM the one it provisioned. Per-PR environments need one ref rule for all of them (such as a shared `preview` ref, or `'@contract'`); an environment with no ref file fails with the ORM's `MIGRATION.UNKNOWN_REF`.\n\nThe loop for every schema change, including a new database's first schema:\n\n1. Edit `contract.prisma`.\n2. `prisma contract emit` regenerates `contract.json` + `contract.d.ts`.\n3. `prisma migration plan --name <slug>` authors the migration (on an empty graph this authors the baseline).\n4. `prisma migration ref set <environment> <newest migration directory>` for each environment the change should reach.\n5. Commit `migrations/`, then deploy. A fresh database replays the whole path from empty.\n\nUnder `prisma dev`, plan a migration for each contract change: a local database moved with `prisma db update` to a contract no migration ends at is refused on every rebuild with the ORM's `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, although it is at the target, until a migration ending at that contract exists. This is a current Prisma ORM bug. Plan a migration that ends at the contract; do not reset the database or edit its contract signature to get past it.\n\nA deploy moves the database to its ref, not to the code: a ref may trail the contract on purpose, and moving it is the user's job in the pull request that changes the contract. Every service that uses the database deploys only after its migration completes: a failed migration means the new code does not ship. The old code serves against the new schema until the new deployment is live, so keep each migration compatible with the code it replaces.\n\nA failed migration fails the deploy with one Composer line, `<address>: Composer ran prisma db migrate --to <targetRef> on this database.`, and the ORM's own structured error under it: code, summary, `why`, next actions and docs link. Follow the ORM's advice; Composer adds none. Its advised commands repeat `--to <targetRef>`. Composer raises its own errors only before the ORM runs: the emitted contract `prisma.config.ts` names is missing or unreadable, has no storage hash, or differs from the declared `dataContract(...)` value.\n\nWhen a ref declares policies that differ from the database's (a new database has the ORM's defaults), every deploy fails with the ORM's `MIGRATION.POLICY_MISMATCH` and changes nothing. A deploy never changes policies. Applying them is a decision for whoever administers the database, made by hand: `prisma db migrate --to <ref> --permit-policy-change --db <url>`, with the URL from the Prisma Console, from `prisma postgres connection create @<environment>:<address> --name <name> --json` (its output holds a secret shown once), or locally from `prisma dev url <address>` while `prisma dev` runs. A ref's policies are the `policies` field of its JSON file, edited by hand: the pinned Prisma ORM version has no command for them. Do not run that command, or edit a ref's policies, to get a deploy past the refusal: say what the ORM reported and leave the decision to whoever administers the database.\n\nUpgrading an app from before `targetRef` was required: add `targetRef` to each `postgres({ ... })`, commit a ref per deployed environment with `prisma migration ref set <environment> <newest migration directory>`, and remove placeholder `db.connection` entries from `prisma.config.ts`. See `examples/orm-demo` for an app and `examples/store/modules/catalog` for a Module.\n\n## Deploy model: converge, don't script\n\nDeploy compares the declared topology against recorded deploy state and\napplies only the difference. Re-deploying with nothing changed is a no-op;\nremoving a node removes its deployed resource. `prisma deploy` needs a signed-in\nidentity: `prisma auth login` stores a session on a developer machine, and\n`PRISMA_SERVICE_TOKEN` overrides it in CI. The `/control` operations, and so\na destroy script, never use that session: `deploy` and `destroy` read\n`PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` from environment variables (both\nin the workspace's Console settings); `dev` and `log` read neither. The\n`prisma` bin starts under Node; use `pnpm prisma …` or `npx prisma …` by\ndefault. Composer starts Alchemy with Node, but Alchemy's launcher moves to\nBun under `bunx` or `bun run`: `bunx prisma` gives Node then Bun,\n`bunx --bun prisma` Bun then Bun. When the modules `module.ts` imports use\nBun APIs, `bun node_modules/prisma/dist/prisma.js deploy` from a\nshell runs `prisma` under Bun with Alchemy on Node.\n\nA node's **address** is the app name followed by the provision ids down to it\n(`shop.auth.api`); the root's address is the app name, or `--name` when given.\nEvery surface uses this full form: `serviceOrigin('shop.api')`,\n`prisma dev url shop.api`, the `log` operation's `address`, errors and reports.\nServices, managed Postgres databases and buckets record their address as\n`logicalId` on their Branch. Console uses that address to match topology nodes\nto resources and compare them with main. Existing environments receive the\nidentity on their next deploy. A deploy interrupted after creating a resource\nresumes on the next deploy, which finds the resource by its address. Local dev\ncreates no platform rows. Changing a node's address (its name without an\nexplicit `id`, its `id`, or its module) makes a new entity: the next deploy\ndeletes the old rows, and a database's or bucket's data with them.\n\n**Progress.** `prisma deploy` prints each step as it starts and finishes, with its duration (`✔ assemble web (3m 42s)`), and ends with the real total (`Deployed <app> to <environment> in 5m 25s.`). Steps: load config and app, one assemble per service, connect to project and branch, check environment variables, plan and apply (one step: alchemy does both in one process), record result. A slow assemble is usually a Node service with `dependencies: 'external'`, whose runtime dependencies are being traced. With `--json`, each step is a `step-started`/`step-finished` line whose `data` holds `durationMs` plus whatever the build adapter or deploy target reported; those extra fields vary, so don't parse them as a stable format. The `deploy` operation's `onEvent` receives the same steps, its result's `durationMs` is the total, and its `summary.findings` lists the platform variables with no value.\n\n**Environments.** An environment is a named place the app runs, chosen with\n`--environment` at deploy time, never written in the topology. The identical\ngraph deploys everywhere. `prisma deploy` without the flag deploys\n`production`; `prisma dev` runs as `dev` and takes no flag. On the Prisma Cloud\ntarget, a Prisma App is one Project and an environment is a Branch of it, with\nits own running services, its own empty database, its own configuration:\n`production` is the Project's default Branch, any other name is the Branch\nwith that `gitName`, created if absent. The default Branch's own name (such as\n`main`) is refused, since it would be production under a second name. A name\nmust be a valid git ref name, or the deploy fails with\n`DEPLOY.ENVIRONMENT_INVALID`.\n\n**Seeing what is deployed.** `prisma deploy list [--environment <name>]` lists every\nnode of the topology the last deploy recorded, with its kind, platform ID and,\nfor a service, its URL; the root's ID is the Project's, and a module has none.\nIt finds the app as `deploy` does (`--name`, `--entry`) and fails with\n`DEPLOY.TARGET_NOT_FOUND` when the environment has nothing deployed. Piped:\naddress, kind, platform ID, URL per line; `--json`: `[{ address, kind, platformId, url }]`. It needs\na `prisma` CLI release that includes it; 8.0.0-rc.26 does not.\n\n**Using an address with platform commands.** A `prisma project|service|postgres|bucket`\ncommand takes `@<environment>:<address>` in place of the platform ID\n(`prisma service logs @pr-42:shop.api`); no environment means production. It\nacts on that one row. Deleting a service, database or bucket this way leaves\nthe deploy state alone, so the next deploy recreates it; deleting the Project\nremoves its deploy state too. It needs a `prisma` CLI release newer than\n8.0.0-rc.28.\n\n**Removing an app** with every environment is a platform command: find the Project\nid with `prisma project list`, then `prisma project delete <id> --confirm <id>`,\nand check `prisma project list` again to confirm it is gone. It works while the\napp's services are running. Don't write a script for this.\n\n**Destroying one environment** is the `destroy` operation, and its\n`environment` is required, even for production; it has no default and a call\nwithout it fails with `DEPLOY.ENVIRONMENT_REQUIRED`:\n\n```ts\nawait destroy({ entry: 'module.ts', environment: 'pr-42', config });\nawait destroy({ entry: 'module.ts', environment: 'production', config });\n```\n\nDestroying any environment other than production\ndeletes its Branch after removing its resources. Destroying production\nremoves only the resources inside the production Branch, never the Branch\nitself directly; once the Project is empty it is deleted too, and that\ndeletion takes the production Branch with it. A Project still holding\nanother environment's resources is kept. Destroy never creates anything:\ndestroying a\nnever-deployed environment fails rather than standing one up.\n\n**Upgrading from stages.** `--stage <name>` is now `--environment <name>`;\n`destroy({ target })` is now `destroy({ environment })`, with production as\n`'production'`; the `--report` file's `stage` field is now `environment`, at\n`version` 2. Keep `@prisma/composer-prisma-cloud` on the same Composer version\nas the Composer that runs the deploy. An older extension would read every\nenvironment as production, so deploy and destroy refuse it with\n`DEPS.EXTENSION_INCOMPATIBLE`.\n\n**The engine underneath is alchemy.** Convergence is executed by [alchemy](https://alchemy.run), a third-party infrastructure-as-code engine that arrives as an ordinary, exactly-pinned npm dependency of `@prisma/composer` (2.0.0-beta.87 at this library version). Your code never imports or configures it; consult alchemy's own docs for the engine itself. What matters operationally:\n\n`prisma deploy` runs alchemy inside the `prisma` process through alchemy's programmatic API: no generated file and no child process. Its progress prints as one step per resource, and a failure is `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, with credentials redacted, or `DEPLOY.INTERRUPTED` after Ctrl-C, which releases the environment's lease. `prisma dev` runs alchemy in the `prisma` process too, each converge in a new worker thread, so an edit to your app definition applies on the next rebuild. Three kinds of edit need `prisma dev` restarted, and it says so: adding or removing a node, making the root pass on an input field it did not pass on at start, and changing which platform variables the app reads. The `destroy` operation runs alchemy inside the process that calls it, the same way as deploy. The alchemy that runs is the one installed beside the app's `@prisma/composer`, so the app needs no direct `alchemy` dependency, and no global Alchemy installation is needed.\n\n1. No command writes a stack file or starts the alchemy CLI. An engine failure surfaces as `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, credentials redacted, for deploy and destroy alike. A structured error, such as the ORM's, keeps its code, `why`, next actions, docs link and the structured error it was caused by: they print in the CLI's error layout, and its next actions stay `{ kind, label, command?, … }` objects, and are data in `failure.meta.reasons`, in the `--report` file's `failure.reasons` and on `prisma dev`'s `converge-failed` events. Only the copy sent to the Prisma Cloud build is shortened, to 5000 characters, by cutting the middle of the longest `why`.\n2. Destroy runs the same preparation as deploy, assembly included, so **an app must be built before it can be torn down**.\n3. alchemy is why the `effect` pin exists: it resolves the `effect`\n   constellation, and a hoisted newer `effect` halts every command (failure\n   mode 1 below).\n\n**The deploy report** ends with the app's own topology: authored names, the\nplatform resource each became, and public URLs. Read ids out of it rather\nthan hunting in the Console. A URL appears only where the address is\ngenuinely public: a service prints one, a database never does, and a\nnode whose product is secret material reports no resource line at all.\n\n**Connection contract refusals.** A connection declares the values it needs\nby name; a producer that omits one fails the deploy, naming the edge, the\nparam, and what the producer did supply:\n\n```text\nConnection input \"auth.db\" declares param \"url\", but its producer \"db\" did not\nsupply it — the producer's outputs carry [host].\n```\n\nThis is a deploy-time refusal, not a broken deploy, and it can appear on an\napp whose code didn't change (the gap used to pass silently as `undefined`\nand crash the consumer at boot). Fix whichever end is wrong; don't mark the\nparam `optional` unless absent really is legal. Only reachable if you\nauthored the connection or an extension on one side.\n\n**Driving deploys from code.** A script imports only\n`@prisma/composer/control`; the extensions' `/control` entries are imported\nonly by `prisma.config.ts` (ADR-0017). `@prisma/composer/control` exposes typed\n`deploy`, `destroy`, `dev`, `devUrl`, `devStop`, and `log` returning structured\nresults; `prisma deploy`, `prisma dev`, `prisma dev url` and `prisma dev stop`\nrender `deploy`, `dev`, `devUrl` and `devStop`. Each takes\na required `config: { value, file }` (`ComposerConfigSource`): the `composer`\nexport of your `prisma.config.ts` and that file's path; a relative `file`\nresolves against `cwd`, so build it from `import.meta.url`. The operations\nnever look for a config file, but refuse what the CLI refuses before any work\nstarts (`CONFIG.FIELD_UNKNOWN` for the whole export instead of its `composer`\nproperty, `CONFIG.FILE_RETIRED`, `CONFIG.FILE_MISSING`); the deploy re-imports\n`file`, so `value` must be its `composer` export. Failures come back as\n`{ ok: false, failure }` with a dotted `failure.code` from a closed registry\n(e.g. `ASSEMBLE.BUILD_FAILED`, `DEPLOY.ENGINE_FAILED`,\n`DEPS.EXECUTOR_UNLOADABLE`); branch on the code, not the message. A\nnon-structured rejection out of an operation is a bug in composer, not an\nexpected failure.\n\n## Local development\n\n`prisma dev` runs the whole app on this machine, wired as it deploys,\nagainst local emulators. No cloud credentials are needed or read. Concepts\nthat surprise:\n\n1. It runs the same pipeline as deploy, so **build first**, exactly like\n   deploy, except for a service that runs a dev server (below). It watches\n   built output and restarts a service when its build changes.\n   **Dev servers.** A service whose build adapter declares one runs it in\n   place of its artifact, with no flag: every `nextjs()` service runs\n   `next dev` (the app's own `next`, resolved from `appDir`), and a `node()`\n   service runs its `dev` argv when it has one. It runs on the service's\n   instance and URL, with the deployment's environment variables: `service.load()`,\n   `service.input()` and `service.port()` work exactly as deployed, so never add a\n   `process.env` fallback for plain `next dev`. It also keeps the shell's\n   environment variables; Composer's values win. `dev` prints ``<address>: runs\n   `<command>` in <dir>`` before the app comes up and streams the dev\n   server's output prefixed `[<address>]` (other services' logs are not\n   streamed). Source edits are the dev server's own hot reload; `dev` watches\n   the entry and every app file it imports, applies an edit to them on the\n   next rebuild (adding or removing a node, passing on a new root input field, or changing which platform variables the app reads needs `dev` restarted, and it says so), and restarts a dev server only when its environment variables changed\n   (``<address>: its environment changed; `<command>` restarted``). It has no\n   terminal (no colours or key shortcuts). The standalone build is not run\n   locally, so a standalone-only\n\n<!-- [TRUNCATED AT 50KB] -->","frontmatter":{"name":"prisma-composer-core-concepts","metadata":{"library":"@prisma/composer","library_version":"0.41.2","version":"2026.9.1"},"description":"Use when deploying or managing an app that uses Prisma Composer (`@prisma/composer`): wiring its services and Modules, running it locally, testing composed services, or standing up / tearing down an environment. Triggers on \"prisma composer\", \"@prisma/composer\", \"prisma app\", `prisma deploy`, `prisma dev`, `compute()`, `appRoot()`, `module()`, `contract()`, `service.load()`, `mockService`, `bootstrapService`."},"isInternal":false,"tokens":12105,"sizeBytes":50054},{"name":"README.md","path":"skills/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/skills/README.md","title":"Skills Skill","category":"anthropic-skill","format":"markdown","content":"# Prisma Composer skills\n\nAgent skills for [Prisma Composer](https://github.com/prisma/composer) — one\n`SKILL.md` that teaches an LLM agent how to write, test, and deploy a Prisma\nApp without re-deriving the API from documentation each time.\n\n## What's in the box\n\nOne skill, `prisma-composer-core-concepts`, covering the whole story: the mental model\n(Modules, `compute()`, `service.load()`), RPC contracts, databases, reusable\nmodules (cron/storage/streams), config params, secrets, testing\n(`mockService`/`bootstrapService`), deploying (`prisma deploy`,\nenvironments, removing an app or an environment), and the production pitfalls. Composer's surface is small\nenough for one skill; there is no router or per-topic cluster.\n\n## Install\n\nThe skill ships inside the `@prisma/composer` tarball, so installing the\npackage is what brings it in. `prisma skills sync` (from the `prisma` CLI)\ncopies it out of `node_modules` into the skill directories the agent runtimes\nread — `.claude/skills/`, `.cursor/skills/`, `.agents/skills/`,\n`.windsurf/skills/`:\n\n```bash\npnpm add @prisma/composer\npnpm add -D prisma\npnpm prisma skills sync\n```\n\nAdd it to your project's `postinstall` so an upgrade brings the matching skill\nwith it:\n\n```jsonc\n// package.json\n\"scripts\": {\n  \"postinstall\": \"prisma skills sync || exit 0\"\n}\n```\n\nIn a monorepo (a pnpm, npm or Yarn workspace), put the hook in the `package.json` at the workspace root (the directory with `pnpm-workspace.yaml`, or the `package.json` that lists `workspaces`), not in a workspace package's: hooks in several packages run at the same time and can leave the skill copy at the root missing a file. The root's sync installs the skills of every workspace package. List `prisma` there as a dev dependency, at the version your packages use, so the root's hook can find the command. If `prisma` warns with `SKILLS.MEMBER_LEFTOVER`, a workspace package still has something an earlier `prisma` put there: move the hook to the root, and delete the other files the warning names, such as old skill copies.\n\nThe version you read is then always the version you installed: the skill's\nfrontmatter carries `metadata.library: \"@prisma/composer\"` and a\n`metadata.library_version` stamped by the release that built the tarball\n([`scripts/set-version.ts`](../scripts/set-version.ts);\n[`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs)\nproves it against the packed artifact).\n\n### Without installing the package\n\nThe GitHub source stays available for anyone who wants the skill without\n`@prisma/composer` in their project:\n\n```bash\nnpx skills add prisma/composer\n```\n\nThe [`skills` CLI](https://npmjs.com/package/skills) installs it at the\nproject level for the agent runtimes it detects (`-a <agent>` to pick one).\nNothing keeps this copy in step with your packages, so pick the git ref\nmatching your `@prisma/composer` version by hand and re-do it on every\nupgrade.\n\n## Authoring rules\n\nThe skill is the agent-condensed mirror of the human guides in\n[`docs/guides/`](../docs/guides/) — the guides are canonical for humans; a\nsurface change lands in both. For anyone editing the skill:\n\n- **Verify every claim while drafting, not in a final pass.** Every import\n  must resolve against a `packages/9-public/*` export map, and every CLI\n  flag/command against `packages/0-framework/3-tooling/cli/`. If ripgrep finds\n  nothing, the surface doesn't ship — name it under *What Composer doesn't do\n  yet* instead of extrapolating.\n- **The skill must be self-contained.** It gets installed into other repos, so\n  no link may resolve outside `skills/prisma-composer-core-concepts/`. Repo\n  docs may be\n  named in prose (\"`docs/design/10-domains/testing.md` in the prisma/composer\n  repo\"), never linked relatively.\n- **Teach concepts, not procedures.** Name the moving parts and the command\n  that reveals each piece of state; reserve numbered steps for one-safe-path\n  operations.\n- **Leave the `metadata` stamp alone.** `metadata.library` names the npm\n  package the skill ships inside, and `metadata.library_version` is rewritten\n  by [`scripts/set-version.ts`](../scripts/set-version.ts) on every release —\n  hand-editing the version, or dropping either key, breaks the release script\n  and [`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs).\n  They live under `metadata` because the Agent Skills spec defines the\n  top-level keys and reserves that map (string → string) for publisher\n  extensions. A new skill needs both keys, with any placeholder version.\n- **Folder name and frontmatter `name` must match** — the runtimes key on the\n  frontmatter, humans on the folder.\n\nMaintainer-facing skills (release process, commit conventions) live in\n[`../skills-contrib/`](../skills-contrib/), not here.\n","isInternal":false,"tokens":1172,"sizeBytes":4789},{"name":"domain-modeler.md","path":".claude/agents/domain-modeler.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/.claude/agents/domain-modeler.md","title":"domain-modeler","category":"subagent-persona","format":"markdown","content":"---\nname: domain-modeler\ndescription: Research and write DDD-style domain models for external systems (e.g. Cloudflare/Wrangler) as structured docs under docs/design/04-inspirations/.\ntools: Read, Write, Bash, WebFetch\ncolor: blue\nmodel: inherit\n---\n\nYou are a domain modeling and domain research specialist.\n\nYour job is to take a target system (product + tooling) and produce a **DDD-style written domain description**: ubiquitous language, core concepts, relationships, user workflows, and behavioral/execution flows — written as a small library of docs that can be reused in later design discussions.\n\nThis agent is designed to be “set loose”: you do the research, make reasonable modeling calls, and leave behind a coherent, cross-linked documentation set.\n\n## Core responsibilities\n\n1. **Capture ubiquitous language**\n   - Build a glossary of the system’s key terms as *users* use them (and note internal/mechanical terms separately).\n   - Prefer the product’s native vocabulary over invented terms; call out synonyms and overloaded words.\n\n2. **Model the domain (things + relationships + behaviors)**\n   - Produce a conceptual domain map (relationships between the core concepts).\n   - Enumerate the primary operations (“verbs”) on those concepts.\n   - Document behavioral relationships: what triggers what, what depends on what, what must be true.\n\n3. **Model the user mental model + UX workflows**\n   - Document the user’s day-to-day mental model.\n   - Capture the common workflows (happy paths + sharp edges) as step-by-step flows.\n\n4. **Separate stable research from evolving takeaways**\n   - Keep “how the system works” relatively stable in research docs.\n   - Keep “what Prisma Composer should do because of it” in a separate takeaways doc that can evolve.\n\n5. **Be explicit about uncertainty**\n   - Track open questions and assumptions at the end of each doc.\n   - When unsure, write the best current model and clearly label it as an assumption.\n\n## Workflow (every time)\n\n### Step 0: Anchor on the repo’s doc system (read-first)\n\nRead:\n- `docs/design/README.md`\n- `docs/design/99-process/README.md`\n- `docs/design/04-inspirations/README.md`\n- Any existing inspiration docs for the target system (if present)\n\nGoal: match the house style and keep outputs discoverable and consistent.\n\n### Step 1: Define scope + output location\n\nDecide:\n- The **target system name** (e.g. “Cloudflare”, “Cloudflare Wrangler”, “Cloudflare Workers + Wrangler”).\n- What is in-scope vs out-of-scope (product surfaces, runtime primitives, billing/account, etc.).\n\nCreate (or update) a research library folder:\n- `docs/design/04-inspirations/<System>/`\n\nIf a single-file inspiration note already exists (e.g. `docs/design/04-inspirations/cloudflare.md`), treat it as a short overview and keep the detailed model in the folder.\n\n### Step 2: Research (prefer primary sources)\n\nUse official docs and product references first (then reputable secondary sources).\n\nWhile researching, continuously extract:\n- **Nouns** (things): resources, identifiers, configuration objects, runtimes, projects, accounts.\n- **Verbs** (operations): create/update/deploy/bind/route/observe/debug/rollback.\n- **Rules** (invariants): what must always hold; what configurations are invalid; what is “the unit of deployment”.\n- **Workflows** (UX): “day 1” setup, deploy, local dev, preview/staging, rollout, rollback, debugging.\n- **Control-plane vs runtime split** (if applicable): author-time/build-time/deploy-time vs runtime execution.\n\n### Step 3: Write the DDD artifacts (structured library)\n\nProduce this set of files (mirrors the `TanStack/` pattern):\n\n- `README.md`\n  - what this library covers, what to read, key sources\n- `glossary.md`\n  - terms + definitions; note “user-facing?”; include synonyms/aliases\n- `domain-map.md`\n  - a conceptual relationship map (use Mermaid where useful)\n- `operations.md`\n  - the primary operations on core concepts (CRUD + lifecycle + operational verbs)\n- `user-domain.md`\n  - the user mental model and how it maps to underlying mechanics\n- `execution-flows.md`\n  - the “always happening” flows (deploy lifecycle, routing, local dev loops, etc.)\n- `takeaways-for-prisma-composer.md`\n  - explicitly evolving: what Prisma Composer should emulate/adapt, plus design questions raised\n\nWriting guidelines:\n- Prefer **small, scannable** docs over one huge one.\n- Keep each doc focused; cross-link instead of duplicating.\n- Include **1–2 diagrams** when they materially improve comprehension.\n- Keep a short **Open questions / assumptions** section at the bottom of each file.\n\n### Step 4: Integrate with the inspiration index\n\nUpdate `docs/design/04-inspirations/README.md` to list the new folder (or new key docs) so the library is discoverable.\n\n### Step 5: Finish with a “what changed” summary\n\nWhen done, summarize:\n- Files created/updated\n- Key domain concepts discovered (5–10 bullets)\n- The most important workflows (3–5 bullets)\n- Open questions / unknowns (explicit list)\n\n## Output expectations\n\nWhen asked to “model Cloudflare + Wrangler”, a successful output usually includes:\n\n- A new folder: `docs/design/04-inspirations/Cloudflare/` (or similarly named)\n- The standard library docs listed above, cross-linked and consistent\n- A takeaways doc that cleanly separates “research facts” from “Prisma Composer implications”\n\n## Guardrails\n\n- Do **not** change Prisma Composer’s core domain docs (`docs/design/03-domain-model/`, `docs/design/10-domains/`) unless the user explicitly asks you to translate research into Prisma Composer design changes.\n- Do **not** create ADRs unless the user explicitly indicates a decision has been made.\n- Prefer documenting what you can verify; label inferred models as assumptions.\n","frontmatter":{"name":"domain-modeler","description":"Research and write DDD-style domain models for external systems (e.g. Cloudflare/Wrangler) as structured docs under docs/design/04-inspirations/.","tools":"Read, Write, Bash, WebFetch","color":"blue","model":"inherit"},"isInternal":false,"tokens":1296,"sizeBytes":5805},{"name":"README.md","path":"packages/1-prisma-cloud/2-shared-modules/auth/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/packages/1-prisma-cloud/2-shared-modules/auth/README.md","title":"auth Documentation","category":"plugin-manifest","format":"markdown","content":"# @internal/auth\n\nSignup, login, sessions, and JWT verification as a composed module wrapping\n[Better Auth](https://better-auth.com) (in-process TypeScript library — not a\nremote IdP), published as `@prisma/composer-prisma-cloud/auth`. One dedicated\nCompute service; the schema ships as a Prisma ORM extension pack; the\ninstance secret is platform-minted.\n\n## Contract scope\n\nThree ports, one service behind them — least privilege is a WIRING choice:\n\n- **`api`** (a raw HTTP port, `rawHttpContract` from `@prisma/composer/http`)\n  — the public Better Auth surface\n  (`/api/auth/*`): signup, login, logout, self-service account deletion,\n  JWKS, token minting. Publicly reachable, with no service key (unlike the\n  rpc ports) — it IS the authentication: Better Auth authenticates each\n  request itself (logout and account deletion need a signed-in session)\n  and rate limits it. Two consumer dependencies bind to it:\n  - `rawHttp()` from `@prisma/composer/http` → `{ url, fetch }` — what\n    `authProxy()` consumes. Any raw HTTP slot accepts this port, so a test\n    double or another auth server can fill the same slot.\n  - `jwtVerifier()` → `verify(token)` — stateless JWT verification over the\n    instance's JWKS (jose remote JWKS, 30 s clock tolerance). Resolves\n    `null` for ANY invalid token content; throws only on operational\n    errors (JWKS unreachable). No DB access — that is its whole value.\n- **`session`** (rpc) — consumer-facing online checks: `getSession(token)`\n  (null for unknown/expired/banned-owner — one shape, no error; a revoked\n  session is a deleted row, so this is the instant-logout read) and\n  `getUser(id)` (profile rendering off a JWT `sub` without admin wiring).\n- **`admin`** (rpc) — the tier-1 admin path: `findUser` (exactly one of\n  id/email; email match case-insensitive), `listUsers` (query/banned\n  filters, keyset cursor), `listSessions`, `revokeSession`,\n  `revokeUserSessions` (idempotent deletes), `banUser` (ban implies\n  revoke, atomically), `unbanUser`, `createUser` (see Provisioning\n  accounts below), `setEmailVerified`, `removeUser` (see Deleting\n  accounts below).\n\nWire each port only where it belongs: the app gets `api` + `session`; the\nback office alone gets `admin`.\n\n`/api/auth/*` is the browser surface. Better Auth origin-checks any request\nthat looks like it came from a browser — one carrying a cookie, an\n`Origin`/`Referer`, or any `Sec-Fetch-*` header — and refuses a missing\n`Origin` with `403 MISSING_OR_NULL_ORIGIN`. Node's built-in `fetch` sends\n`Sec-Fetch-Mode` on every request, so a Node script calling `/api/auth/*`\n(directly or through `authProxy`) is refused unless it sends an `Origin`\nthat is in `trustedOrigins` (the module's `baseUrl`). Server-to-server work\nbelongs on the rpc ports instead.\n\n## Golden-path wiring\n\n```ts\n// module.ts (the root)\nimport { appRoot, resolve } from '@prisma/composer';\nimport { serviceOrigin } from '@prisma/composer-prisma-cloud';\nimport { auth } from '@prisma/composer-prisma-cloud/auth';\nimport { postgres } from '@prisma/composer-prisma-cloud/orm';\nimport { appContract } from './src/contract.ts';\nimport apiService from './src/api/service.ts';\n\nexport default appRoot('app', ({ environment, provision }) => {\n  const db = provision(\n    postgres({\n      name: 'database',\n      contract: appContract,\n      config: './prisma.config.ts',\n      targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n    }),\n    { id: 'database' },\n  );\n  const identity = provision(auth(), {\n    id: 'auth',\n    deps: { db },\n    input: { baseUrl: serviceOrigin('app.api') }, // the PUBLIC app origin\n  });\n  provision(apiService, {\n    id: 'api',\n    deps: { authApi: identity.api, verifier: identity.api, session: identity.session },\n  });\n});\n```\n\nEvery deploy migrates the database to its `targetRef`. Here `prisma dev` migrates to the contract the commit emits, and a deploy to the environment `production` migrates to the ref `migrations/app/refs/production.json`, which you commit after planning a migration: `prisma migration ref set production <newest migration directory>`.\n\n```ts\n// src/api/service.ts: the app service declares its three dependencies\nimport { rawHttp } from '@prisma/composer/http';\nimport { rpc } from '@prisma/composer/service-rpc';\nimport { authSessionContract, jwtVerifier } from '@prisma/composer-prisma-cloud/auth';\n\nexport default compute({\n  name: 'api',\n  deps: { authApi: rawHttp(), verifier: jwtVerifier(), session: rpc(authSessionContract) },\n  build: node({ module: import.meta.url, entry: 'server.js' }),\n});\n```\n\n```ts\n// in the app service: first-party cookies via the proxy (the browser golden path)\nimport { authProxy } from '@prisma/composer-prisma-cloud/auth';\n\nconst { authApi, verifier } = service.load();\nconst proxy = authProxy(authApi);\n// route /api/auth/* → proxy(request); verify API calls with verifier.verify(<bearer>)\n```\n\nThe database is a BOUNDARY dependency: the root decides dedicated vs shared. `baseUrl` is the public origin browsers see (scheme+host, no trailing slash, no path) — bind it with `serviceOrigin('<app>.<service>')`, the service's full address, so each environment trusts its own URL, or a field of the root's input, such as `input.AUTH_BASE_URL`, for a custom domain. The instance secret is platform-minted inside the module; rotation is unsupported in v1 (rotating would invalidate every session and the encrypted jwks rows).\n\nA complete, deployable copy of this wiring lives in `examples/auth`.\n\n## Provisioning accounts\n\nAn account an operator creates goes through the `admin` port, server to\nserver — never through the browser sign-up surface:\n\n```ts\n// in a service wired to `identity.admin`\nconst { admin } = service.load();\nconst { user } = await admin.createUser({\n  email: 'ops@example.com',\n  name: 'Ops',\n  password: 'a-long-passphrase',   // optional; omit for a magic-link-only account\n  emailVerified: true,             // optional; default false\n});\n```\n\n`createUser` writes exactly what Better Auth's own sign-up writes — the\n`user` row and, with a password, a `credential` account hashed by Better\nAuth's own hasher — and sends no mail. The contract input applies the same\nchecks sign-up does (a well-formed email, a password of 8–128 characters),\nso a caller mistake is a 400 at the rpc boundary; a duplicate email\n(case-insensitive) is refused by the handler. Every refusal reaches a typed\nrpc client as a thrown error, so a script cannot mistake it for success. `setEmailVerified({ userId, emailVerified })` flips\nthe flag a created account needs before `requireEmailVerification` lets it\nsign in (`user: null` for an unknown id).\n\nA deployed stack's rpc ports are reachable only by consumers in its graph:\na script on a laptop cannot call `admin.createUser`. The application\nexposes its own operator route (allowlisted however it sees fit) from a\nservice wired to `admin`, and that route makes the call.\n\nInvite-only applications close self-service sign-up with a module setting,\nenforced by Better Auth itself, instead of filtering their proxy:\n\n```ts\nprovision(auth({ signUp: 'closed' }), { id: 'auth', deps: { db, email: mail.send }, input: { baseUrl: … } });\n```\n\n`signUp: 'closed'` sets `emailAndPassword.disableSignUp` and the magic-link\nplugin's `disableSignUp`: `/api/auth/sign-up/email` answers `400\nEMAIL_PASSWORD_SIGN_UP_DISABLED`, and a magic link requested for an unknown\nemail is still sent but completes to an `error=new_user_signup_disabled`\nredirect with no user created. Sign-in for existing accounts is unchanged.\nDefault `'open'`. Nothing about origin, CSRF, or `trustedOrigins` changes\neither way.\n\n## Deleting accounts\n\nA signed-in user deletes their own account through Better Auth's\n`POST /api/auth/delete-user`, reached through `authProxy()` like the rest\nof `/api/auth/*`:\n\n```ts\n// browser, signed in (cookie through the proxy)\nawait fetch('/api/auth/delete-user', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json' },\n  body: JSON.stringify({ password }), // optional when the session is < 24 h old\n});\n```\n\nIt needs a signed-in session (`401` otherwise), deletes only that\nsession's user (there is no `userId` parameter), and demands the current\n`password` (`400 INVALID_PASSWORD`) or a session younger than 24 hours\n(`400 SESSION_EXPIRED` — sign in again; magic-link users have no password).\n\nAn operator deletes an account through the `admin` port, server to server\n— this module's database-direct rpc, not Better Auth's admin-session API:\n\n```ts\n// in a service wired to `identity.admin`\nconst { removed } = await admin.removeUser({ userId });\n```\n\n`removed: false` means no such user, so a retried deletion is not an\nerror. No mail is sent.\n\nBoth paths delete the `user` row, its sessions, and its accounts. Pending\nverification tokens are left to expire: an unused magic link (the email,\n5 minutes) or reset (the user id, 1 hour); Better Auth deletes expired\ntokens the next time it checks any token. Your own rows follow your foreign\nkey onto `auth:User`: `onDelete: Cascade` deletes them with the user,\n`Restrict` refuses the deletion, and without an FK nothing links them.\nData outside the database (uploaded files, other stores) needs your own\ncleanup first — route that deletion through your service and\n`removeUser`. Already-minted JWTs keep verifying until they expire\n(≤ 15 min, see Sessions & JWTs); `session.getSession(token)` is `null`\nimmediately.\n\n## The pack\n\nBetter Auth's tables (`user`, `session`, `account`, `verification`, `jwks` —\nPostgres schema `auth`) ship as a Prisma ORM extension pack with authored\nmigrations — Better Auth's own migrator never runs anywhere. Consumers:\n\n```ts\n// prisma.config.ts\nimport authPack from '@prisma/composer-prisma-cloud/auth/pack';\nexport default defineConfig({ ..., extensions: [authPack] });\n```\n\nRun `prisma migration plan` once — it materialises the pack's shipped\nmigrations into `migrations/auth/` — and deploy: the ONE migration step\ncreates and evolves the auth tables beside your own, marker-signed per\nspace. On a shared database your own contract can FK `auth:User`\n(cross-space relations are non-navigable in the generated client; the value\nis the real constraint):\n\n```prisma\nmodel Profile {\n  id     String @id\n  userId String @unique\n  user   auth:User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n```\n\nUpgrade procedure: bump this package → `prisma migration plan` (the new\nshipped migrations materialise) → deploy. The deploy preflight fails loudly\nwhen a wired database's config is missing the pack or is at a stale head.\nA version whose section below says otherwise needs those steps instead.\n\n### Upgrading to a required `targetRef`\n\nThe app's database now needs `targetRef`, and every deploy runs the ORM's migrate to it, for the auth pack's contract space as for the app's. Add `targetRef` to the app's `postgres({ ... })` as shown above, commit a ref per environment you deploy with `prisma migration ref set <environment> <newest migration directory>` (run where the app's `prisma.config.ts` is), and remove any placeholder `db: { connection: … }` from that `prisma.config.ts`. The auth pack's own space always migrates to its shipped head.\n\n### Upgrading to Prisma ORM 8.0.0-rc.26\n\nPrisma ORM 8.0.0-rc.26 computes every contract hash in a new way, so the auth pack's storage hash moves from `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d` to `cb2e6cac77e993f93581b354f39af672267ae9c5888a156e68c00bb9087f769e`. The tables do not change. Follow [Upgrading to Prisma ORM's new contract hashes](../../../../docs/guides/deploying.md#upgrading-to-prisma-orms-new-contract-hashes): its script rewrites your copy of the auth pack's migrations in `migrations/auth/` with your own, and `prisma db sign` signs the auth pack's space with your app's.\n\nA database that only `startLocalAuthServer` uses, such as one your tests create, has no project to run `prisma db sign` from. Point the server at a fresh database instead: on a database it set up under an earlier version, it now stops with the ORM's `CONTRACT.PRISMA_SPACE_BEHIND` and changes nothing.\n\n### Upgrading to Composer 0.34.0\n\nComposer 0.34.0 moves to Prisma ORM 8.0.0-rc.20. The auth pack's contract no longer stores its `Tstz` type alias: each column stores its own type. The tables do not change, but the auth pack's storage hash does, from `0df0ef0989ec3dd95124dde6303fbe0572bbab08bebf00abff6a7955cadd786e` to `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d`. Your app keeps its own copy of the auth pack's migrations (`migrations/auth/` and the snapshot in `migrations/snapshots/0df0ef…/`), and Prisma ORM rc.20 refuses to load that snapshot as it is. Every database's marker also still holds the old hash. Until you follow these steps, `prisma deploy` and `prisma dev` fail at the migration step: first with `Contract-space contract validation failed for \"auth\"`, and after the script in step 3 with an error that the database is at a contract no migration of contract space `\"auth\"` reaches.\n\n1. Commit your work, so the changes below can be reviewed and undone with git.\n2. Upgrade `@prisma/composer`, `@prisma/composer-cli` and `@prisma/composer-prisma-cloud` to 0.34.0, `@prisma/orm-postgres` to 8.0.0-rc.20, and `prisma` to 8.0.0-rc.26 or later. An earlier `prisma` cannot read an rc.20 contract, so `contract emit` and `db sign` fail with `Cannot use 'in' operator to search for 'kind' in typeAlias`.\n3. From the app's root, copy the Prisma skills into the project and run the ORM's type-alias script. Node does not run a TypeScript file from inside `node_modules`, which is why the script runs from the copy:\n\n   ```sh\n   prisma skills sync\n   node .agents/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts\n   ```\n\n   It renames `migrations/snapshots/0df0ef…/` to `migrations/snapshots/24a0762…/` and rewrites `migrations/auth/0001_init/migration.json` and `migrations/auth/refs/head.json`. It prints `0df0ef… -> 24a0762…`.\n4. Run `prisma contract emit`. For an app whose own contract has no type aliases, this only moves the version stamps in `contract.json` and `contract.d.ts`.\n5. Run `prisma db sign --db <url>` against every database of the app: production, each other environment and the local dev database. The database does not change; only its marker moves to the new hash. It prints `auth: signed 24a0762… (was 0df0ef…)`.\n   - **Deployed environments.** A deploy never prints a connection string. Copy each database's connection string from the Prisma Console: the app's Project for production, and the Branch named after the environment for any other environment.\n   - **The local dev database.** It must be running: `prisma db sign --db \"$(prisma dev url database)\"`, where `database` is your auth database's node address. A `prisma dev` that fails stops the app, and `prisma dev url` reports only a running database, so sign before you run `prisma dev` on the new version. A `prisma dev --detach` started before the upgrade keeps the database running. If the database is already stopped, start over with `prisma dev --fresh`, which deletes the local data.\n6. Deploy and run `prisma dev` as usual.\n\nThe script also gives the rewritten `0001_init` migration a new hash, and each database's migration history keeps the old one. So `prisma migration status` no longer shows the auth pack's earlier migrations as applied, although it still reports the database as up to date. `prisma db migrate` does not run them again.\n\n## Sessions & JWTs\n\nStateless JWTs by default: 15-minute TTL, EdDSA via the instance's JWKS at\n`/api/auth/jwks`. Verified claims: `sub` (userId), `sid` (sessionId),\n`email`, `emailVerified`, `exp`. Cookie sessions last 7 days (rolling,\nrefreshed daily).\n\nThe trade-off is explicit: a revoked/banned session's already-minted JWTs\nkeep verifying until they expire (≤ 15 min). A route that needs instant\nlogout opts in per call with `session.getSession(token)` — a revoked\nsession is a deleted row. `iss`/`aud` are not validated in v1: the verifier\nonly trusts keys fetched from the wired instance, and instances never share\nkeys.\n\n## Local dev\n\n```ts\nimport { startLocalAuthServer } from '@prisma/composer-prisma-cloud/auth/testing';\n\nconst server = await startLocalAuthServer({ databaseUrl }); // e.g. `prisma dev`\n// server.url            → real Better Auth + the real port handlers\n// server.capturedEmails → { template, to, url } per send — read your\n//                          verification / magic links straight from here\n```\n\nReal Better Auth, the real handlers, the same fetch topology as production; the pack's schema applies idempotently at boot; a fixed dev secret; rpc runs keyless. No cloud credentials anywhere.\n\nThe helper applies the schema with the Prisma ORM your app installs (`@prisma/orm-postgres`, a required peer, and `@prisma/orm-toolchain`, which Composer depends on). It carries no copy of its own.\n\n## Email flows\n\nVerification, password reset, and magic-link emails deliver through the\n[email module](../email/README.md), wired as a boundary dependency:\n\n```ts\nconst mail = provision(email(), { id: 'mail', input: { /* deliveryMode, from, deliveryCredential */ } });\nconst identity = provision(auth(), {\n  id: 'auth',\n  deps: { db, email: mail.send },\n  input: { baseUrl: serviceOrigin('shop.web') },\n});\n```\n\nSignup requires verification (`requireEmailVerification: true`; the\nverification send fires on signup, and verifying auto-signs-in; an\n`admin.createUser` account skips the mail and is verified when created\nwith `emailVerified: true`). Magic links expire after 5 minutes. The three templates ship with the module —\nminimal semantic HTML plus a plain-text part; every interpolation is\nHTML-escaped, and a link whose origin differs from `baseUrl` fails the\nsend rather than going out.\n\nDelivery is fire-and-forget from auth's perspective: a failed send is\nlogged, never thrown (a down mail path must not brick signup), and each\nsend carries a deterministic idempotency key, so Better Auth retries\ncan't double-deliver. The email module's outbox is the operational\nrecord — read delivery state back through its `outbox` port.\n\nLocally, `startLocalAuthServer` captures sends in `capturedEmails` by\ndefault, or accepts an `email` sender hydrated against the email module's\nown local server so the outbox-readback path is the one production uses.\n`examples/auth` runs the full loop both ways: signup → verification link\nread back from the outbox → verify → login → magic link.\n\n## Embedded mode\n\nArrives with slice S4: `createEmbeddedAuth()` (`./embedded`) — the same\n`buildAuthOptions()` mounted in your own service, for the fully-in-process\nshape.\n\n## The SPA alternative\n\nDocumented fully in S2 alongside the browser flows: talk to the `api` port's\norigin directly with `Authorization: Bearer` (the bearer plugin is enabled),\nat the cost of the first-party-cookie golden path.\n\n## Limits (v1)\n\nNo social providers (mechanism reserved, none ship) · no organizations /\n2FA / passkeys / username / phone · no secret rotation · no impersonation · admin web UI is tier 2+ (the `admin` port is tier 1) ·\nrpc bodies cap at 1 MiB.\n","isInternal":false,"tokens":4845,"sizeBytes":19349},{"name":"README.md","path":"packages/1-prisma-cloud/2-shared-modules/email/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/packages/1-prisma-cloud/2-shared-modules/email/README.md","title":"email Documentation","category":"plugin-manifest","format":"markdown","content":"# `@prisma/composer-prisma-cloud/email`\n\nTransactional email as a Prisma Composer module. It is an ordinary module: a\nCompute service backed by a module-provisioned Prisma Postgres (every email is\nstored first, then delivery is attempted — the outbox), exposing two\nindependent ports: `send` (deliver a rendered email) and `outbox` (query every\nemail the module has handled). Templates are declared and rendered\n**consumer-side**; the wire carries only rendered mail.\n\nShips as the `@prisma/composer-prisma-cloud/email` subpath (like `/storage`\nand `/cron`).\n\n## Contract scope\n\nTwo ports, three ops:\n\n| Port | Op | Notes |\n| --- | --- | --- |\n| `send` | `send` | `{ templateId, to, cc?, bcc?, replyTo?, subject, html, text?, idempotencyKey }` → `{ id, status, error? }`. `to` 1–50 entries; `idempotencyKey` 1–256 chars. |\n| `outbox` | `getEmail` | `{ id }` → `{ email }` (`null` for an unknown id — never an error). |\n| `outbox` | `listEmails` | Optional `to`/`templateId`/`status`/`cursor`/`limit` filters (AND-combined; `to` matches any recipient) → `{ emails, nextCursor? }`, newest-first, keyset-paginated. `limit` 1–200, default 50. |\n\n`status` is one of `stored` (mode `none`), `queued` (real modes, transient),\n`sent`, `failed`. `send` never throws for a delivery failure — failure is\ndata (`status: 'failed'`, `error` set); it throws only for transport,\nvalidation, or database errors.\n\n`from` is not part of `send`'s input — the sender address is module config\n(one per module instance); a template cannot override it.\n\n## Envelope\n\n**No attachments** in v1. service-rpc request/response bodies cap at **1\nMiB**, so a rendered email (subject + html + text) must fit inside that.\n**Retention: none** — every sent email's full body is stored, unredacted,\nforever (no expiry, no deletion, no redaction). Do not put anything in a\ntemplate you would not want to live in the database indefinitely.\n\n## Wiring\n\nProvision `email()` in a module and declare template-typed dependencies on\nits two ports:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { email, emailDeliveryModes } from '@prisma/composer-prisma-cloud/email';\nimport { variable } from '@prisma/composer-prisma-cloud';\nimport { type } from 'arktype';\n\nexport default appRoot(\n  'app',\n  {\n    input: type({\n      EMAIL_DELIVERY_MODE: type.enumerated(...emailDeliveryModes),\n      EMAIL_FROM: 'string',\n    }),\n  },\n  ({ input, provision }) => {\n    const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));\n    const mail = provision(email(), {\n      id: 'email',\n      input: {\n        deliveryMode: input.EMAIL_DELIVERY_MODE,\n        from: input.EMAIL_FROM,\n        deliveryCredential,\n      },\n    });\n    provision(appService, { deps: { email: mail.send } });\n    provision(adminService, { deps: { outbox: mail.outbox } });\n  },\n);\n```\n\n```ts\n// consumer service — templates declare the client's shape. Interpolated\n// values are HTML-escaped before going into markup — `render` runs on\n// whatever data the caller supplies, so treat it as untrusted the same way\n// you would any other template.\nimport { defineTemplates, emailSender } from '@prisma/composer-prisma-cloud/email';\nimport { type } from 'arktype';\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#39;');\n}\n\nconst templates = defineTemplates({\n  verification: {\n    data: type({ link: 'string' }),\n    render: ({ link }) => ({\n      subject: 'Verify your email',\n      html: `<p><a href=\"${escapeHtml(link)}\">Verify</a></p>`,\n      text: `Verify: ${link}`,\n    }),\n  },\n});\n\nexport default compute({ deps: { email: emailSender(templates) }, /* … */ });\n```\n\n```ts\n// consumer server\nconst { email } = service.load();\nawait email.verification({ to: user.email, data: { link } });\n```\n\nThe outbox port needs no custom factory — declare `deps: { outbox:\nrpc(emailOutboxContract) }` and get the generated client directly.\n\n## Using react-email\n\n`render` may be synchronous or async — the sender method awaits either.\nThis module neither depends on nor imports react-email; a template's\n`render` just calls react-email's own `render()` and returns its result:\n\n```tsx\n// emails/welcome.tsx — a plain react-email component\nimport { Body, Container, Html, Text } from '@react-email/components';\n\nexport function WelcomeEmail({ name }: { name: string }) {\n  return (\n    <Html lang=\"en\">\n      <Body>\n        <Container>\n          <Text>Welcome, {name}!</Text>\n        </Container>\n      </Body>\n    </Html>\n  );\n}\n```\n\n```tsx\n// templates.tsx\nimport { render } from '@react-email/render';\nimport { WelcomeEmail } from './emails/welcome.tsx';\n\nconst templates = defineTemplates({\n  welcome: {\n    data: type({ name: 'string' }),\n    render: async ({ name }) => ({\n      subject: `Welcome, ${name}!`,\n      html: await render(<WelcomeEmail name={name} />),\n      text: await render(<WelcomeEmail name={name} />, { plainText: true }),\n    }),\n  },\n});\n```\n\nJSX interpolation (`{name}` above) escapes automatically — React escapes\ntext children by construction, so a react-email template needs no manual\n`escapeHtml` the way a plain-function template does. See\n[`examples/email`](../../../../examples/email)'s `welcome` template for\nthe full worked version, alongside `verification` as a plain function —\nboth authoring styles side by side.\n\nOne deploy caveat: `prisma deploy` loads your module graph with\nNode's own loader, which cannot transform JSX — a `.tsx` file imported by\nyour topology fails with `Unknown file extension \".tsx\"`. Precompile the\ntemplates file in your app's own build and import the compiled output, as\n[`examples/email/scripts/build.ts`](../../../../examples/email/scripts/build.ts)\ndoes (see the matching `gotchas.md` entry).\n\n## Values per environment\n\n`deliveryMode`, `from` and `deliveryCredential` are the module's `input`. `deliveryMode` is `resend`, `smtp` or `none`, exported as `emailDeliveryModes` (and the type `EmailDeliveryMode`): bind it to one of those literals, or to a field of your root's input declared from `emailDeliveryModes`, as above, so the root's schema checks it before anything is created. With Zod, declare the field as `z.enum(emailDeliveryModes)`. A plain platform variable may hold any text, so binding its value to `deliveryMode` fails to compile. Bind `from` to a literal, a field of your root's input or the value of a `variable(...)` node, so it can vary per environment. `deliveryCredential` is a `secretString()` field: bind it to the value of a `variable.secret(...)` node the app root provisions. `deliveryMode` and `from` are wrapped fields (`field()`), so a module that passes its own wrapped field of the same type on can bind them too. `deliveryUrl` is a factory option (`email({ deliveryUrl })`), static per app: it defaults to `https://api.resend.com` and follows the mode.\n\nIn the sample above, `EMAIL_DELIVERY_MODE` and `EMAIL_FROM` are root input fields: set them in the shell that runs the deploy. `EMAIL_DELIVERY_CREDENTIAL` is a platform secret: set it on the platform with `prisma project env add`.\n\n| Name | Where it is set | Production | Preview |\n| --- | --- | --- | --- |\n| `EMAIL_DELIVERY_MODE` | the deploy shell | `resend` (or `smtp`) | `none` |\n| `EMAIL_FROM` | the deploy shell | `noreply@myapp.com` | anything (unused when `none`) |\n| `EMAIL_DELIVERY_CREDENTIAL` | the platform | Resend API key / SMTP password | any non-empty value, which preflight requires even though the service never reads it |\n\nPreview needs a credential because the email service's input schema requires it in every mode, so an environment that never delivers still sets a non-empty value. A schema can make a secret field optional (ADR-0042); this one does not. `gotchas.md` records this.\n\n## Delivery policy\n\nShared by both real backings (`resend`, `smtp`):\n\n- Per-attempt timeout: **10 s**.\n- Up to **3 attempts** (1 initial + 2 retries), delayed **500 ms then\n  2000 ms** between them (no jitter).\n- Retryable: thrown/network errors, HTTP 429, HTTP 5xx (Resend); SMTP\n  connection errors and response codes 421/450/451/452.\n- Not retryable (fails immediately): any other Resend 4xx (including 409\n  idempotency conflicts — those should be unreachable given the outbox's\n  own row-level dedup; if one surfaces, it is not masked); any other SMTP\n  response code, including permanent 5xx rejections.\n- The outbox row's `attempts` accumulates the count each delivery\n  invocation actually made (1–3 under the policy above) — a future\n  redelivery from the outbox adds its own tries to the running total.\n- Stored `error` string: `` resend <status> <name>: <message> `` (Resend,\n  parsed from its error body; falls back to the raw response text if\n  unparseable) or `` smtp <responseCode>: <message> `` (SMTP protocol\n  rejection). A connection-level failure (no response code) stores the raw\n  error message with no prefix, for either backing.\n\n**SMTP: \"accepted\" is not \"delivered\".** `status: 'sent'` for an SMTP send\nmeans the relay accepted the message for submission — nothing more. SMTP\ngives no delivery confirmation; `providerMessageId` is nodemailer's\n`info.messageId` (or `null`).\n\n**SMTP: a timeout retry can duplicate a send.** The per-attempt timeout\nonly stops the module from waiting on a slow relay — it does not cancel\nthe in-flight SMTP transaction. If the timeout fires, the shared policy\nretries; a slow relay can still accept the first attempt's message after\nthe retry has already started, delivering the same email twice. This is a\ndeliberate retry-semantics tradeoff (at-least-once, not exactly-once) and\nstays as pinned — the only fix that removes the possibility is not\nretrying on timeout, which would trade a rare duplicate for a more common\nfalse failure on a merely slow relay.\n\n## Idempotency\n\n`idempotencyKey` is required on every `send` call and must be **unique per\nlogical send**. A repeated key returns the original row — status, id, and\nall — with no new delivery attempt, even if the payload differs. This is a\ndurable, row-level guarantee (a unique constraint on `idempotency_key`),\nindependent of and stronger than service-rpc's own in-memory replay cache.\n\n`emailSender`'s per-template methods make `idempotencyKey` optional: omit\nit and a fresh UUID is minted on every call, so that call gets no dedup\nprotection against its own retries. If your own retry logic re-invokes a\nsend method after a transient failure, capture the key from the first\nattempt and pass it explicitly on the retry — the module does not\nremember it for you.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/email/testing` boots the same handler map\nover an in-memory store, `deliveryMode: 'none'`, loopback only, no auth —\nno cloud credentials, no Postgres:\n\n```ts\nimport { startLocalEmailServer } from '@prisma/composer-prisma-cloud/email/testing';\n\nconst server = await startLocalEmailServer(); // ephemeral port by default\n// server.url — point emailSender()/rpc(emailOutboxContract) clients at it.\nawait server.stop();\n```\n\n[`examples/email`](../../../../examples/email) is the worked example: a\n`mailer` app wired to `email()`, tested locally against this stand-in with\nno cloud credentials, and deployed to Prisma Cloud in `none` mode as the\nsmoke test.\n\nTests that exercise the real Resend/SMTP backings point `deliveryUrl` at a\nlocal fake instead of the real provider — a `Bun.serve` fake HTTP endpoint\nfor Resend, a minimal loopback SMTP responder for SMTP (see\n`delivery-resend.test.ts`/`delivery-smtp.test.ts`).\n\n## Manual resend check (not run in CI)\n\nA one-off, by-hand verification that a real send actually delivers — not\npart of the test suite or the deploy smoke, since it needs a real Resend\naccount:\n\n1. Set the environment's `EMAIL_DELIVERY_MODE` to `resend`, `EMAIL_FROM` to an\n   address on a domain verified with Resend, and `EMAIL_DELIVERY_CREDENTIAL`\n   to a real Resend API key.\n2. Send one template to a real inbox you control.\n3. Confirm the message arrives, and that the outbox row for it reads\n   `status: 'sent'` with a non-null `providerMessageId`.\n\n## Non-goals (v1)\n\nAttachments, cc/bcc size limits beyond the contract's, per-send `from`\noverride, batch/scheduled send, Resend webhooks, delivery-status polling,\nopen/click tracking, queue-backed async delivery (the outbox is the seam\nfor a later relay — no contract change needed), retention/redaction/\ndeletion, and an admin UI. react-email is not a dependency of this module\n— see \"Using react-email\" above for how a consumer wires it in.\n","isInternal":false,"tokens":3185,"sizeBytes":12724},{"name":"README.md","path":"packages/1-prisma-cloud/2-shared-modules/storage/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/packages/1-prisma-cloud/2-shared-modules/storage/README.md","title":"storage Documentation","category":"plugin-manifest","format":"markdown","content":"# `@prisma/composer-prisma-cloud/storage`\n\nS3-compatible object storage as a Prisma Composer module. It is an ordinary\nmodule: a Compute service that speaks the **S3 wire protocol**, backed by a\nmodule-provisioned Prisma Postgres (objects live in a single `bytea` column),\nwith SigV4 credentials minted at deploy. Consumers wire the module's `store`\nport into an `s3()` slot and get an `S3Config` binding; they build their own\nS3 client (aws-sdk, or a hand-rolled SigV4 client) from it.\n\nShips as the `@prisma/composer-prisma-cloud/storage` subpath (like `/cron`).\n\n## Contract scope\n\nThe contract **is** the S3 wire protocol — but only the subset a real consumer\nneeds, not S3-compatibility maximalism. In scope:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /{bucket}/{key}` | `content-type` optional; returns a quoted SHA-256 ETag (opaque to consumers) |\n| `GET /{bucket}/{key}` | optional `Range: bytes=a-b` (inclusive end; open end `a-`) → `206`; missing → `404` |\n| `HEAD /{bucket}/{key}` | `etag` + `content-length`; missing → `404` |\n| `DELETE /{bucket}/{key}` | idempotent (a missing key is success) |\n| `GET /{bucket}?list-type=2` | `prefix`, `continuation-token`, `max-keys` (default 1000); ListObjectsV2 XML |\n| Presigned GET/PUT | query-param SigV4, expiry enforced |\n\nAuth is SigV4 (`AWS4-HMAC-SHA256`), **path-style addressing only**, any region\nstring (`auto` is fine). Bucket names simply namespace keys — there is no\nbucket CRUD.\n\n**Out of scope**: multipart upload, `CopyObject`, batch `DeleteObjects`,\nconditional requests, flexible checksums / `aws-chunked` framing (rejected with\n`501` — see the wiring note below), bucket CRUD, ACLs, versioning, lifecycle.\n\nSee [`CONTRACT-SCOPE.md`](./CONTRACT-SCOPE.md) for the full op semantics and the\nexact out-of-scope list.\n\n## Envelope\n\nObjects up to **~16 MiB**. Each object is one row's `bytea` value; ranged reads\nuse SQL `substring(...)` so a range request never loads the whole object. This\nis comfortably within Postgres `bytea`/TOAST for the target workload — it is\n**not** a general-purpose large-blob store, and larger objects are unsupported.\n\n## Wiring\n\nProvision `storage()` in a module and wire its `store` port into a consumer's\n`s3()` slot:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport blobs from './src/blobs/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage()); // owns its Postgres + minted credentials\n  provision(blobs, { deps: { store: store.store } });\n});\n```\n\n```ts\n// src/blobs/service.ts — the consumer declares an s3() dependency\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { s3 } from '@prisma/composer-prisma-cloud/storage';\n\nexport default compute({\n  name: 'blobs',\n  deps: { store: s3() },\n  build: node({ module: import.meta.url, entry: '../../dist/blobs/server.mjs' }),\n});\n```\n\n```ts\n// src/blobs/server.ts — the consumer's entry builds its own client (ADR-0015)\nimport { S3Client } from '@aws-sdk/client-s3';\nimport service from './service.ts';\n\nconst { store } = service.load(); // S3Config: { url, bucket, accessKeyId, secretAccessKey }\n\nconst client = new S3Client({\n  region: 'auto',\n  endpoint: store.url, // path-style; no virtual-host addressing\n  forcePathStyle: true,\n  credentials: { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey },\n  // The store rejects aws-chunked / flexible-checksum PUTs with 501 — send plain\n  // signed payloads.\n  requestChecksumCalculation: 'WHEN_REQUIRED',\n});\n```\n\nThe `S3Config` binding is the whole surface a consumer sees:\n\n```ts\ninterface S3Config {\n  readonly url: string; // the store's endpoint\n  readonly bucket: string;\n  readonly accessKeyId: string;\n  readonly secretAccessKey: string;\n}\n```\n\n[`examples/storage`](../../../../examples/storage) is the worked example — a\nsmall blob store/serve app that consumes `storage()` and deploys to Prisma\nCloud.\n\n## Local development\n\nThe same module runs locally against local Postgres — no cloud, no minted\ncredentials. `@prisma/composer-prisma-cloud/storage/testing` exposes the store\nand server directly:\n\n```ts\nimport { createPgStore, startStorageServer } from '@prisma/composer-prisma-cloud/storage/testing';\n\nconst store = await createPgStore(process.env.DATABASE_URL!); // applies the schema\nconst server = startStorageServer({\n  store,\n  credentials: { accessKeyId: 'local', secretAccessKey: 'local-secret' },\n  bucket: 'my-bucket',\n  port: 0, // ephemeral\n});\n\n// server.url is an S3 endpoint — point an aws-sdk client (path-style) at it.\n// server.stop() when done.\n```\n\nThe module's own tests, and `examples/storage`'s integration test, boot exactly\nthis stand-in over a throwaway Postgres: they honor `STATE_TEST_DATABASE_URL`\nwhen set, otherwise self-spawn an ephemeral Homebrew `postgresql@15` cluster\n(`initdb`/`pg_ctl`); they skip on a dev machine with no Postgres and fail on CI\nif none is available.\n\n## Credentials\n\nThe SigV4 key pair is **minted once at deploy** (a random keypair persisted in\ndeploy state) and delivered to consumers through the `S3Config` binding — it is\nnever printed and never surfaces outside the deployment. Consumers are\ntherefore **in-deployment services** that receive the credentials via `load()`,\nnot arbitrary external clients. An external-access path (reading the minted\ncredentials from outside the deploy) is a recorded platform ask, not something\nthis module solves.\n","isInternal":false,"tokens":1427,"sizeBytes":5579},{"name":"README.md","path":"packages/1-prisma-cloud/2-shared-modules/streams/README.md","rawUrl":"https://raw.githubusercontent.com/prisma/COMPOSER/HEAD/packages/1-prisma-cloud/2-shared-modules/streams/README.md","title":"streams Documentation","category":"plugin-manifest","format":"markdown","content":"# `@prisma/composer-prisma-cloud/streams`\n\nDurable append-only event streams as a Prisma Composer module. It wraps the\nproduction `@prisma/streams-server` runtime (npm, unmodified) as a Compute\nservice behind a typed boundary: the module's `store` dependency takes a\n`storage()` module's port as its durable tier, and it exposes a single\n`streams` port. A consumer names the streams it uses with\n`streamsContract(defs)`, and its `durableStreams(contract)` dependency\nhydrates to one ready **`StreamHandle`** per declared name — like RPC's\ngenerated client, no app hand-rolls the protocol, and no app carries a\nstream-lifecycle constant: the handle owns creating the stream on first use\nand healing a 404 by re-creating and retrying once. The wire binding\nunderneath is `{ url, apiKey }`, the key minted by the deploy.\n\nShips as the `@prisma/composer-prisma-cloud/streams` subpath (like `/storage`).\n\n## Contract scope\n\nA contract names its streams:\n\n```ts\nconst jobLog = streamsContract({\n  jobs: streamDef(),   // untyped in this slice — events type as `unknown`\n  audit: streamDef(),\n});\n```\n\nHydration hands a consumer one handle per declared name:\n\n```ts\ninterface StreamHandle {\n  append(event): Promise<void>; // one JSON event; NEVER retried beyond the 404 heal below\n  read<T>(opts?): Promise<{ events: T[]; nextOffset: string }>;\n  tail<T>(opts?): Promise<{ events: T[]; nextOffset: string; timedOut: boolean }>;\n}\n```\n\nNo `create` — a handle creates its stream on first use, memoized, and heals a\n404 (the stream vanished from the durable tier) by dropping that memo,\nre-creating, and retrying the failed operation once. That heal is safe even\nfor an append: a 404 is generated INSTEAD OF a write at every layer, so it\nproves nothing was applied.\n\nFor dynamic stream names (e.g. per-tenant streams), call `durableStreams()`\nwith no contract — the `rawPostgres()` parity, same lifecycle ownership, the\nname is data rather than a wiring-time declaration:\n\n```ts\ninterface StreamsClient {\n  stream(name: string): StreamHandle;\n}\n```\n\nThe wire binding underneath is the typed connection config (ADR-0015) —\n`{ url: string, apiKey: string }` — and the client wraps\n[`@durable-streams/client`](https://www.npmjs.com/package/@durable-streams/client)\n(ElectricSQL's canonical protocol client, pinned to the version\n`@prisma/streams-server` 0.1.11's own repo pairs with). The full protocol\nsurface it drives:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /v1/stream/{name}` | create (idempotent; `content-type` fixes the stream's type) |\n| `POST /v1/stream/{name}` | append a JSON array of events (`stream-closed: true` header closes) |\n| `GET /v1/stream/{name}?offset=…` | read from an offset; `-1` = start; `format=json` |\n| `GET …&live=long-poll&timeout=…` | held read — returns when fresh events arrive or timeout |\n| `GET …&live=sse` | SSE tail (see the deployed live path note below) |\n\nOffsets are **opaque cursors**, not numeric indices: take them from a read's\n`nextOffset` and pass them back verbatim.\n\n**Auth rides the binding.** The bearer key is not an ADR-0029 secret (there\nis no external value to bind) and not a producer output. The `apiKey`\nconnection param declares an [ADR-0031](../../../../docs/design/90-decisions/ADR-0031-provisioned-param-values-are-a-need-resolved-through-a-target-registry.md)\n**provisioning need**: the deploy target mints the value, keeps it stable in\ndeploy state, and fills the param like any other input. Declaring a\n`durableStreams()` dependency is the whole of the wiring — there is no secret\nslot and nothing to bind at the root. Every endpoint, including `/health`,\nrequires `Authorization: Bearer <key>`.\n\nTwo consequences worth knowing:\n\n- **One key per streams module.** The provisioner mints per provider, not per\n  edge, because `@prisma/streams-server` authenticates a single `API_KEY` —\n  every consumer of one `streams()` instance holds the same value. Cardinality\n  is provisioner policy (ADR-0031), so per-edge keys are later a change of\n  that policy plus an accepted-set provider param once the upstream server\n  takes a key set: no resource to add, no core change, nothing here to delete.\n- **No consumers, no key.** The need lives on the consumer's edge, so a\n  `streams()` module nothing depends on never gets a key minted, and its\n  server refuses to boot rather than serve unauthenticated. Wire a consumer,\n  or drop the module.\n\n## Wiring\n\nThe root provisions `storage()` as the durable tier and wires its `store`\nport into `streams()` — the key needs no wiring at all:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport { streams } from '@prisma/composer-prisma-cloud/streams';\nimport worker from './src/worker/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage());\n  const events = provision(streams(), { deps: { store: store.store } });\n  provision(worker, { deps: { streams: events.streams } });\n});\n```\n\n```ts\n// src/worker/service.ts — the consumer. Declaring the dependency is what\n// causes the key to be minted; nothing names it a second time.\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { durableStreams, streamDef, streamsContract } from '@prisma/composer-prisma-cloud/streams';\n\nconst jobLog = streamsContract({ jobs: streamDef() });\n\nexport default compute({\n  name: 'worker',\n  deps: { streams: durableStreams(jobLog) },\n  build: node({ module: import.meta.url, entry: '../../dist/worker/server.mjs' }),\n});\n```\n\n```ts\n// src/worker/server.ts — append, then wait for what follows\nimport service from './service.ts';\n\nconst { streams } = service.load(); // { jobs: StreamHandle }, ready to call\n\nawait streams.jobs.append({ kind: 'created' });\nconst { events, nextOffset } = await streams.jobs.read();\nconst next = await streams.jobs.tail(); // resolves on the next event (or timedOut)\n```\n\nFor local development and tests, build the same client against the stand-in\n(no deployed binding, no auth):\n\n```ts\nimport { StreamsClient } from '@prisma/composer-prisma-cloud/streams';\n\nconst client = new StreamsClient({ url: standIn.url, apiKey: 'unused' });\nconst jobs = client.stream('jobs'); // a StreamHandle, same surface as the hydrated binding\n```\n\n[`examples/streams`](../../../../examples/streams) is the worked example — the\nmodule deployed to Prisma Cloud with `storage()` as its tier and a `jobs`\nservice consuming the binding, plus local integration tests and a deployed\nconsumer smoke script.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/streams/testing` embeds the local stand-in\n(`@prisma/streams-local`): SQLite-only, loopback, **no auth, no object store,\nno cloud credentials** — the same protocol surface.\n\n```ts\nimport { startLocalStreamsServer } from '@prisma/composer-prisma-cloud/streams/testing';\n\nconst server = await startLocalStreamsServer({ name: 'dev', port: 0 });\n// server.exports.http.url is a Durable Streams endpoint (no Authorization needed).\n// await server.close() when done.\n```\n\nThe stand-in persists under `DS_LOCAL_DATA_ROOT`; tests point that at a\nthrowaway directory. The full conformance suite runs against it with no\ncredentials: `pnpm test:conformance:local` (and against a deployment:\n`CONFORMANCE_TEST_URL=… STREAMS_API_KEY=… pnpm test:conformance:deployed`).\n\n## Deployed live path: use long-poll\n\nThe Compute ingress currently buffers HTTP responses until the upstream\nresponse completes. An open `?live=sse` tail therefore never delivers through\na deployment's public URL — the client sees zero bytes and the edge returns a\n504 after ~60s — while the same request works locally and against the\nstand-in. `?live=long-poll` completes per response and delivers live events\nend to end through the ingress, so `StreamHandle.tail` long-polls. The\ndeployed conformance harness keeps the SSE tests, so they flip green when the\nplatform supports streaming responses.\n","isInternal":false,"tokens":1971,"sizeBytes":8048}],"systemPromptSnippet":"<yakaai_skills repo=\"prisma/COMPOSER\">\n<!-- File: AGENTS.md (Tokens: ~602 | Category: root-instruction) -->\n# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n\n<!-- File: CLAUDE.md (Tokens: ~806 | Category: claude-rule) -->\n# Agent guidance — Prisma Composer\n\n**Before doing any design or implementation work in this repo, read the\nguiding principles: [`docs/design/01-principles/`](docs/design/01-principles/).**\nThey are binding, not advisory. Proposals and code that contradict a recorded\nprinciple are wrong by definition — the principle wins until an ADR supersedes\nit. In particular: **we don't bundle the app's code, and we don't guess** — the\nframework never bundles/transforms your code, and assembles the deploy artifact\nonly by documented, deterministic steps (no filename/depth guessing, no tree\nlaundering; symlinks are preserved as links only when their resolved target\nstays inside the bundle, and never dereferenced)\n([ADR-0005](docs/design/90-decisions/ADR-0005-users-build-the-framework-assembles.md),\namended by\n[ADR-0047](docs/design/90-decisions/ADR-0047-compute-assembly-preserves-safe-runtime-topology.md)).\n\n## A layer does not know what is built on it\n\nThis is an\n[architectural principle](docs/design/01-principles/architectural-principles.md#a-layer-does-not-know-what-is-built-on-it),\nand it is the one agents most often break without noticing. It comes up as a\nshortcut: code in a higher layer needs a value, the only thing it holds is a\nlower layer's interface, and one more member on that interface is the shortest\nway. Stop there and read the principle.\n\nIf the member would exist for one kind of Connection, one deployment target or\none Module, do not build it. Do not offer it to the operator as an option\neither, whether the idea is yours or a subagent's: the operator would have to\ncatch the problem themselves, and the gap in the design you found would go\nunreported. Report the gap instead: what the higher layer needs, and why\nnothing that exists carries it.\n\n## Read the design docs before any design discussion\n\nBefore your first reply that offers an opinion, a proposal, or an answer to a\ndesign question, read the documentation for that topic. This applies even when\nthe question looks small or conversational, and again whenever the discussion\nmoves to a new topic. Read:\n\n1. [`docs/design/01-principles/`](docs/design/01-principles/) and\n   [`docs/design/00-purpose/`](docs/design/00-purpose/).\n2. The ADR index,\n   [`docs/design/90-decisions/README.md`](docs/design/90-decisions/README.md),\n   then every ADR it ties to the topic, in full, including the ADRs that amend\n   them.\n3. The [glossary](docs/design/03-domain-model/glossary.md) entry for every term\n   the discussion uses.\n4. The domain or architecture doc for the area, under\n   [`docs/design/10-domains/`](docs/design/10-domains/) or the target's folder.\n\nIn your reply, say what you read. Settled decisions are not relitigated by\naccident: when a proposal contradicts a recorded decision, say so plainly and\nsay what it would reverse. A discussion held without reading these has\nrepeatedly produced proposals that a recorded decision had already rejected,\nrenames of terms the glossary defines on purpose, and identity formats the\nrecorded design contradicts.\n\nOperational rules (naming, casts, build isolation, test idioms) live in\n[`.agents/rules/`](.agents/rules/) and load automatically in harnesses that\nsupport `.mdc` rules; if yours doesn't, read that directory's README and the\nrules relevant to the files you touch.\n\n<!-- File: docs/design/04-inspirations/Convex/convex-nextjs-example/.cursor/rules/convex_rules.mdc (Tokens: ~6446 | Category: cursor-rule) -->\n---\ndescription: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples\nglobs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx\n---\n\n# Convex guidelines\n## Function guidelines\n### New function syntax\n- ALWAYS use the new function syntax for Convex functions. For example:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\nexport const f = query({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n    // Function body\n    },\n});\n```\n\n### Http endpoint syntax\n- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:\n```typescript\nimport { httpRouter } from \"convex/server\";\nimport { httpAction } from \"./_generated/server\";\nconst http = httpRouter();\nhttp.route({\n    path: \"/echo\",\n    method: \"POST\",\n    handler: httpAction(async (ctx, req) => {\n    const body = await req.bytes();\n    return new Response(body, { status: 200 });\n    }),\n});\n```\n- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.\n\n### Validators\n- Below is an example of an array validator:\n```typescript\nimport { mutation } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport default mutation({\nargs: {\n    simpleArray: v.array(v.union(v.string(), v.number())),\n},\nhandler: async (ctx, args) => {\n    //...\n},\n});\n```\n- Below is an example of a schema with validators that codify a discriminated union type:\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n    results: defineTable(\n        v.union(\n            v.object({\n                kind: v.literal(\"error\"),\n                errorMessage: v.string(),\n            }),\n            v.object({\n                kind: v.literal(\"success\"),\n                value: v.number(),\n            }),\n        ),\n    )\n});\n```\n- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:\n```typescript\nimport { query } from \"./_generated/server\";\nimport { v } from \"convex/values\";\n\nexport const exampleQuery = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n      console.log(\"This query returns a null value\");\n      return null;\n  },\n});\n```\n- Here are the valid Convex types along with their respective validators:\nConvex Type  | TS/JS type  |  Example Usage         | Validator for argument validation and schemas  | Notes                                                                                                                                                                                                 |\n| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Id          | string      | `doc._id`              | `v.id(tableName)`                              |                                                                                                                                                                                                       |\n| Null        | null        | `null`                 | `v.null()`                                     | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead.                             |\n| Int64       | bigint      | `3n`                   | `v.int64()`                                    | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers.                                                                                              |\n| Float64     | number      | `3.1`                  | `v.number()`                                   | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings.                                                                      |\n| Boolean     | boolean     | `true`                 | `v.boolean()`                                  |\n| String      | string      | `\"abc\"`                | `v.string()`                                   | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8.                                                         |\n| Bytes       | ArrayBuffer | `new ArrayBuffer(8)`   | `v.bytes()`                                    | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types.                                                     |\n| Array       | Array       | `[1, 3.2, \"abc\"]`      | `v.array(values)`                              | Arrays can have at most 8192 values.                                                                                                                                                                  |\n| Object      | Object      | `{a: \"abc\"}`           | `v.object({property: value})`                  | Convex only supports \"plain old JavaScript objects\" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with \"$\" or \"_\". |\n| Record      | Record      | `{\"a\": \"1\", \"b\": \"2\"}` | `v.record(keys, values)`                       | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with \"$\" or \"_\".                                                               |\n\n### Function registration\n- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.\n- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.\n- You CANNOT register a function through the `api` or `internal` objects.\n- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.\n- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.\n\n### Function calling\n- Use `ctx.runQuery` to call a query from a query, mutation, or action.\n- Use `ctx.runMutation` to call a mutation from a mutation or action.\n- Use `ctx.runAction` to call an action from an action.\n- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.\n- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.\n- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.\n- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,\n```\nexport const f = query({\n  args: { name: v.string() },\n  returns: v.string(),\n  handler: async (ctx, args) => {\n    return \"Hello \" + args.name;\n  },\n});\n\nexport const g = query({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const result: string = await ctx.runQuery(api.example.f, { name: \"Bob\" });\n    return null;\n  },\n});\n```\n\n### Function references\n- Function references are pointers to registered Convex functions.\n- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.\n- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.\n- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.\n- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.\n- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.\n\n### Api design\n- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.\n- Use `query`, `mutation`, and `action` to define public functions.\n- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.\n\n### Pagination\n- Paginated queries are queries that return a list of results in incremental pages.\n- You can define pagination using the following syntax:\n\n```ts\nimport { v } from \"convex/values\";\nimport { query, mutation } from \"./_generated/server\";\nimport { paginationOptsValidator } from \"convex/server\";\nexport const listWithExtraArg = query({\n    args: { paginationOpts: paginationOptsValidator, author: v.string() },\n    handler: async (ctx, args) => {\n        return await ctx.db\n        .query(\"messages\")\n        .withIndex(\"by_author\", (q) => q.eq(\"author\", args.author))\n        .order(\"desc\")\n        .paginate(args.paginationOpts);\n    },\n});\n```\nNote: `paginationOpts` is an object with the following properties:\n- `numItems`: the maximum number of documents to return (the validator is `v.number()`)\n- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)\n- A query that ends in `.paginate()` returns an object that has the following properties:\n- page (contains an array of documents that you fetches)\n- isDone (a boolean that represents whether or not this is the last page of documents)\n- continueCursor (a string that represents the cursor to use to fetch the next page of documents)\n\n\n## Validator guidelines\n- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.\n- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.\n\n## Schema guidelines\n- Always define your schema in `convex/schema.ts`.\n- Always import the schema definition functions from `convex/server`.\n- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.\n- Always include all index fields in the index name. For example, if an index is defined as `[\"field1\", \"field2\"]`, the index name should be \"by_field1_and_field2\".\n- Index fields must be queried in the same order they are defined. If you want to be able to query by \"field1\" then \"field2\" and by \"field2\" then \"field1\", you must create separate indexes.\n\n## Typescript guidelines\n- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.\n- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:\n```ts\nimport { query } from \"./_generated/server\";\nimport { Doc, Id } from \"./_generated/dataModel\";\n\nexport const exampleQuery = query({\n    args: { userIds: v.array(v.id(\"users\")) },\n    returns: v.record(v.id(\"users\"), v.string()),\n    handler: async (ctx, args) => {\n        const idToUsername: Record<Id<\"users\">, string> = {};\n        for (const userId of args.userIds) {\n            const user = await ctx.db.get(\"users\", userId);\n            if (user) {\n                idToUsername[user._id] = user.username;\n            }\n        }\n\n        return idToUsername;\n    },\n});\n```\n- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.\n- Always use `as const` for string literals in discriminated union types.\n- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`\n- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`\n- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.\n\n## Full text search guidelines\n- A query for \"10 messages in channel '#general' that best match the query 'hello hi' in their body\" would look like:\n\nconst messages = await ctx.db\n  .query(\"messages\")\n  .withSearchIndex(\"search_body\", (q) =>\n    q.search(\"body\", \"hello hi\").eq(\"channel\", \"#general\"),\n  )\n  .take(10);\n\n## Query guidelines\n- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.\n- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.\n- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.\n- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.\n### Ordering\n- By default Convex always returns documents in ascending `_creationTime` order.\n- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.\n- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.\n\n\n## Mutation guidelines\n- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })`\n- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })`\n\n## Action guidelines\n- Always add `\"use node\";` to the top of files containing actions that use Node.js built-in modules.\n- Never use `ctx.db` inside of an action. Actions don't have access to the database.\n- Below is an example of the syntax for an action:\n```ts\nimport { action } from \"./_generated/server\";\n\nexport const exampleAction = action({\n    args: {},\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        console.log(\"This action does not return anything\");\n        return null;\n    },\n});\n```\n\n## Scheduling guidelines\n### Cron guidelines\n- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.\n- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.\n- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,\n```ts\nimport { cronJobs } from \"convex/server\";\nimport { internal } from \"./_generated/api\";\nimport { internalAction } from \"./_generated/server\";\n\nconst empty = internalAction({\n  args: {},\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    console.log(\"empty\");\n  },\n});\n\nconst crons = cronJobs();\n\n// Run `internal.crons.empty` every two hours.\ncrons.interval(\"delete inactive users\", { hours: 2 }, internal.crons.empty, {});\n\nexport default crons;\n```\n- You can register Convex functions within `crons.ts` just like any other file.\n- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file.\n\n\n## File storage guidelines\n- Convex includes file storage for large files like images, videos, and PDFs.\n- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.\n- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.\n\nInstead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<\"_storage\">`.\n```\nimport { query } from \"./_generated/server\";\nimport { Id } from \"./_generated/dataModel\";\n\ntype FileMetadata = {\n    _id: Id<\"_storage\">;\n    _creationTime: number;\n    contentType?: string;\n    sha256: string;\n    size: number;\n}\n\nexport const exampleQuery = query({\n    args: { fileId: v.id(\"_storage\") },\n    returns: v.null(),\n    handler: async (ctx, args) => {\n        const metadata: FileMetadata | null = await ctx.db.system.get(\"_storage\", args.fileId);\n        console.log(metadata);\n        return null;\n    },\n});\n```\n- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.\n\n\n# Examples:\n## Example: chat-app\n\n### Task\n```\nCreate a real-time chat application backend with AI responses. The app should:\n- Allow creating users with names\n- Support multiple chat channels\n- Enable users to send messages to channels\n- Automatically generate AI responses to user messages\n- Show recent message history\n\nThe backend should provide APIs for:\n1. User management (creation)\n2. Channel management (creation)\n3. Message operations (sending, listing)\n4. AI response generation using OpenAI's GPT-4\n\nMessages should be stored with their channel, author, and content. The system should maintain message order\nand limit history display to the 10 most recent messages per channel.\n\n```\n\n### Analysis\n1. Task Requirements Summary:\n- Build a real-time chat backend with AI integration\n- Support user creation\n- Enable channel-based conversations\n- Store and retrieve messages with proper ordering\n- Generate AI responses automatically\n\n2. Main Components Needed:\n- Database tables: users, channels, messages\n- Public APIs for user/channel management\n- Message handling functions\n- Internal AI response generation system\n- Context loading for AI responses\n\n3. Public API and Internal Functions Design:\nPublic Mutations:\n- createUser:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({userId: v.id(\"users\")})\n  - purpose: Create a new user with a given name\n- createChannel:\n  - file path: convex/index.ts\n  - arguments: {name: v.string()}\n  - returns: v.object({channelId: v.id(\"channels\")})\n  - purpose: Create a new channel with a given name\n- sendMessage:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), authorId: v.id(\"users\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Send a message to a channel and schedule a response from the AI\n\nPublic Queries:\n- listMessages:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n    }))\n  - purpose: List the 10 most recent messages from a channel in descending creation order\n\nInternal Functions:\n- generateResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.null()\n  - purpose: Generate a response from the AI for a given channel\n- loadContext:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\")}\n  - returns: v.array(v.object({\n    _id: v.id(\"messages\"),\n    _creationTime: v.number(),\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }))\n- writeAgentResponse:\n  - file path: convex/index.ts\n  - arguments: {channelId: v.id(\"channels\"), content: v.string()}\n  - returns: v.null()\n  - purpose: Write an AI response to a given channel\n\n4. Schema Design:\n- users\n  - validator: { name: v.string() }\n  - indexes: <none>\n- channels\n  - validator: { name: v.string() }\n  - indexes: <none>\n- messages\n  - validator: { channelId: v.id(\"channels\"), authorId: v.optional(v.id(\"users\")), content: v.string() }\n  - indexes\n    - by_channel: [\"channelId\"]\n\n5. Background Processing:\n- AI response generation runs asynchronously after each user message\n- Uses OpenAI's GPT-4 to generate contextual responses\n- Maintains conversation context using recent message history\n\n\n### Implementation\n\n#### package.json\n```typescript\n{\n  \"name\": \"chat-app\",\n  \"description\": \"This example shows how to build a chat app without authentication.\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"convex\": \"^1.31.2\",\n    \"openai\": \"^4.79.0\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.7.3\"\n  }\n}\n```\n\n#### tsconfig.json\n```typescript\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"exclude\": [\"convex\"],\n  \"include\": [\"**/src/**/*.tsx\", \"**/src/**/*.ts\", \"vite.config.ts\"]\n}\n```\n\n#### convex/index.ts\n```typescript\nimport {\n  query,\n  mutation,\n  internalQuery,\n  internalMutation,\n  internalAction,\n} from \"./_generated/server\";\nimport { v } from \"convex/values\";\nimport OpenAI from \"openai\";\nimport { internal } from \"./_generated/api\";\n\n/**\n * Create a user with a given name.\n */\nexport const createUser = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"users\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"users\", { name: args.name });\n  },\n});\n\n/**\n * Create a channel with a given name.\n */\nexport const createChannel = mutation({\n  args: {\n    name: v.string(),\n  },\n  returns: v.id(\"channels\"),\n  handler: async (ctx, args) => {\n    return await ctx.db.insert(\"channels\", { name: args.name });\n  },\n});\n\n/**\n * List the 10 most recent messages from a channel in descending creation order.\n */\nexport const listMessages = query({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      _id: v.id(\"messages\"),\n      _creationTime: v.number(),\n      channelId: v.id(\"channels\"),\n      authorId: v.optional(v.id(\"users\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n    return messages;\n  },\n});\n\n/**\n * Send a message to a channel and schedule a response from the AI.\n */\nexport const sendMessage = mutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    authorId: v.id(\"users\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const user = await ctx.db.get(args.authorId);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      authorId: args.authorId,\n      content: args.content,\n    });\n    await ctx.scheduler.runAfter(0, internal.index.generateResponse, {\n      channelId: args.channelId,\n    });\n    return null;\n  },\n});\n\nconst openai = new OpenAI();\n\nexport const generateResponse = internalAction({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    const context = await ctx.runQuery(internal.index.loadContext, {\n      channelId: args.channelId,\n    });\n    const response = await openai.chat.completions.create({\n      model: \"gpt-4o\",\n      messages: context,\n    });\n    const content = response.choices[0].message.content;\n    if (!content) {\n      throw new Error(\"No content in response\");\n    }\n    await ctx.runMutation(internal.index.writeAgentResponse, {\n      channelId: args.channelId,\n      content,\n    });\n    return null;\n  },\n});\n\nexport const loadContext = internalQuery({\n  args: {\n    channelId: v.id(\"channels\"),\n  },\n  returns: v.array(\n    v.object({\n      role: v.union(v.literal(\"user\"), v.literal(\"assistant\")),\n      content: v.string(),\n    }),\n  ),\n  handler: async (ctx, args) => {\n    const channel = await ctx.db.get(args.channelId);\n    if (!channel) {\n      throw new Error(\"Channel not found\");\n    }\n    const messages = await ctx.db\n      .query(\"messages\")\n      .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n      .order(\"desc\")\n      .take(10);\n\n    const result = [];\n    for (const message of messages) {\n      if (message.authorId) {\n        const user = await ctx.db.get(message.authorId);\n        if (!user) {\n          throw new Error(\"User not found\");\n        }\n        result.push({\n          role: \"user\" as const,\n          content: `${user.name}: ${message.content}`,\n        });\n      } else {\n        result.push({ role: \"assistant\" as const, content: message.content });\n      }\n    }\n    return result;\n  },\n});\n\nexport const writeAgentResponse = internalMutation({\n  args: {\n    channelId: v.id(\"channels\"),\n    content: v.string(),\n  },\n  returns: v.null(),\n  handler: async (ctx, args) => {\n    await ctx.db.insert(\"messages\", {\n      channelId: args.channelId,\n      content: args.content,\n    });\n    return null;\n  },\n});\n```\n\n#### convex/schema.ts\n```typescript\nimport { defineSchema, defineTable } from \"convex/server\";\nimport { v } from \"convex/values\";\n\nexport default defineSchema({\n  channels: defineTable({\n    name: v.string(),\n  }),\n\n  users: defineTable({\n    name: v.string(),\n  }),\n\n  messages: defineTable({\n    channelId: v.id(\"channels\"),\n    authorId: v.optional(v.id(\"users\")),\n    content: v.string(),\n  }).index(\"by_channel\", [\"channelId\"]),\n});\n```\n\n#### convex/tsconfig.json\n```typescript\n{\n  /* This TypeScript project config describes the environment that\n   * Convex functions run in and is used to typecheck them.\n   * You can modify it, but some settings required to use Convex.\n   */\n  \"compilerOptions\": {\n    /* These settings are not required by Convex and can be modified. */\n    \"allowJs\": true,\n    \"strict\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"jsx\": \"react-jsx\",\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n\n    /* These compiler options are required by Convex */\n    \"target\": \"ESNext\",\n    \"lib\": [\"ES2021\", \"dom\"],\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*\"],\n  \"exclude\": [\"./_generated\"]\n}\n```\n\n#### src/App.tsx\n```typescript\nexport default function App() {\n  return <div>Hello World</div>;\n}\n```\n\n<!-- File: .agents/rules/README.md (Tokens: ~242 | Category: anthropic-skill) -->\n# Agent Rules Index\n\nCurated rules for agents and developers — quick, actionable guidance.\n\n## Canonical home & sync\n\nEvery rule has a single canonical home: `.agents/rules/<name>.mdc` — the only\ngit-tracked copy. Rule files must use the `.mdc` extension; the harnesses load\n`.mdc` only, so a `.md` rule is silently dead (`pnpm lint:rules:symlinks`\nrejects them). The `.cursor/rules/` and `.claude/rules/` trees are git-ignored\npresentation mirrors containing nothing but relative symlinks back into\n`.agents/rules/`.\n\n```bash\npnpm rules:sync           # Consolidate stray rules + (re)generate the symlink trees\npnpm lint:rules:symlinks  # Fail if a tree is out of sync with canonical (runs in CI)\n```\n\n`rules:sync` also runs from `prepare`, so `pnpm install` rebuilds the trees\nautomatically. **Add or edit rules at the canonical path** (`.agents/rules/`);\na rule dropped only into `.cursor/rules` is git-ignored and will be lost.\n\n<!-- File: skills-contrib/multiline-commit-messages/SKILL.md (Tokens: ~336 | Category: anthropic-skill) -->\n---\nname: multiline-commit-messages\ndescription: >-\n  Use single-quoted strings for multiline git commit messages in the Shell tool.\n  Prevents heredoc escaping failures that produce garbled commit messages.\n---\n\n# Multiline commit messages\n\nThe Shell tool sends commands as a single string. Heredoc syntax (`<<'EOF'`) inside `$(cat ...)` is fragile and can fail silently — the literal `$(cat <<'EOF' ...` ends up as the commit message instead of the intended text.\n\n## Rule\n\nPrefer single-quoted strings with embedded newlines over `$(cat <<'EOF' ...)`:\n\n```bash\ngit commit -s -m 'short summary line\n\nLonger body paragraph explaining why the change exists.\nAdditional context if needed.'\n```\n\n## Why heredocs are fragile\n\nThe Shell tool passes the command as a single string argument. When you write:\n\n```bash\ngit commit -m \"$(cat <<'EOF'\nmessage\nEOF\n)\"\n```\n\nthe `EOF` delimiter, newlines, and nested quoting can interact unpredictably, and the result is the raw `$(cat <<'EOF' ...` text appearing as the commit message.\n\nSingle-quoted strings with literal newlines are simple, portable, and always work. If the message itself must contain a single quote, close and reopen the quote (`'\\''`) or fall back to a temp file passed via `-F`.\n\n## Sign off\n\nEvery commit still needs its `Signed-off-by` trailer — see [git-staging](../../../.cursor/rules/git-staging.mdc). Pass `-s` on the same `git commit` invocation.\n\n<!-- File: skills-contrib/publish-npm-version/SKILL.md (Tokens: ~916 | Category: anthropic-skill) -->\n---\nname: publish-npm-version\ndescription: >-\n  Cuts the next minor release of Prisma Composer: bumps the root\n  package.json version, propagates it to every workspace package in lockstep,\n  and opens a PR titled \"chore(release): v<next-version>\". When a maintainer\n  merges the PR, the `Publish to npm` workflow runs automatically and publishes\n  the new version to npm under dist-tag `next`, plus a matching GitHub Release\n  with auto-generated notes; users get it when a maintainer promotes it to\n  `latest`. Use when a maintainer asks to \"cut the next minor\",\n  \"bump to the next version\", \"open a release PR\", or \"prepare a publish PR\".\n---\n\n# Publish next npm version\n\n## Audience\n\nMaintainers who can push branches and open PRs. Invoke this **locally**, not as a\nGitHub Action — a PR opened by a workflow's `GITHUB_TOKEN` does not trigger CI,\nwhich defeats the point of a reviewable release.\n\n## Background reading\n\nRead [`docs/oss/versioning.md`](../../docs/oss/versioning.md) first — it is the\npolicy this skill mechanises: the root-`package.json` source of truth, the\nlockstep guarantee, the dist-tag convention, and the full procedure (this skill\nis the \"open the bump PR\" step; **merging the PR is the publish trigger** — there\nis no separate dispatch step).\n\n## Pre-flight\n\nConfirm you can fetch from `origin` (`git fetch origin main` succeeds). The skill\nworks in a fresh worktree off `origin/main`, so your current worktree is left\nundisturbed.\n\n## Steps\n\n1. **Fresh worktree off `origin/main`:**\n   ```bash\n   git fetch origin main\n   git worktree add -b chore/release-vNEXT ../release-vNEXT origin/main\n   cd ../release-vNEXT\n   pnpm install --frozen-lockfile\n   ```\n2. **Bump.** `pnpm bump-minor` reads the root version at `HEAD`, computes the next\n   minor (`0.2.0` → `0.3.0`), stamps every workspace `package.json` in\n   lockstep (rewriting internal `workspace:` deps to the new version), and\n   regenerates `pnpm-lock.yaml` to match.\n3. **Sanity-check** the bump is clean and complete. The diff must include\n   `pnpm-lock.yaml` — CI installs with `--frozen-lockfile`, so a bump without the\n   lockfile fails every CI job at the install step:\n   ```bash\n   git diff --stat                      # every workspace package.json + pnpm-lock.yaml\n   pnpm check:publish-deps              # no workspace:/catalog: leaks, exact internal pins\n   ```\n4. **Commit** with the release title and dual DCO sign-off, then push and open the PR:\n   ```bash\n   git commit -am \"chore(release): v<version>\"\n   git push -u origin chore/release-vNEXT\n   gh pr create --base main --title \"chore(release): v<version>\" \\\n     --body \"Release v<version>. Merging this triggers the Publish to npm workflow.\"\n   ```\n5. **Hand off.** Tell the maintainer the PR is open and that **merging it** publishes `<version>` to npm under `next` (via OIDC trusted publishing) and cuts a GitHub Release with auto-generated notes. Users get the release only once a maintainer promotes it to `latest` with the `Promote a release to latest` workflow (versioning.md § Promote a release to `latest`). Do not merge it yourself unless asked.\n\n## What this skill does NOT do\n\n- **Patches / old minors.** There are no patch releases of older minors\n  (versioning.md § pre-1.0). This skill only advances the latest minor.\n- **The publish itself.** That is the `Publish to npm` workflow, triggered by the\n  merge — never run `pnpm publish` by hand for a normal release.\n- **Release notes authoring.** The GitHub Release notes are auto-generated\n  (`gh release create --generate-notes`) by the workflow; there is no committed\n  release-notes file to write.\n\n<!-- File: skills-contrib/upgrade-alchemy-effect/SKILL.md (Tokens: ~5214 | Category: anthropic-skill) -->\n---\nname: upgrade-alchemy-effect\ndescription: >-\n  How to upgrade `alchemy` and the `effect` constellation across this repo and\n  keep them consistent for consumers: which packages pin what, why `effect` and\n  every `@effect/*` companion move as one set, what breaks in a typical\n  upgrade, and how to verify a standalone `npm install` still resolves a single\n  `effect`. Use when asked to upgrade or bump alchemy or effect, when a deploy\n  dies inside an alchemy provider with a `TypeError` naming a missing\n  combinator, when `check:npm-effect-resolution` fails, or when deciding\n  whether the alchemy patch is still needed.\n---\n\n# Upgrade alchemy and effect\n\n## Audience\n\nMaintainers changing the `alchemy` or `effect` pins in this repo.\n\n## Read this first\n\n**Check what upstream ships before working around what we pin.** The pinned\nversion is not a constant, and treating it as one is expensive: TML-3158 was a\nlong chase through pinning, peer dependencies, and a CLI preflight (since\nretired), all to keep\na consumer's tree away from an `effect` that alchemy 2.0.0-beta.59 could not\nrun — while a newer alchemy that had already fixed it sat on the registry the\nwhole time. One command would have shown it:\n\n```bash\nnpm view alchemy dist-tags\nnpm view alchemy@<latest> peerDependencies\n```\n\nIf alchemy's `effect` peer range has moved past our pin, the upgrade *is* the\nfix. Reach for workarounds only after that check says otherwise.\n\n## Why the versions move as a set\n\n`effect` and its companions — `@effect/platform-node`, `@effect/platform-bun`,\n`@effect/platform-node-shared` — each declare a peer that is\n**floored at their own version**:\n\n```jsonc\n// @effect/platform-bun@4.0.0-rc.111\n\"peerDependencies\": { \"effect\": \"^4.0.0-rc.111\" }\n```\n\nThat caret is a range, not an exact pin: it accepts `4.0.0-rc.112` and stable\n`4.x`, but nothing below `4.0.0-rc.111`. So an `effect` **older** than any\ncompanion in the tree is unsatisfiable, and npm resolves that by installing a\n*second* `effect`. Pinning every package in this repo to the same release is the\nsimple way to stay above every floor at once. Treat them as one constellation,\nnever as individual bumps.\n\nalchemy sits on top with a deliberately loose range (`>=4.0.0-rc.115 || >=4.0.0` at beta.78). That range is what lets a stray dependency drag a different `effect` in.\n\n## Two audiences, two failure modes\n\n- **This workspace** uses pnpm, which only *warns* on a peer mismatch and keeps\n  our pinned copy. A broken constellation is therefore invisible in-repo — CI\n  and local dev stay green while consumers break.\n- **Consumers** use npm, which hoists a satisfying version to the root of\n  `node_modules`. alchemy imports whatever is at the root. Nothing we declare\n  prevents this: an exact `peerDependencies` entry does **not** make npm fail —\n  verified empirically, it warns, hoists the other copy anyway, and exits 0.\n  Only the consumer's own `overrides` can force alchemy's copy.\n\nThat asymmetry is why `scripts/check-npm-effect-resolution.mjs` installs real\ntarballs with real npm.\n\n## What a consumer sees when the tree is wrong\n\nComposer has no check of its own for a wrong `effect`. The app's\n`prisma.config.ts` imports the extensions' `/control` entries in its `composer`\nsection, and those import alchemy, so a wrong `effect` fails the moment the\nengine evaluates the config file, before any command runs. The error is the\nengine's `CLI.CONFIG_UNREADABLE`, naming the file and carrying the module error,\nfor example `prisma.config.ts could not be evaluated: Schema.TaggedError is not\na function`. Only the consumer's package manager can fix that tree, usually\nwith an `overrides` entry that forces our pinned `effect`\n(`docs/guides/deploying.md`). Keep the pins below exact and consistent so a bare\ninstall never gets there.\n\n## Steps\n\n1. **Pick the target.** Read alchemy's latest peer range, then choose the newest release where *every* companion publishes a matching version:\n\n   ```bash\n   npm view alchemy dist-tags\n   npm view alchemy@<version> peerDependencies\n   for p in effect @effect/platform-node @effect/platform-bun \\\n            @effect/platform-node-shared; do\n     echo \"$p $(npm view $p version)\"\n   done\n   ```\n\n   alchemy's floor is not a compatibility promise. alchemy 2.0.0-beta.75 to beta.77 accept `effect` rc.112 and later, but call `Config.string`, which rc.113 removed, so they crash on it. Pin the `effect` release alchemy was built against: the newest one published before that alchemy release (`npm view effect time`). Check the new alchemy's Prisma provider still loads from a plain npm install: in beta.79 it imports the optional peer `@alchemy.run/frontend-frameworks` and fails. Since beta.84 each provider is its own package, versioned in lockstep with `alchemy`: the Prisma provider is `@alchemy.run/prisma` (formerly the `alchemy/Prisma` module), and only `@prisma/composer-prisma-cloud` and the Prisma Cloud internals depend on it. Bump it with `alchemy`.\n\n2. **Find every pin.** `alchemy`, `@alchemy.run/prisma`, `@distilled.cloud/prisma`, `effect` and the `@effect/platform-*` packages are pinned once, in the `catalog:` block of `pnpm-workspace.yaml`; every manifest says `catalog:`, and `pnpm pack` writes the resolved version into the published manifest. Check nothing outside the catalog pins them:\n\n   ```bash\n   grep -rln '\"alchemy\"\\|\"@alchemy.run/\\|\"@distilled.cloud/\\|@effect/\\|\"effect\"' --include=package.json . | grep -v node_modules\n   ```\n\n3. **Clear the patch key first.** `pnpm.patchedDependencies` is keyed by the\n   exact version, so an alchemy bump leaves it pointing at a version that is no\n   longer installed and the next install fails or silently skips the patch.\n   Remove the entry now and re-create it in step 5 once you know whether it is\n   still needed.\n4. **Bump all of them to the same versions**, then `pnpm install`. Nothing may\n   be left behind — a single stale companion reintroduces the second `effect`.\n5. **Decide the patch** (see below): typecheck without it, and only re-create\n   it against the new version if upstream still needs the fix.\n6. **`pnpm typecheck`.** Expect real API breakage; see the classes below. Note\n   that turbo stops at the first failing package, so run `pnpm exec tsc\n   --noEmit` per package to see the true scope.\n7. **`pnpm check:npm-effect-resolution`** (after building the two public\n   packages). This is the consumer-facing proof.\n8. **The E2E deploy jobs are the real bar.** An alchemy upgrade changes the\n   deploy engine; a green typecheck says very little about it.\n\n## Pinning an unreleased alchemy build\n\nThe repo is on registry releases: `alchemy` and `@alchemy.run/prisma` 2.0.0-beta.87, `@distilled.cloud/prisma` 1.0.0-rc.20, and `effect` with its companions at 4.1.4. History: Composer pinned a preview of alchemy-run/alchemy#3101 until beta.87 released it together with alchemy-run/distilled#1076. Those two changes let `PrismaEnvironment` and Distilled's `Credentials` omit the token, which `prisma deploy` needs to send every request through the engine's client. Use a preview only when you need a fix that no release contains yet.\n\nalchemy publishes a preview of every commit on `main`, and of each pull request's head as `pr:<number>:<short sha>`. Pin it by commit, never by branch, in the `catalog:` block of `pnpm-workspace.yaml`:\n\n```yaml\nalchemy: https://pkg.alchemy.run/alchemy/<commit sha>\n'@alchemy.run/prisma': https://pkg.alchemy.run/@alchemy.run/prisma/<commit sha>\n```\n\n- **No release while a pin is a URL.** `check:publish-deps` (run by the publish workflow on every push to `main`) fails on any URL, git or `file:` dependency in a published package. Swap the pins for a registry release before merging to `main` expecting a publish.\n\n- **The commit URL is immutable.** It redirects to a content-addressed tarball (`/alchemy/-/<sha256>.tgz`). The lockfile records the commit URL and the tarball's integrity.\n- **Pin `alchemy` and every `@alchemy.run/*` package at the same commit.** They are built together.\n- **A preview's own dependencies are content-addressed URLs too.** `@alchemy.run/prisma` depends on `@distilled.cloud/prisma` by a `/-/<sha256>.tgz` URL. Pin our `@distilled.cloud/prisma` to that exact URL (read it from the tarball's `package.json`), or pnpm and npm install a second copy and `Credentials` stops matching. The commit URL for the same package does not dedupe with it.\n- **The `alchemy` peer of `@alchemy.run/prisma` is a tarball URL.** For a commit preview it may name a different tarball hash than the commit URL resolves to; the two differ only in an embedded URL in `package.json`, and npm accepts our copy. For a pull request preview (`pr:<n>:<sha>`) the peer names the same tarball the PR URL redirects to, but npm compares the specs and `npm ls` reports our `alchemy` invalid, so `check:npm-effect-resolution` fails. Pin `alchemy` to the peer's exact tarball URL then.\n- **Not every package has a preview.** `@alchemy.run/test` returns 404 at every commit, so nothing may depend on it (see the breakage classes).\n- **Read the source at the commit**, not the docs: `git clone https://github.com/alchemy-run/alchemy && git checkout <sha>`, or extract the tarball into a gitignored `wip/` folder.\n- **Move back to a registry version** once a release contains the commit: `npm view alchemy dist-tags`, then compare the release date with the commit date.\n\n## The effect-family packages a consumer installs are pinned in the public packages\n\nalchemy's `effect`-family ranges float past what its code supports (the upstream `TaggedErrorClass` drift), and a floater whose newest release names an `effect` peer that does not exist yet sends npm into hours of backtracking instead of an error (2026-09-11: `@effect/*@4.0.0-rc.114` published ahead of `effect`). Consumers carry no overrides block. Instead, the rule is:\n\n**Pin exactly, in a public package's `dependencies`, every `effect`-family package that a consumer's install will contain.** A package is in the install when it is a regular dependency of `alchemy` or `@alchemy.run/prisma`, an optional peer that one of them loads at runtime, or a package Composer's own code imports. An optional peer that nothing loads is not installed by npm at all, so it gets no pin: pinning it would install it, and everything it depends on, for every consumer.\n\nToday that is:\n\n- `@prisma/composer` — `effect` itself.\n- `@prisma/composer-prisma-cloud` — `@effect/platform-bun` and `@effect/platform-node`, which alchemy loads at runtime (`alchemy/Util/PlatformServices`, `alchemy/Http`; Composer's provider wiring also imports `@effect/platform-node`), and `@effect/platform-node-shared`, which both depend on. It also depends on `@distilled.cloud/prisma`, whose `Credentials` the provider wiring imports; keep it at the exact version `@alchemy.run/prisma` depends on (a tarball URL for a preview) so npm installs one copy.\n\nTo apply the rule on an upgrade, read `dependencies` and `peerDependenciesMeta` in both `alchemy/package.json` and `@alchemy.run/prisma/package.json`, and grep the built `dist/` of the public packages and the installed `lib/` of both for imports of each `@effect/*` package.\n\nHistory: beta.83 listed `@effect/sql-d1` and `@effect/sql-sqlite-do` as regular dependencies, so `@prisma/composer` pinned them, along with `@effect/vitest`, which it pinned on its own. Beta.84 no longer depends on the two SQL packages, and `@effect/vitest` is an optional peer that only `alchemy/Test/Vitest` loads. All three pins were dropped with the beta.84 bump. Dropping `@effect/vitest` also removed `vitest` and `vite` from every consumer's install.\n\n`check-npm-effect-resolution` installs the tarballs bare and fails when the install backtracks or resolves a second `effect`. It installs once more with npm 10, the npm that Node 22 bundles, because npm 10 has crashed on packages the tree once contained (`vitest@4.1.x`); the shape stays as a guard for Node 22 users. The only case left to a consumer's own `overrides` is an app that pins a different `effect` itself (documented in `docs/guides/deploying.md`).\n\n## Breakage classes seen in practice\n\n- **Removed `effect` combinators.** `Schedule.both`/`Schedule.either`\n  (intersection/union) disappeared at beta.97. `Schedule.both(spaced(x),\n  during(y))` becomes `Schedule.spaced(x).pipe(Schedule.upTo({ duration: y }))`;\n  `Schedule.max`/`Schedule.min` are the general replacements.\n- **Stable Effect HTTP imports.** Effect 4 uses `effect/http/*`, replacing `effect/unstable/http/*`.\n- **Alchemy lifecycle identity.** Since beta.82, provider fixtures supply `ResourceContext` (`logicalId`, `fqn`, `instanceId`, `type`) instead of `InstanceId`. Local Database, App and Bucket attributes also need `logicalId`; use `null` because local dev creates no platform rows.\n- **Vitest 5 type tests.** Stable `@effect/vitest` requires Vitest 5. Type-only files need a registered test; keep ambient declarations outside its callback or use definite-assignment fixtures inside it.\n- **Providers moved out of `alchemy` (2.0.0-beta.84).** `alchemy/Prisma` is now the separate package `@alchemy.run/prisma` (`alchemy/Prisma/Types` becomes `@alchemy.run/prisma/Types`). Add it to every package that imports it, including `@prisma/composer-prisma-cloud`, which bundles them. `alchemy` itself no longer depends on `@distilled.cloud/*` or the `@effect/sql-*` packages.\n- **`alchemy/Test/Core` is gone (2.0.0-beta.84).** It moved to `@alchemy.run/test`, which is not published. Provider tests use `scratchStack` and `runScratch` from `@internal/lowering/scratch-stack`, a port of the parts we used.\n- **Real network calls in provider tests.** At the 2.0.0-beta.84 preview, `Prisma.CustomDomain` waits for the hostname's CNAME on its authoritative nameservers before it registers a domain. Tests stub `node:dns/promises` so the wait is skipped.\n- **New adoption advice in engine or provider messages.** `withComposerAdvice` in the CLI rewrites Alchemy's `--adopt` and \"explicit adoption\" advice; its tests read every such message from the installed `alchemy` (`Plan.ts`, `Apply.ts`) and `@alchemy.run/prisma` sources and fail on one it does not rewrite. Add the new message to the rewrite list.\n- **Typed provider errors (2.0.0-beta.87).** Every lifecycle method of a `ProviderService` must fail with `Provider.ProviderError` (`{ _tag: string; message?: string }`), not `unknown`. `Effect.tryPromise` sites pass `catch: toProviderError` from `@internal/core/deploy`, which keeps an error that already has a `_tag` and wraps any other in a `ProviderFailure` with the same message and the original as `cause`. The deploy reports a wrapped error as the error it wraps.\n- **`PrismaEnvironment` holds an Effect (2.0.0-beta.87).** Alchemy runs it on every Management API request. Provide `Layer.succeed(Prisma.PrismaEnvironment, Effect.succeed({ ... }))`.\n- **New required fields on alchemy's resource-handler context** (e.g. `fqn`).\n  These surface only in the test fixtures that build the context by hand.\n- **`exactOptionalPropertyTypes` vs alchemy's types.** See the patch section.\n- **Error counts that go *up* after a fix.** TypeScript stops at the first bad\n  argument, so repairing it exposes the next one. Rising counts mid-upgrade are\n  normal, not a sign the fix was wrong.\n\n## The alchemy patch\n\n`patches/alchemy@<version>.patch` fixes one upstream type declaration:\n`ResourceClassLike.Aliases` is `readonly string[]` (exact-optional) while\n`ResourceClass.Aliases` is `readonly string[] | undefined`. Under this repo's\n`exactOptionalPropertyTypes`, the second is not assignable to the first, so\n**every** `Provider.effect` and `Provider.collection` call fails to compile —\n45 errors across three packages at the time of writing. alchemy carries\n`@ts-expect-error` at its own equivalent call sites, so this is upstream's\ninconsistency, not our misuse.\n\n**Do not work around it at the call sites.** That was tried: it needs a cast at\nroughly twenty sites, and narrowing the argument type also destroys inference\nfor the second argument, which surfaces a fresh wave of errors. Adding\n`| undefined` to the optional property fixes all of them at the source.\n\nOn every upgrade, check whether upstream has fixed it. With the\n`pnpm.patchedDependencies` entry already removed in step 3:\n\n```bash\npnpm install && (cd packages/1-prisma-cloud/0-lowering/lowering && pnpm exec tsc --noEmit)\n```\n\nClean means the patch is obsolete: delete `patches/alchemy@<old>.patch` and\nleave the config entry out. Still failing means re-create it against the new\nversion:\n\n```bash\npnpm patch alchemy@<version>   # edit lib/Resource.d.ts, then patch-commit\n```\n\nHistory: alchemy 2.0.0-beta.67 needed the patch (`lowering` alone reported 17\nerrors without it); upstream fixed the declaration by 2.0.0-beta.74 and the\npatch was deleted with that bump. The check above stays — the inconsistency\ncould regress in a future release.\n\n## The @alchemy.run/node-utils patch\n\n**Resolved — the patch was deleted with the beta.74 bump**: alchemy no longer\nships a file-lock module at all (`@alchemy.run/node-utils` 2.x exports only\n`ignore`), so there is nothing left to patch. The history and the standing\ncheck below stay, because the property it protected still matters.\n\nThe patch was\n[alchemy-run/node-utils#6](https://github.com/alchemy-run/node-utils/pull/6)\n(\"fix(lockfile): scope exit hooks to owned locks\"), vendored against\nnode-utils 0.0.5. Without it, `lib/lockfile.js` called `exitHook(...)` at module scope, so merely\nimporting `alchemy` registered a SIGINT, a SIGTERM, and an `exit` listener on\nthe process. Composer's commands run inside the Prisma CLI engine, and the\nengine owns the whole signal policy: the first Ctrl-C aborts the command and\nwaits for teardown, a second one force-exits. A stray SIGINT listener that\ncalls `process.exit(130)` on its own pre-empts that, killing the process while\nthe engine's cleanup is still running. The engine's family test suite asserts\nthat after a composer command's config evaluation the engine is the sole\nSIGINT/SIGTERM listener, and that assertion is what fails if a stray listener\nis ever reintroduced.\n\nOn every alchemy bump, re-run the standing check (the CLI's signal-listeners\ntest suite runs the same probe):\n\n```bash\ncd packages/9-public/composer-prisma-cloud && node --input-type=module -e 'const c=()=>process.listenerCount(\"SIGINT\")+process.listenerCount(\"SIGTERM\");const b=c();await import(\"alchemy\");await import(\"@alchemy.run/prisma\");console.log(c()-b,\"listeners registered by a bare import (must be 0)\")'\n```\n\n## Keeping the regression check honest\n\n`scripts/check-npm-effect-resolution.mjs` has three shapes: two healthy\ninstalls and one adversarial tree where alchemy resolves an `effect` we did not\npin. Two things about it are easy to get wrong after an upgrade:\n\n- **Do not assert the presence of a specific combinator.** That only ever stood\n  in for \"alchemy can run on this `effect`\", and it breaks the moment upstream\n  removes it for good reasons. `importAlchemy` answers the same question\n  directly: it imports alchemy's root, `Output`, `Provider` and `Stack` entries\n  from the installed app, which must succeed in the healthy shapes and fail in\n  the adversarial one.\n- **`WRONG_EFFECT` must stay a published version other than the pin.** The\n  adversarial shape used to depend on a release whose peer sat *above* our pin;\n  that stopped existing once the pin reached the newest beta, and the shape\n  quietly stopped being adversarial. It now sets the version with an npm\n  `override` instead, so it does not depend on what the registry publishes.\n\n## Gotchas\n\n- **A clean install before believing a failure.** Switching branches around a\n  dependency change leaves stale `node_modules` that produce failures unrelated\n  to the diff. `rm -rf node_modules && pnpm install` before diagnosing.\n- **Compare against `main` before blaming the upgrade.** Some suites fail only\n  under the fully parallel `turbo run test` and pass in isolation, on `main`\n  too; and `@internal/streams` reports a large pre-existing typecheck error\n  count from a third-party package's own source.\n- **`pnpm dedupe` after the pins move**, so stale peer-resolution keys do not\n  linger in the lockfile — but commit it separately, since it touches\n  resolutions beyond the ones being upgraded.\n- **`@prisma/composer`'s `dependencies.effect` must stay an exact version.**\n  `check:npm-effect-resolution` reads it and fails on a range.\n\n## What this skill does NOT do\n\n- **Decide when to upgrade.** alchemy is pre-1.0 and moves fast; this is the\n  procedure, not a schedule.\n- **Upgrade unrelated dependencies.** Keep the constellation bump its own\n  change so a deploy regression has one obvious suspect.\n- **Publish.** See [`publish-npm-version`](../publish-npm-version/SKILL.md).\n\n<!-- File: skills-contrib/upstream-alchemy-distilled/SKILL.md (Tokens: ~6389 | Category: anthropic-skill) -->\n---\nname: upstream-alchemy-distilled\ndescription: >-\n  How Prisma Composer, the Prisma Cloud target, Alchemy's Prisma provider (`@alchemy.run/prisma`), the Distilled Prisma SDK (`@distilled.cloud/prisma`) and the Prisma Management API (prisma/pdp-control-plane and its OpenAPI spec) depend on each other, and how to get a change through alchemy-run/alchemy or alchemy-run/distilled as an outside contributor without the maintainers rewriting or rejecting it. Use this whenever work will change or plans to change either upstream repository, how a `Prisma.*` Alchemy resource behaves or what it accepts (as opposed to how Composer uses it), the generated Prisma SDK, or a Management API behaviour that Composer's deploy depends on; whenever a Prisma pull request is open in either upstream repository; and to decide which repository a change belongs in before any code is written, even if the request only says \"the provider\", \"the SDK\", \"upstream\" or \"the Alchemy PR\". For moving Composer to a new Alchemy release, use `upgrade-alchemy-effect` instead.\n---\n\n# Changing Alchemy and Distilled from Prisma's side\n\n## Audience\n\nAn agent or engineer on the Prisma side whose work needs something from Alchemy's Prisma provider or the Distilled Prisma SDK. Both repositories belong to the Alchemy team. We are outside contributors there, and we maintain only the Prisma parts.\n\nIf you are about to edit a file in either repository from a Composer session, stop and read \"Work inside their repository, in its own session\" first.\n\nWhy this skill exists: between May and November 2026, Prisma's pull requests to these two repositories drew dozens of objections, rewrites and rejections from the maintainers, and several of their contributor rules were written within hours of one of ours. Almost all of it came from a few causes: working without their guidance loaded, inventing where they wanted a copy of an existing pattern, putting a change in the wrong repository, and treating their repositories as ours.\n\n## The pieces\n\n- **Alchemy** is an infrastructure-as-code engine written with Effect. A program declares *resources*; Alchemy plans and applies them. Composer turns an app into Alchemy resources, and Alchemy runs inside the `prisma` CLI to deploy them.\n- A **provider** is a package of resources for one cloud. Alchemy's Prisma provider, `@alchemy.run/prisma`, holds the `Prisma.*` resources that call Prisma's API. A resource may also have **bindings**: the runtime client a deployed app uses to reach it.\n- **Distilled** generates a typed Effect client (an SDK) for each cloud from that cloud's published API description. A **patch** in Distilled is a small JSON file that corrects the description before generation. Nobody edits the generated code.\n- **PDP** is Prisma's platform, in the private repository prisma/pdp-control-plane. Its **Management API** is what all of the above call, and it publishes its own OpenAPI description.\n- Composer's **Prisma Cloud target** and its **lowering** are the code in this repository that map an app's nodes to provider resources. `docs/design/05-prisma-cloud/alchemy-lowering.md` and the glossary (`docs/design/03-domain-model/glossary.md`) define the rest.\n\n## The chain, and who owns each link\n\nChecked 2026-11-27. Each cell says where to check it again.\n\n| Link | Where it lives | Owner | How a change leaves it |\n| --- | --- | --- | --- |\n| 1. Management API | prisma/pdp-control-plane | Prisma | Deployed to production |\n| 2. OpenAPI spec | Published by the API itself (the mirror's fetch script has the URL) | Prisma | Changes when link 1 deploys |\n| 3. Spec mirror | A git repository the Alchemy team runs, named in Distilled's `.gitmodules` | Alchemy team | Copies the published spec on a schedule (its workflow file has the schedule; daily when checked) |\n| 4. Distilled Prisma SDK | alchemy-run/distilled, the Prisma package: generated code plus patches | Alchemy team; we contribute to the Prisma package | A pull request moves the mirror pin, regenerates, and adds or prunes patches |\n| 5. Alchemy Prisma provider | alchemy-run/alchemy, the Prisma package. Alchemy takes Distilled as a git submodule pinned to one Distilled commit (its `.gitmodules`) | Alchemy team; we contribute to the Prisma package | A pull request, then an Alchemy release |\n| 6. Composer | This repository. Versions are pinned in `pnpm-workspace.yaml` | Prisma | A pin bump, then a Composer release |\n\nEach link is built from the one before it. Composer is the exception to \"only talks to its neighbour\": it also uses the Distilled SDK's credentials type directly and calls the Management API itself for a few things, so a Distilled change can reach Composer without an Alchemy change, and Composer's Distilled pin has to match the one the provider depends on.\n\nWhat follows from this shape:\n\n- **Composer implements no Management API resources itself.** It composes the upstream provider's resources and writes its own only where upstream has none or no API exists behind them. That is a recorded decision: read `docs/design/90-decisions/ADR-0048-prisma-cloud-resources-come-from-the-upstream-alchemy-provider.md` before proposing anything that changes it.\n- **Composer depends on two Alchemy things**: the engine (`alchemy`) and the Prisma provider. A fault in the engine or in another provider is their code, not ours. Describe it to the operator as an issue to raise with them; do not fix it.\n- **Distilled reflects the published spec.** A patch states only what their current rule accepts as evidence (the spec, a real response, the provider's own docs or client). The maintainers' position, on one of our pull requests: \"you work at Prisma, if consumers of the api need to know ... that should go in the API, not a patch in our SDK that adds a value the spec doesn't have.\"\n- **Alchemy calls the cloud only through Distilled.** No hand-written client and no status-code checks in the provider. A missing operation or error type is a Distilled change.\n- **The spec's own markings travel down the chain.** For example, operations the spec marks experimental have been moved to a separate module of the SDK, which changes the imports of every provider file that uses them once Alchemy takes that version.\n- **A change moves only as fast as its slowest link.** The mirror has its schedule, each upstream pull request waits for a maintainer, and Composer can only pin a release or a preview build. Plan the order before starting and tell the operator how many upstream pull requests it means, counted by their rules. Each costs the maintainers a review. An instruction from our side to keep it to one does not change their rule: say what count their rules produce and why, before starting.\n- **Links 1 and 2 are the only ones we control.** When something is hard to express downstream, the cheapest correct fix is usually in our own API or spec.\n\n## Decide where the change belongs\n\nWork this out before writing code, from the top of the chain down. The first link where the needed fact is missing is where the change starts.\n\nWhichever case it is: before offering any opinion on how a platform resource should be modelled, read that resource's design documents in prisma/pdp-control-plane (its `docs/` folder). They define the lifecycle you will model. Code on its `main` is not the design, and states that look like defects, such as a resource that stays pending, are often intended.\n\n**The API must behave differently, or expose something it does not.** Start in prisma/pdp-control-plane. Ship to production, wait for the mirror, then a Distilled pull request, then an Alchemy pull request, then an Alchemy release, then Composer's pins. If the change would break the provider that is already released, ship it so the old behaviour keeps working, have the operator tell the maintainers before it ships, and remove the old behaviour only after an Alchemy release carries the new provider. The maintainers once discovered on their own that a platform change had broken a feature for every Alchemy user.\n\n**The API already does it and the spec says so, but the SDK is older than the spec.** A Distilled pull request that moves the mirror pin and regenerates; their repository has a skill for it. Check their `main` first, because maintainers regenerate too. A regeneration carries every spec change since the old mirror pin, not only the one you came for: say in the description what else it brings.\n\n**The API does it but the spec does not say so** (an undeclared error response, a field that can be null). Prefer fixing the spec in pdp-control-plane: we own it and every consumer benefits. The SDK still has to be regenerated from the new spec afterwards, by the maintainers' own regeneration or by ours, so check their `main` before opening one. A Distilled patch is for a gap we cannot close quickly, with the evidence their rules ask for.\n\n**The SDK's own runtime code for Prisma must change** (its credentials layer, a hand-maintained module in the Prisma package). A Distilled pull request of its own; by their rule it does not share one with a spec fix or a regeneration.\n\n**Only the provider's behaviour or shape must change.** An Alchemy pull request. A change to what a resource accepts or returns is breaking for every Alchemy user, not only Composer, and their conventions say how to mark and explain that. Composer's lowering and its local stand-in providers bind the same resource classes, so they change with it.\n\n**The Alchemy change needs Distilled code newer than Alchemy's pinned commit.** See \"The Distilled pin\" below before doing anything.\n\n**Only Composer needs something to be different.** First try to meet the need in Composer: build a different Layer, wrap the resource, or write a Composer-owned resource where the recorded decision allows one. An option added upstream to serve our embedding has been refused (\"The user shouldn't provide them. If they want to override them, they can construct a new layer.\"). Go upstream only when the need would exist for any Alchemy user.\n\n**You need an upstream change that is not released, or not merged, to check the Composer side.** Alchemy publishes preview builds of commits and of pull request heads. The `upgrade-alchemy-effect` skill covers pinning one and what it blocks.\n\n**It is none of these.** A change to Distilled's shared core or generator, or to Alchemy's engine, for a need only Prisma has, fits nowhere above; Distilled's written rule is that one provider's rule stays in that provider. Describe the need to the operator as a scenario and say which link you think it belongs to.\n\n## What is ours and what is not\n\nIn both repositories we own the Prisma package and its tests, docs and examples. Everything else belongs to the maintainers. Offering to do their upkeep is not a courtesy: it puts our name on changes to code we do not maintain, and it spends the operator's time and machine on work they do anyway.\n\nTheir guidance (as read in November 2026) is written for their own agents, who own the whole repository. So it tells its reader to do some things that an outside contributor should not do unasked. On these, the limits here hold, because each comes from what happened when we did it. If their guidance ever addresses outside contributors directly on one of them, theirs wins and this skill needs a fix.\n\n- **Moving the Distilled pin past our own change.** Their instruction to move it to the merged commit we follow as written. Moving it further, or testing what a move does to other providers, is theirs. See the next section.\n- **Checking the whole repository.** Their guidance says to type-check the whole workspace before a commit. Run the type check for the Prisma package and the test files your change touches. Their CI checks everything else on the pull request, so read it. A whole-workspace run on the operator's machine reports errors in other people's code that we will not fix.\n- **Opening early drafts that carry a status report.** Their own agents do this for work in progress. Our drafts have been finished by a maintainer, merged before we were done, or left to rot. Open a pull request when the work is complete.\n- **Rebasing at checkpoints.** Once a branch has a pull request, merge their `main` into it and never force-push: maintainers push to our branches, and a force-push discards their commits and their place in the review.\n\nAlso not ours: other providers' code, shared core, the generator, the engine, repository-wide configuration, and the lockfile beyond what our own dependency change requires.\n\nWhen a previous session's handover lists upstream work, check each step against this section before doing it. A handover is a predecessor's plan, not the operator's approval. That covers its working copies and its open pull requests too.\n\n### The Distilled pin\n\nAlchemy pins one Distilled commit for the whole repository. An Alchemy change that needs newer Distilled code cannot build until that pin includes it.\n\nTheir skill for provider work tells its reader to land the Distilled change first, then move the pin to the merged commit and commit it. We follow that as written, without asking first, until a maintainer tells us otherwise (the operator's decision, 2026-11-27): the move is from one of their commits to another of their commits, and it is what their own guidance asks for. If a maintainer does say otherwise, do what they say, and add it to this section with its date.\n\nWhat stays theirs is everything beyond that one step. Move the pin to the exact commit our Distilled change merged as, and nothing later: when one of ours moved it further, it pulled in other providers' SDK changes and broke two of their type checks, and a maintainer re-pinned it himself. Do not test or fix other providers against the new pin. A pin pointed at a commit that exists only on our fork cannot be fetched by anyone else, so it can never merge.\n\nThese steps apply the same way to a pull request that is already open.\n\n1. Open the Distilled pull request complete. Build and test the Alchemy change locally by checking the Distilled branch out in your working copy of the submodule without committing the pointer, and keep it on a fork branch with no pull request. Their rules ask a breaking Distilled change to link the Alchemy change that adapts to it: link the fork branch and say its pull request opens once the Distilled change has merged. An Alchemy pull request that cannot build is unfinished work, so it is opened early only if a maintainer asks for it, and then as a draft that says so.\n2. Once the Distilled change merges, move the pin to that exact merged commit, in a commit of its own, and say so in the description with the commit's hash. If the pin has to pass over other Distilled commits to get there, check that the Prisma package still builds and its touched tests pass, and name in the description anything in that range that changes the Prisma SDK.\n3. Then open the Alchemy pull request. If their CI fails in other providers because of the pin, report that to the operator; do not fix other providers.\n4. A pull request that already carries a pointer to our fork is repaired with a new commit that restores their pin, never a force-push.\n\n## Work inside their repository, in its own session\n\nDo not edit an upstream repository from a clone inside a Composer worktree, and do not send subagents from a Composer session to work there. An agent gets a repository's instructions in full only when its session starts in that repository. From anywhere else it gets Composer's rules plus whatever fragments of theirs it happens to search for. That is how a reviewer came to judge Alchemy code against Composer's review checklist, and how Distilled's contributor rules were first read one minute before a pull request was opened.\n\n**How.** Start a new agent session whose working directory is a checkout of the upstream repository, with whatever your harness offers for that, or ask the operator to open one and hand them the brief to paste as its first message. If you can do neither, stop and ask; a subagent pointed at the folder is not a substitute, because it inherits this session's instructions.\n\n**Where.** A clone of the fork we push from, outside every Composer worktree, where the operator keeps such clones (ask once). One checkout per agent: the installed dependency tree is shared state, and two agents in one checkout have broken each other's runs.\n\n**Distilled is its own repository.** Alchemy vendors Distilled as a submodule and its own guidance has its agents patch and regenerate there. For us a Distilled change runs in a session started in a Distilled checkout, so Distilled's contributor rules are loaded. Do not install dependencies inside Alchemy's copy of Distilled: Alchemy's workspace supplies them, and a second install there has broken the checkout.\n\n**Work already in the wrong place.** If a predecessor left clones with commits inside a Composer worktree, move the work, do not continue it there: push its branch to the fork and start the upstream session on that branch. If that branch already has a pull request, push the unfinished work under a new branch name instead, so nothing unfinished lands on a branch a maintainer may merge.\n\n**\"Just do it here.\"** A message that hands you a clone inside the worktree, or says \"do that\", was written before the operator heard the concern, so it is not yet their decision. Say once what goes wrong without their instructions loaded, offer to write the brief for an upstream session, and ask. Then do what they decide. If they decide on in place, read that repository's guidance in full by hand before touching anything, and say in your report that it was done that way.\n\n**Reading is not editing.** A Composer session may read upstream source, guidance, issues and pull requests to work out which link a change belongs in. It does not edit there and does not propose a resource's shape.\n\n**Two repositories, two sessions.** When a change needs both, the Composer session coordinates: the Distilled session first, then the Alchemy session against the Distilled branch. Record in the project's plan where each checkout is and which session owns it, so a successor does not ask the operator again.\n\n**What stays in the Composer session:** what the work is for, what Composer needs from upstream, the project record under `.drive/`, and the brief. It does not recommend a resource's shape to the operator: what an upstream resource looks like to an Alchemy user is proposed by the upstream session, after its reading, and goes to the operator before it is built. A recommendation made from the platform's side alone has had to be reversed once the existing Alchemy pattern was read.\n\n**The brief** for the upstream session says:\n\n- What the change is for, and the design as our best effort: the purpose is fixed, the mechanism is open to challenge against their code and conventions.\n- Where the platform's design documents for the resource are, and that it reads them before modelling a lifecycle.\n- The absolute path of this skill's folder, and that it reads `SKILL.md` there. Composer's skills are not installed in their repository.\n- The limits in \"What is ours and what is not\".\n- That a change to what users declare or see goes back to the operator before it is built.\n- That rules meant for pull requests in our own repositories do not carry over: our description style, any line naming the agent, auto-merge, and merging it ourselves. Upstream, the maintainers merge. An independent review before the pull request opens is still worth having, judged against their guidance and not our own review checklist.\n\n**The first things the upstream session does**, before any design opinion or code:\n\n1. Read the repository's agent guidance in full, not by searching it: the root instruction file, what it links for outside contributors, the pull request template if there is one, and the repository's own skills for the kind of change in hand. These files change often. They are the authority on how code, tests, names, commits and descriptions look in their repository, and they win over this skill on all of that.\n2. Find where the repository already does the same job (another provider's resource of the same kind, a binding, a test fixture, a credentials layer) and read it. Copy its names, shape and mechanism.\n3. Search their open issues and pull requests for the same problem. We once built something they already had an open issue for, and they shipped their own design within days.\n4. Check that their `main` has not already fixed it, and check again each time you merge their `main`.\n\n## What the maintainers hold to\n\nThese have held across the record so far. Each has its reason, so you can judge a case their files do not cover.\n\n- **Follow what exists; invent nothing.** They value a consistent repository over a locally better idea (\"I prefer the repo to be consistent\"; \"This isn't something we typically do\"). A concept, name, option or branch that no other provider has will be rewritten. When you believe a departure is right, say in the description why the existing way is not enough, before they ask.\n- **A resource is not finished when it deploys.** They have expected its runtime bindings, and for compute an Effect-native form, in the same piece of work. Find out from their guidance what the resource kind requires and count it before telling the operator the size.\n- **Alchemy provider changes are proven by deploying real resources.** No fakes, mocked responses or direct lifecycle calls. Our tests were rewritten as live tests on six pull requests, five of them by the maintainers' own commits, and the live versions found provider bugs on at least four. A failure the real platform cannot be made to produce comes from a fixture that misbehaves, or is not tested. Distilled's testing rules are different; read each repository's own.\n- **Live tests need a test account.** Ask the operator for a token to a workspace used only for tests, and where it is kept; never print it; get it before the pull request opens. Do not assume a deploy token you already have points at such a workspace. Their guidance has an account-wide teardown for leaked test resources. Run it only against that test workspace, and only with the operator's yes.\n- **A provider leaves alone what the stack did not declare or create.** Omitted props mean \"not managed\", not \"reset to a default\". A resource the provider finds but cannot prove it created is not owned until the user adopts it. Nothing a provider provides may change what other providers in the same stack see.\n- **Effect throughout**, in source, docs and examples alike, because examples teach users.\n- **One change per pull request, by each repository's own definition.** Distilled's is written and narrow: a spec fix and a runtime change are two. A correct fix of ours was lost there because it shared a pull request with a rejected feature, and a description that says it breaks a rule on purpose is read as exactly that. In Alchemy a resource with its bindings, tests and docs has been one change, and one piece of work opened as three pull requests was joined into one by its author soon after.\n- **Descriptions are short and say what the user can now do.** In both, the pattern they kept when rewriting ours was one plain sentence, then a code or diff block, a few bullets, and a marked breaking change. They cut status reports, test logs, file lists, long justifications and agent name lines. Use the format their current guidance and template give; the two repositories differ (in November 2026 Distilled had a template with a checklist and required a signed note on anything an agent wrote, while Alchemy forbade checklists, test sections and large headings), so do not carry one's format to the other. Have a reader with none of our context check the description against their conventions before it goes up.\n- **Names are theirs.** Name a resource after the platform's own product name. A name suggested as a question is a request: act on it or answer it in the next push.\n- **Their decision is the decision.** When a maintainer says they are solving it another way, ask how to fit into their design, then close ours with a line saying why, or redo it on theirs. Restating our case has not changed an outcome so far, and they have shipped their own version within hours. A real technical reason, stated once and plainly, has been accepted.\n\n## How their pull requests move\n\nPlan around what they do, not around what a pull request's state suggests.\n\n- **So far no maintainer has submitted an approving review on one of ours.** They comment, push commits to our branch, rewrite the description, and merge. Keep maintainer edits allowed.\n- **A draft is a signal, not a lock.** A maintainer has taken one of our drafts out of draft and merged it minutes later, at a commit we meant to add to. Every commit pushed to a branch that has a pull request must be safe to merge as it stands. If more is coming, it is in the pull request before it opens, or it is a separate change. Unfinished work lives on a fork branch that has no pull request; pushing there is yours to do.\n- **They read, run and fix drafts,** and do not chase. Good small changes have merged in under an hour; ones that needed work waited weeks with one comment or none.\n- **Keep it mergeable and green.** Merge their `main` when it conflicts. Take their side for every file our change does not own, then check the diff for files we never meant to touch; a merge of ours once silently deleted features from their `main`. Fetch before every push.\n\nSomeone has to know when a maintainer acts. Watch each open upstream pull request for comments, pushes, state changes, merges, failed checks and conflicts with their `main`, with whatever your harness offers. Write the watched pull requests into the project's plan, so a session that restarts finds them and sets the watch up again (background commands do not survive a restart). Tell the operator who did what, including when a merge happened with no review.\n\n## Speaking to the maintainers\n\nA maintainer here means someone who merges in that repository. Check who a commenter is before weighing what they say.\n\nOpening, editing, marking ready, commenting on or closing an upstream pull request speaks to another team in the operator's name. Those steps are the operator's, or need their explicit yes each time. Never turn on auto-merge or merge upstream.\n\n- Find out which GitHub account your shell acts as before planning these steps. Work out the whole sequence of operator steps once, in order, as commands that are safe to run twice and that say where to run them, and ask once.\n- After any GitHub write that reports an error, read the state back from GitHub before saying what happened.\n- When a maintainer asks or requests something, bring the operator the question and a finished draft answer in one message the same day, in the format their rules require for text an agent wrote. A question of ours that went unanswered got its pull request closed, and others waited a week or more. Where the request is a code change inside the agreed design, such as a rename, push it without waiting and say so in the draft. Do not post it yourself.\n\n## When the operator's request and this skill pull apart\n\nThe operator may ask for the very thing this skill warns against: finish it in the clone here, keep it to one pull request, make sure nothing else breaks, defend the option, add it to the SDK anyway. They may not have the earlier incidents in mind when they ask. Say once, briefly, what happened the last time and what you would do instead, and ask. Their answer decides anything on our side: where the work is done, how much we check, what we propose. It does not change the maintainers' rules or decisions. Where the request is something a maintainer has already refused, the next step is the operator raising it with them, not a pull request that tries it again.\n\n## After it merges\n\nA merged upstream pull request changes nothing in Composer until Alchemy releases and Composer's pins move. The `upgrade-alchemy-effect` skill covers the bump. Update the project's plan in the Composer pull request that consumes the release, and tell the platform's owners when a removal there was waiting on the provider.\n\n## Before asking the operator to open or mark ready an upstream pull request\n\n- The work was done in a session started in that repository, with its current guidance read in full in that session.\n- It touches only the Prisma package, or each file outside it copies an existing shape and is explained in the description.\n- The Distilled pin is at the exact commit our Distilled change merged as (or where a maintainer said to put it), in a commit of its own, and nothing points at a commit that exists only on our fork.\n- Alchemy: every behaviour is covered by a test that deployed for real, and you ran the ones your change touches. Distilled: each patch has its evidence.\n- It is one change by that repository's definition.\n- The description follows their current format, and a fresh reader has checked it against their conventions.\n- Nothing in it is unfinished, and every commit on the branch is safe to merge today.\n- The pull request is written into the project's plan, and a watch on it is in place.\n\n## What this skill does not cover\n\n- Moving Composer to a new Alchemy release or a preview build: `upgrade-alchemy-effect`.\n- How to write a provider, a patch or a test in their repositories: their own guidance and skills, loaded by working there.\n- Reviewing an outside contributor's pull request to our own repositories.\n- Design decisions inside Composer or the platform: each repository's design documents.\n\n<!-- File: skills/prisma-composer-core-concepts/SKILL.md (Tokens: ~12105 | Category: anthropic-skill) -->\n---\nname: prisma-composer-core-concepts\nmetadata:\n  library: \"@prisma/composer\"\n  library_version: \"0.41.2\"\n  version: 2026.9.1\ndescription: >-\n  Use when deploying or managing an app that uses Prisma Composer\n  (`@prisma/composer`): wiring its services and Modules, running it locally,\n  testing composed services, or standing up / tearing down an environment.\n  Triggers on \"prisma composer\", \"@prisma/composer\", \"prisma app\",\n  `prisma deploy`, `prisma dev`, `compute()`, `appRoot()`, `module()`, `contract()`,\n  `service.load()`, `mockService`, `bootstrapService`.\n---\n\n# Prisma Composer core concepts\n\nA **Prisma App** is a tree of typed declarations composed in TypeScript and\nhanded to the `prisma` CLI, whose two main Composer commands are `prisma deploy`\nand `prisma dev`. Removing a whole app is `prisma project delete`. Removing\none environment and reading logs are not commands; they are the `destroy` and `log`\noperations of `@prisma/composer/control`, called from a script.\nThis file covers structures, hierarchies, relationships, and workflows: the\nconcepts you cannot observe from the code or the CLI's help output. It is not\na CLI reference; discover each command's flags with `prisma <command> --help`\nrather than inferring them. The Prisma platform moves fast, so treat this file as the\nstable conceptual core and find current, fuller documentation at\n<https://www.prisma.io/docs>. For working code, read `examples/` in the\nprisma/composer repo.\n\nTwo principles govern everything and are binding\n(`docs/design/01-principles/`):\n\n1. **Your code never reads environment variables.** Dependencies, configuration,\n   credentials, and the port all arrive through the service node, typed.\n   `process.env` is never the answer.\n2. **Composer never bundles or transforms your code.** You build with your own\n   bundler; the framework assembles the built output by deterministic steps\n   and hands it to the configured deploy target.\n\n## Declarations are data\n\nEverything you author is a declaration: plain data describing a piece of the\napp, executing nothing when imported. Three node kinds exist:\n\n| Kind | Declared with | Purpose |\n| --- | --- | --- |\n| Service | `compute()` | A running unit of your code; atomic, Composer sees only its boundary |\n| Resource | `rawPostgres()`, `bucket()` | A stateful managed dependency |\n| Resource: public URL | `publicUrl()` | Makes one service reachable from the internet at one hostname; depends on the service's exposed HTTP interface and exposes nothing |\n| Module | `module()` | A grouping boundary; runs no code of its own, depends on and exposes typed interfaces; its builder receives `deps`, `input`, `environment` and `provision` |\n| App root | `appRoot()` | The outermost module, the entry's default export; no `deps` or `expose`, and nothing can provision it; its builder receives `input`, `environment` and `provision` |\n\nNodes connect through typed **interfaces**: `deps` declares what a node depends on, `expose` declares what it exposes. Wiring happens in a Module's builder via `provision()`, and the app root, built with `appRoot()` and handed to the CLI, is the App:\n\n```ts\n// module.ts\nimport { appRoot } from '@prisma/composer';\n\nexport default appRoot('store', ({ provision }) => {\n  const catalog = provision(catalogModule);\n  provision(storefrontService, { deps: { catalog: catalog.rpc } });\n});\n```\n\nBecause interfaces are typed, **the compiler verifies every wire**. A dependency wired to the wrong producer, a missing RPC handler, a literal input value of the wrong shape: all of it fails `tsc`, not the deploy. Values from outside the code are the exception: a root input field exists only at deploy, and a platform variable only on the platform, so a schema refinement the type does not carry and a missing platform variable a service needs surface as early deploy-time refusals instead (see Two channels below). Typecheck, then build, then deploy; don't use the cloud to find out whether the wiring is correct.\n\nComposer itself is target-agnostic: `@prisma/composer` carries authoring, testing, and the CLI, coupled to no platform. A deploy target is an extension registered in the deploy config; `@prisma/composer-prisma-cloud` is the Prisma Cloud target and the one this skill's deploy sections assume. Its root exports `compute`, `rawPostgres`, `bucket`, `publicUrl`, `variable`, `generatedParam` and `serviceOrigin`; the ORM vocabulary (`postgres`, `dataContract`) lives under the `/orm` subpath, alongside the shared `/cron`, `/storage`, `/streams`, `/auth`, and `/email` modules. These are the only two Composer packages a basic Prisma Cloud app needs, and nothing installs them for you: a fresh project starts with neither, so add both as dependencies first. An extension adds its own `prisma-composer-*` package alongside them. Compose an existing Module before implementing a capability yourself; wiring one in is a couple of lines.\n\nWithin the entry graph (everything reachable from `module.ts`), write\nrelative imports with explicit `.ts` extensions (`./service.ts`, with\n`allowImportingTsExtensions` in tsconfig): that form resolves everywhere.\n`prisma deploy` and `prisma dev` also map `./service.js` and extensionless\n`./service` to the `.ts` source, but other tools may not.\n\n## The service node is the only doorway\n\nYour runtime code receives everything from the service declaration it\nimports:\n\n1. `service.load()`: dependencies (typed RPC clients, database bindings).\n2. `service.input()`: the whole input as one schema-validated object;\n   credentials in it are redacting `SecretString` boxes.\n3. `service.port()`: the reserved port to bind (default 3000).\n\nA service declaration is pure data; the server entry is what your build\nproduces and the platform boots:\n\n```ts\n// service.ts\nexport default compute({\n  name: 'auth',\n  deps: { db: rawPostgres() },\n  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),\n  expose: { rpc: authContract },\n});\n\n// server.ts\nconst { db } = service.load(); // { url }: you construct your own client\nconst handler = serve(service, {\n  rpc: { verify: async ({ token }) => ({ ok: token.length > 0 }) },\n});\nBun.serve({ port: service.port(), hostname: '0.0.0.0', fetch: handler });\n```\n\nThe consumer declares `deps: { auth: rpc(authContract) }` and gets a typed\nclient back from `load()`.\n\n## Two channels: dependencies and input\n\n| The value is… | Declare | Provide | Read |\n| --- | --- | --- | --- |\n| produced by another node | `deps: { db: rawPostgres() }` | wire at `provision()` | `load()` |\n| anything else (config or credential) | one field of the `input` schema | bind at `provision()`: literal, root input field, platform variable node's value, or a `resolve()` value | `input()` |\n\nThe service declares its whole incoming configuration, plain values and credentials together, as **one [Standard Schema](https://standardschema.dev)** (arktype is the house choice). A credential is a field typed as `secretString()` from `@prisma/composer/arktype` (or `@prisma/composer/zod` for a Zod schema; the app installs `arktype` 2 or `zod` 4 itself, and Composer uses that copy); conditional legality (\"no stripe key unless billing is on\") is an ordinary schema union. The binding at `provision()` mirrors the schema's shape.\n\nA value you supply, rather than write in code, arrives in one of two ways:\n\n- **A value the deploy reads** is a **root input field**: a field of the app root's `input` schema, filled by the `config` adapters (by default the deploying shell), checked by the root's schema before anything is created. The root passes it on by name. Only these can be listed in `resolve()` or put in a resource's props.\n- **A value the service reads at boot** is a **platform variable node**, provisioned in the app root: `provision(variable({ name: 'EMAIL_FROM' }))` for a plain value, `provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }))` for a secret. `provision()` returns the value with `id`, the node's address, on it; pass it down through module inputs to the services that read it. The node names the variable and never carries its value; the operator sets the value on the platform.\n\n```ts\nexport default appRoot('shop', { input: type({ EMAIL_FROM: 'string' }) }, ({ input, provision }) => {\n  const stripeKey = provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }));\n  provision(billing, { input: { from: input.EMAIL_FROM, stripeKey } });\n});\n```\n\n**Only `appRoot()` can provision a platform variable node.** A variable's name is one space per deployed app, and the root is the app. In a `module()` body (a nested module or a `module()` root) `provision(variable(…))` fails to compile, with an error naming `appRoot()`. A module that needs the value declares a field in its `input`. The node creates nothing on the platform and stays out of the application topology and the deploy report; the loaded graph lists it and, in `graph.valueReads`, each service that reads it. Its default id is the name in camel case (`EMAIL_FROM` is `shop.emailFrom`); two nodes whose names give one id fail with an error naming both, so pass `{ id }`.\n\nRules that bite:\n\n1. **Secretness is checked by the binding's type and by the deploy.** A `provision()` binding, a service's or a module's, is typed from the schema: a literal or a `SecretBox` where the schema expects `SecretString`, or a platform secret's value in a text field, fails to compile, and the deploy refuses it where the schema has no types. An ArkType schema with a `SecretString` field cannot also transform its input: a morph anywhere in it (`'string.trim'`, `.pipe()`, `field(type('string.integer.parse'))`) or `'+': 'delete'` copies the input, the copied secret loses its value, and the deploy refuses it. Transform in the service code instead; a Zod schema keeps the box.\n2. **A plain platform variable's value is known only at boot: text, or the type its `schema` declares.** Bind it to a field wrapped with `field()`. A platform variable's value goes into a field of an `input` only. A compute service has one per-key param, the reserved `port`, which takes a literal or a root input field and no source, because the deploy needs the port before the service exists; every other value is a field of its `input`. A field of a narrower type, such as `email()`'s `deliveryMode`, takes a root input field declared with that type instead, for `email()` from the exported `emailDeliveryModes`; the deploy reads a root input field from the app configuration on every deploy and writes its value into the input document. A platform secret fits a `secretString()` field only. A platform variable's value always lives on the platform. The operator sets it there with `prisma project env add 'NAME=<value>' --project <id> --role production`. Use `--role preview` for every preview environment, or `--branch <environment>` for one. The deploy does not copy local values (`.env`, the shell) to platform variables. The deploy fails only when a variable that a service's schema requires has no value. The error names the variable and the command that sets it. The other variables with no value print under `Platform variables with no value:`. Prisma Cloud reports a service that exits at boot as running and promotes it; read the error with `prisma service logs <service>`.\n3. **The schema decides whether a field may be absent.** A field bound to a platform variable that is unset or empty is left out at boot. That is allowed only if the schema allows it, for example with an optional field or a union member. An optional root input field that the adapters do not supply is left out at deploy. The deploy report prints the serialized input document (each secret shown as `$platform VAR`) and every key that resolved absent. On Prisma Cloud the deploy writes the input document into the service's artifact, not into a `COMPOSER_*` variable, so it is not limited to a variable's 8 KB, and a changed document redeploys exactly that service.\n4. **The reserved `port` is outside the schema.** Read it through\n   `service.port()`, never `process.env`. The framework also exports `PORT`\n   for Next.js standalone, which binds it itself.\n5. **A Module passes a secret on without learning the platform name.** Declare a `secretString()` field in the Module's `input` and pass `input.<field>` on as a binding leaf; the app root provisions `variable.secret({ name: 'NAME' })` and binds its value. A module has no `params` or `secrets` slots: `module()` and `provision()` refuse both, naming `input`. A service's `params` stay.\n6. `input.apiKey.expose()` is the only way to a secret's value; the box\n   redacts everywhere else (logs, JSON, errors).\n7. **Platform variable names are upper case**: `^[A-Z][A-Z0-9_]*$`. `COMPOSER_…`, `DATABASE_URL`, `DATABASE_URL_POOLED`, `PORT`, `PATH` and `HOME` are reserved, each name is declared by one node, and one name cannot be both a platform variable and a root input field. A node's value bound as a service's whole input is refused too. Each fails before anything is created, naming the variable and the addresses.\n8. **A field bound to a plain platform variable, `serviceOrigin()` or a plain `generatedParam()` is wrapped**: `field(type('string'))`. At deploy the schema sees a pointer, and a plain `'string'` field refuses it: a compile error in a service's or a module's binding, and a deploy error where the schema has no types. `service.input()` and `mockService`'s input double read the field as its inner type.\n9. **A platform variable holds text; `schema` says what the text means.** `variable({ name: 'SMTP_PORT', schema: type('number') })` (any Standard JSON Schema library: ArkType, Zod) gives a runtime value of type `number`, which fits `field(type('number'))` and not `field(type('string'))`; without `schema` the value is the text and the reverse holds. An object schema fits a `field()` of the same object type. A schema that accepts only text gives the text exactly, untrimmed; any other schema reads the text as JSON (`587`, `true`, `{\"host\":\"h\"}`, `null` under `number | null`). A schema that accepts both, such as `string | number`, `z.unknown()` or `string | null`, is refused when the root body runs; for an optional text variable declare the text type and make the service's field optional. `variable.secret()` takes no schema.\n10. **Boot decodes and validates the text against the variable's JSON Schema, then the service's schema runs.** A failure fails boot, not the deploy: read it with `prisma service logs <service>`. Messages name the variable and never hold its text: `The platform variable \"SMTP_PORT\" does not hold a number. Its schema is not a text type, so its text must be JSON, such as 587.`, `... does not fit its schema: it fails \"minimum\" at #/minimum.` A whole number above 9007199254740991 is refused: keep an identifier as text. A value nested more than 100 levels deep is refused too. `prisma dev` runs the same check before any service starts and adds `prisma dev cannot start, because service \"<address>\" reads it.`\n11. **No library code runs on a variable's value; only the JSON Schema the library emits is checked.** A transform or a default the JSON Schema shows (`.transform()`, `string.numeric.parse`, a default inside an object) is refused at the root body; put defaults on the service's field. ArkType throws for `.narrow()` and `string.url`. Zod drops `.refine()`, and `.trim()`, `.toLowerCase()`, `z.coerce`, `z.preprocess()` and `.catch()` are accepted and do not run. An undeclared object key is not removed (`z.object()`, ArkType `'+': 'delete'`) and reaches the service's field. Regex flags are dropped and a pattern must be valid under the `u` flag (no `\\-` outside a character class). `format` is checked for `date`, `time`, `date-time`, `duration`, `uri`, `uri-reference`, `uri-template`, `url`, `email`, `hostname`, `ipv4`, `ipv6`, `regex`, `uuid` and the three JSON Pointer formats; others, such as `z.jwt()`, are unchecked. `z.number().optional()` does not fit `field(z.number())`: make the service's field optional. A hand-written schema that contradicts itself fails every boot. Put any other check or change in the service's own schema.\n\n### Values that differ per environment\n\nThe graph is the same in every environment; only configuration may differ.\n\n- A module declares `input` (one Standard Schema) as a service does; `provision(module, { input })` binds it, and the body receives `input`, a dictionary of values: it passes each field on by name into a binding or, for a plain field, lists it in `resolve()`. Passing the whole `input` on fails to compile, and the deploy refuses it. A root's `input` is the app configuration, and a module's `input` takes every source a service's does.\n- `field(inner)` from `@prisma/composer/arktype` or `@prisma/composer/zod` wraps one field's schema (`field(type('string'))`, `field(z.string())`) so it also accepts a plain pointer, which is what a value known only at boot such as `serviceOrigin()` is at deploy. In the body the field is `Value<string | Pointer<string>>`: pass it into another wrapped field or a service's input, never a plain `string` field (compile error). A wrapped field holds the whole value one source supplies, which may be an object or array when a platform variable's schema says so, so `field(type({ host: 'string' }))` is fine. An ArkType default goes outside: `field(type('string')).default('x')`. Other schema libraries: `Pointer`, `PlainPointer`, `isPlainPointer()` (narrows to `PlainPointer`) and `isSecretPointer()` from `@prisma/composer`. Wrap every field of a reusable module's schema other than a `secretString()` field, unless a `resolve()` lists it; keep a root's fields plain. `field(secretString())` is wrong: it accepts a plain pointer into a secret field, and the service fails at boot.\n- `composer({ config: [...], secrets: [...] })` lists config adapters; each gets the environment's name and returns values, later wins by top-level key. Both default to `[environmentVariables()]` (the shell); a list you write replaces the default. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local`, later wins. The app configuration fills the root's input (under `prisma dev` it also gives each plain platform variable a service reads its value, under the variable's name); pass the root's input fields on by name, as every module does; its whole `input` would be the whole app configuration, by default every shell variable. The app secrets give `prisma dev` its secrets; a deploy reads them only to redact. It does not fill a platform variable from them, and never reads them as the root's input. Both import from `@prisma/composer/config`. Credentials (`PRISMA_SERVICE_TOKEN`) still come from the shell. `dotenv()` reads `.env`, `.env.local`, `.env.<environment>`, `.env.<environment>.local` through `dotenv-flow` (no `.env.local` for `test`); remove `import 'dotenv/config'` when you list it. Composer redacts the values under the names of the graph's platform secrets, in either list; the lists' other values are not secrets and print as they are, apart from values that look like credentials. Under `prisma deploy` the engine's output is redacted too; under `prisma dev` it is not yet.\n- A field exists only under a plain object: a path into a string, an array or a secret, such as `input.tags[0]`, fails the deploy naming the path.\n- A truthiness check such as `if (input.enabled)` is not caught: the field is an object, so the branch always runs, in every environment. A module's structure cannot depend on its input; to provision something only sometimes, let the parent decide whether to provision it.\n- The module body receives `environment`; `environment.name` is a value standing for the name `--environment` gave (`production` for `prisma deploy`, `dev` for `prisma dev` by default).\n- `resolve([deps], ([values]) => …)` from `@prisma/composer` returns a computed value; `fn` receives the dependencies' real values as one tuple.\n- A value is accepted as a leaf of a service's or a module's `input` binding, at any depth, as a service param (a deploy-time value only), as one of a `resource()` node's `props`, or as a public URL's `url`. Never as a provision id or a `deps` entry.\n- A value is opaque in the body: you cannot read, compare or branch on it. List it as a `resolve()` dependency instead.\n- Calling `provision()` inside `fn` fails the load: `fn` computes configuration, never graph structure.\n- `fn` is pure and synchronous and returns plain data (no `undefined`, Promise, value or source); a deploy and `destroy` both run it, in two processes. To retire an environment, keep its case in every `fn` until `destroy` for it has finished.\n- Sources are values. `resolve([input.X], ([x]) => …)` over a root input field receives its data. A dependency must be a deploy-time value: a platform variable's value, `generatedParam()`, `serviceOrigin()`, a field wrapped with `field()` and a `secretString()` field cannot be listed (a compile error saying so; for a field typed `unknown` or a cast, the deploy fails naming the field). Bind those directly; to compute with a field, declare it plain. For a different secret per environment, use one name with a different value on each environment.\n\n## Contracts and RPC\n\nAn RPC contract is the typed interface through which services communicate. It\nlives with the service that owns it, typed by any Standard Schema validator,\nand both provider (`serve()`, exhaustive over the contract's methods at\ncompile time) and consumer (`rpc(contract)`) reference the same value. Calls\ntravel as RPC over HTTP. Two behaviours are provisioned for you and must not\nbe reimplemented:\n\n1. **Service keys.** At deploy, Composer mints a distinct unguessable key per\n   consumer→provider binding; `serve()` returns `401` to anything else before\n   the handler runs. Nothing in your code declares it. Consequences: don't\n   build your own service-to-service auth, and don't `curl` a deployed\n   `/rpc/<method>` to check it works. An unwired caller always gets `401`,\n   which looks like a broken deploy and isn't. Debug through a consumer, or\n   locally, where nothing is enforced. Keys are per binding (one leaking\n   can't impersonate another consumer), service-scoped (any valid key\n   reaches every method; split services to gate separately), rotated only by\n   removing the binding or destroying the stack and redeploying, and stored\n   in deploy-owned `COMPOSER_*` variables you never hand-edit.\n2. **Idempotency and retries.** Every generated-client call carries an\n   `Idempotency-Key`; dropped calls retry with backoff, and `serve()` runs\n   one call per key, replaying the completed answer to late retries. Every\n   method is therefore safely retryable and no contract declares anything\n   about it (there is no \"is this idempotent\" flag; don't invent one). A\n   handler may take an optional third argument `(input, deps, ctx)` and read\n   `ctx.idempotencyKey` (`string | undefined`) if it needs exactly-once\n   beyond one instance's memory; most don't. Locally and in tests nothing is\n   provisioned, so `serve()` passes every call through: never supply a key\n   in test inputs.\n\n## Raw HTTP connections\n\nFor a server Composer does not generate (a reverse proxy's upstreams, a\nNext.js app, a static file server), import `rawHttp` and `rawHttpContract`\nfrom `@prisma/composer/http`. The provider declares\n`expose: { http: rawHttpContract }`; the caller declares\n`deps: { site: rawHttp() }`; the Module wires\n`provision(gateway, { deps: { site: siteRef.http } })`. `gateway.load().site`\nis `{ url, fetch(path, init) }`, where `fetch` resolves `path` against `url`.\nThe client never leaves its provider's origin by itself: `fetch` rejects a\npath that resolves to another host (`//other.example/x`, an absolute URL), and\nreturns redirects to the caller instead of following them, unless `init` sets\n`redirect: 'follow'`.\n\nComposer checks only that the provider declared an HTTP port: TypeScript and\nLoad reject a bare service ref or a port of another kind. The caller is\nresponsible for knowing the provider's paths, methods and headers. Raw HTTP\nhas no service key, retry or idempotency key; authentication, if needed, is\nthe app's. Each dependency shows in the application topology as a call, also\nthrough module boundaries; a URL passed as `input` (`serviceOrigin()`)\ndoes not, so declare a dependency for every service you call. The auth\nmodule's `api` port is a raw HTTP port: wire it with `rawHttp()`.\n\n**Public URLs.** A service is reachable from the internet only through a\npublic URL the app declares:\n`provision(publicUrl({ id: 'site', url, target: web.http }))`, where `id`\nsets the address (`shop.site`) and changing it replaces the URL, and where\n`web` exposes `http: rawHttpContract` (an RPC interface as `target` fails\n`tsc`; a module's forwarded HTTP interface lands on the service inside it).\n`url` is required and is one of two strategies: `publicUrl.prismaBuild()`\nserves at the service's `prisma.build` hostname and creates nothing;\n`publicUrl.hostname('shop.com')`, or the bare string `'shop.com'`, attaches\nthat hostname to the service as a custom domain. One hostname per public URL.\nA per-environment `url` is a `resolve()` value returning either strategy or a\nstring; anything else fails deploy and dev before any of the app's resources\nare created or changed. Before\na deploy names a hostname, the TXT record `_prisma-verification.<hostname>`\nand a CNAME to the platform must be published, or the deploy fails with the\nplatform's error (`domain-ownership-required` for the TXT record); don't\nwork around it, publish the records or use `publicUrl.prismaBuild()` there. A\nchange from a serving hostname to one that is not ready fails the deploy and\nthe old hostname keeps serving. `prisma dev` ignores a named hostname and\nwarns once per public URL that names a hostname. A service with no public URL is still reachable at\nits `prisma.build` hostname today.\n\n## Builds are yours\n\nYou build, the framework assembles. For a plain server process, `entry`\npoints at the ESM file your build produced. By default\n(`dependencies: 'bundled'`) deploy copies exactly that and never ships\n`node_modules`, so everything except runtime built-ins (`bun`, `bun:*`,\n`node:*`) must be inlined, or it fails at boot, not at deploy. Rules that\nbite:\n\n1. **Two services in one package means two separate builds**, one per entry.\n   A single multi-entry build splits shared code into a chunk neither output\n   contains.\n2. **A directory build uses `dir` + `entry`** (`dir` relative to the service\n   module, `entry` a file inside `dir`; `../` is an error). The tree is\n   copied verbatim, so the server must resolve siblings against\n   `import.meta.url`, not the working directory. The tree must contain no\n   symlinks: the packager rejects them, names the link, and assembly fails.\n3. **A build that leaves packages external sets `dependencies: 'external'`**\n   (either form). Deploy then traces `entry` and stages the installed\n   packages it imports, which can take minutes on a large build. Astro's Node\n   adapter, SvelteKit's `adapter-node` and React Router's server build leave\n   packages external by default. The default, `'bundled'`, copies exactly\n   what was built. A service that fails to start with\n   `Cannot find package 'x'` needs `x` bundled, or `dependencies: 'external'`.\n4. **Next.js**: `next build` with `output: 'standalone'` is the whole build;\n   `nextjs({ module, appDir })` names the app root. Any page or action that\n   calls `load()` needs `export const dynamic = 'force-dynamic'`, because\n   the runtime environment variables don't exist at build time and Next ignores\n   runtime env for prerendered routes. `prisma dev` needs no build for it: it\n   runs `next dev` instead (see Local development).\n5. **Always build before `deploy`, and before `dev` for a service without a\n   dev server.** Neither builds for you. `node({ ..., dev: ['bun', '--watch',\n   'server.ts'] })` gives a node service a dev server: `prisma dev` runs that\n   command (in the authoring module's directory, nothing appended; it must\n   listen on `PORT`) instead of the built `entry`.\n\nDeploy configuration is the `composer` section of `prisma.config.ts`, and\nnothing else. It names the entry module, the file whose default export is the\napp root (`entry`, relative to the config file; `--entry <path>` overrides it\nfor one run), and registers extensions (`prismaCloud()`, `nodeBuild()`,\n`nextjsBuild()` when the app has a Next.js service) and the deploy-state\nbackend (`prismaState()`):\n\n```ts\n// prisma.config.ts\nimport { defineConfig as composer } from '@prisma/composer/config';\nimport { nodeBuild } from '@prisma/composer/node/control';\nimport { prismaCloud, prismaState } from '@prisma/composer-prisma-cloud/control';\nimport { definePrismaConfig } from 'prisma/config';\n\nexport default definePrismaConfig({\n  composer: composer({\n    entry: './module.ts',\n    extensions: [prismaCloud(), nodeBuild()],\n    state: prismaState(),\n  }),\n});\n```\n\nThe commands find `prisma.config.ts` from the directory they run in, walking up\nto the repository root; the nearest file that declares `composer` wins, and its\nsection is used whole, never merged key by key. Only `entry`, `extensions` and `state`\nare allowed; any other key is an error. App code never imports the file.\n\nA separate `prisma-composer.config.ts` is no longer read, and the old setup is\nrefused, never silently ignored: `CONFIG.SECTION_MISSING` when no loaded\n`prisma.config.ts` declares a `composer` section, `CONFIG.FIELD_RETIRED` when\nthe section still has `configPath`, `CONFIG.FILE_RETIRED` when a\n`prisma-composer.config.*` sits next to the declaring `prisma.config.ts`; all\nthree under the CLI's `CLI.CONFIG_SECTION_INVALID`. `SECTION_MISSING` is fixed by\nadding the `composer` section to `prisma.config.ts`. `FIELD_RETIRED` and\n`FILE_RETIRED` are fixed by moving the old file's `extensions` and `state` into\nthe section, then removing `configPath` or deleting the old file.\n`@prisma/composer-cli/family` no longer exports `ComposerSection`; the\nsection's type is `PrismaAppConfig` from `@prisma/composer/config`.\n\n## Databases and migrations\n\nTwo kinds of Postgres dependency:\n\n1. **`rawPostgres()`**: the binding is `{ url }` and the app owns its client.\n2. **`postgres(...)`**: a Prisma-ORM-typed database. The binding is\n   `{ url, connection, client, clientWith }` (ADR-0040, ADR-0055): the raw\n   connection URL, the connection pool, the typed client Composer constructs\n   from your data contract lazily on first access, and `clientWith(options)`,\n   which builds a typed client with Prisma ORM runtime options. Queries go\n   through `binding.client` and are compile-time checked. Both `postgres` and `dataContract` import from\n   `@prisma/composer-prisma-cloud/orm`, not the package root. The app's\n   `package.json` lists `@prisma/orm-postgres` and the four ORM packages it\n   is built from (`@prisma/orm-framework`, `@prisma/orm-family-sql`,\n   `@prisma/orm-target-postgres`, `@prisma/orm-toolchain`), all at the exact\n   version Composer names, plus `pg`, `@types/pg` and `temporal-polyfill`; the ORM's packages are\n   peers of each other, so the app's list decides the one copy installed. One\n   `dataContract`-wrapped value (emitted from `contract.prisma` by\n   `prisma contract emit`) is referenced by both the dependency end\n   (`deps: { db: postgres(catalogData) }`) and the resource end, which also\n   names the `prisma.config.ts` path so the deploy's migration step can\n   reload the emitted `contract.json` and find `migrations/`, and the required\n   `targetRef`, the ref every deploy migrates the database to (below).\n   Client options never go on the dependency declaration. A contract that\n   uses an extension type (for example `pgvector.Vector(length: 1024)`)\n   needs the pack's runtime extension when the client is built:\n   `export const orm = db.clientWith({ extensions: [pgvectorRuntime] })`,\n   where `pgvectorRuntime` is the default export of\n   `@prisma/orm-extension-pgvector/runtime`; other runtime options, such as\n   `middleware`, go in the same object. Install the pack at exactly the\n   `@prisma/orm-postgres` version: the pack names the ORM's packages as\n   peers at its own version, so with a mismatch npm refuses the install and\n   pnpm, Yarn and Bun only warn, and the client rejects the extension's\n   values. Composer never looks extensions up itself;\n   with `binding.client` instead, the first access throws\n   \"Contract requires extension pack(s) 'pgvector'\".\n\n**Every deploy and every `prisma dev` converge runs the ORM's migrate** for each ORM database: the equivalent of `prisma db migrate --to <targetRef>` against the database Composer provisioned, whether or not anything changed. The ORM decides what is pending; with nothing pending it applies nothing and no service is redeployed. A deploy only migrates: it never runs `db update`, `db init` or `db sign`, and never creates schema from the contract.\n\n`targetRef` is required on the resource end. It takes a ref name (a committed `migrations/app/refs/<name>.json`) or `@contract`, the contract this commit emits. An app that deploys to environments computes it from the environment name:\n\n```ts\npostgres({\n  name: 'database',\n  contract: catalogData,\n  config: './prisma.config.ts',\n  targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n});\n```\n\n`@empty`, `@db`, a contract hash or a migration directory name is refused. A Module that provisions its own ORM database targets `'@contract'`: its migrations ship inside its package, so the app cannot commit refs for it, and a Module that copies the app's `resolve([environment.name], …)` pattern makes the app's first `production` deploy fail with the ORM's `MIGRATION.UNKNOWN_REF`. The `prisma.config.ts` names no database (no `db.connection`); the deploy passes the ORM the one it provisioned. Per-PR environments need one ref rule for all of them (such as a shared `preview` ref, or `'@contract'`); an environment with no ref file fails with the ORM's `MIGRATION.UNKNOWN_REF`.\n\nThe loop for every schema change, including a new database's first schema:\n\n1. Edit `contract.prisma`.\n2. `prisma contract emit` regenerates `contract.json` + `contract.d.ts`.\n3. `prisma migration plan --name <slug>` authors the migration (on an empty graph this authors the baseline).\n4. `prisma migration ref set <environment> <newest migration directory>` for each environment the change should reach.\n5. Commit `migrations/`, then deploy. A fresh database replays the whole path from empty.\n\nUnder `prisma dev`, plan a migration for each contract change: a local database moved with `prisma db update` to a contract no migration ends at is refused on every rebuild with the ORM's `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, although it is at the target, until a migration ending at that contract exists. This is a current Prisma ORM bug. Plan a migration that ends at the contract; do not reset the database or edit its contract signature to get past it.\n\nA deploy moves the database to its ref, not to the code: a ref may trail the contract on purpose, and moving it is the user's job in the pull request that changes the contract. Every service that uses the database deploys only after its migration completes: a failed migration means the new code does not ship. The old code serves against the new schema until the new deployment is live, so keep each migration compatible with the code it replaces.\n\nA failed migration fails the deploy with one Composer line, `<address>: Composer ran prisma db migrate --to <targetRef> on this database.`, and the ORM's own structured error under it: code, summary, `why`, next actions and docs link. Follow the ORM's advice; Composer adds none. Its advised commands repeat `--to <targetRef>`. Composer raises its own errors only before the ORM runs: the emitted contract `prisma.config.ts` names is missing or unreadable, has no storage hash, or differs from the declared `dataContract(...)` value.\n\nWhen a ref declares policies that differ from the database's (a new database has the ORM's defaults), every deploy fails with the ORM's `MIGRATION.POLICY_MISMATCH` and changes nothing. A deploy never changes policies. Applying them is a decision for whoever administers the database, made by hand: `prisma db migrate --to <ref> --permit-policy-change --db <url>`, with the URL from the Prisma Console, from `prisma postgres connection create @<environment>:<address> --name <name> --json` (its output holds a secret shown once), or locally from `prisma dev url <address>` while `prisma dev` runs. A ref's policies are the `policies` field of its JSON file, edited by hand: the pinned Prisma ORM version has no command for them. Do not run that command, or edit a ref's policies, to get a deploy past the refusal: say what the ORM reported and leave the decision to whoever administers the database.\n\nUpgrading an app from before `targetRef` was required: add `targetRef` to each `postgres({ ... })`, commit a ref per deployed environment with `prisma migration ref set <environment> <newest migration directory>`, and remove placeholder `db.connection` entries from `prisma.config.ts`. See `examples/orm-demo` for an app and `examples/store/modules/catalog` for a Module.\n\n## Deploy model: converge, don't script\n\nDeploy compares the declared topology against recorded deploy state and\napplies only the difference. Re-deploying with nothing changed is a no-op;\nremoving a node removes its deployed resource. `prisma deploy` needs a signed-in\nidentity: `prisma auth login` stores a session on a developer machine, and\n`PRISMA_SERVICE_TOKEN` overrides it in CI. The `/control` operations, and so\na destroy script, never use that session: `deploy` and `destroy` read\n`PRISMA_SERVICE_TOKEN` and `PRISMA_WORKSPACE_ID` from environment variables (both\nin the workspace's Console settings); `dev` and `log` read neither. The\n`prisma` bin starts under Node; use `pnpm prisma …` or `npx prisma …` by\ndefault. Composer starts Alchemy with Node, but Alchemy's launcher moves to\nBun under `bunx` or `bun run`: `bunx prisma` gives Node then Bun,\n`bunx --bun prisma` Bun then Bun. When the modules `module.ts` imports use\nBun APIs, `bun node_modules/prisma/dist/prisma.js deploy` from a\nshell runs `prisma` under Bun with Alchemy on Node.\n\nA node's **address** is the app name followed by the provision ids down to it\n(`shop.auth.api`); the root's address is the app name, or `--name` when given.\nEvery surface uses this full form: `serviceOrigin('shop.api')`,\n`prisma dev url shop.api`, the `log` operation's `address`, errors and reports.\nServices, managed Postgres databases and buckets record their address as\n`logicalId` on their Branch. Console uses that address to match topology nodes\nto resources and compare them with main. Existing environments receive the\nidentity on their next deploy. A deploy interrupted after creating a resource\nresumes on the next deploy, which finds the resource by its address. Local dev\ncreates no platform rows. Changing a node's address (its name without an\nexplicit `id`, its `id`, or its module) makes a new entity: the next deploy\ndeletes the old rows, and a database's or bucket's data with them.\n\n**Progress.** `prisma deploy` prints each step as it starts and finishes, with its duration (`✔ assemble web (3m 42s)`), and ends with the real total (`Deployed <app> to <environment> in 5m 25s.`). Steps: load config and app, one assemble per service, connect to project and branch, check environment variables, plan and apply (one step: alchemy does both in one process), record result. A slow assemble is usually a Node service with `dependencies: 'external'`, whose runtime dependencies are being traced. With `--json`, each step is a `step-started`/`step-finished` line whose `data` holds `durationMs` plus whatever the build adapter or deploy target reported; those extra fields vary, so don't parse them as a stable format. The `deploy` operation's `onEvent` receives the same steps, its result's `durationMs` is the total, and its `summary.findings` lists the platform variables with no value.\n\n**Environments.** An environment is a named place the app runs, chosen with\n`--environment` at deploy time, never written in the topology. The identical\ngraph deploys everywhere. `prisma deploy` without the flag deploys\n`production`; `prisma dev` runs as `dev` and takes no flag. On the Prisma Cloud\ntarget, a Prisma App is one Project and an environment is a Branch of it, with\nits own running services, its own empty database, its own configuration:\n`production` is the Project's default Branch, any other name is the Branch\nwith that `gitName`, created if absent. The default Branch's own name (such as\n`main`) is refused, since it would be production under a second name. A name\nmust be a valid git ref name, or the deploy fails with\n`DEPLOY.ENVIRONMENT_INVALID`.\n\n**Seeing what is deployed.** `prisma deploy list [--environment <name>]` lists every\nnode of the topology the last deploy recorded, with its kind, platform ID and,\nfor a service, its URL; the root's ID is the Project's, and a module has none.\nIt finds the app as `deploy` does (`--name`, `--entry`) and fails with\n`DEPLOY.TARGET_NOT_FOUND` when the environment has nothing deployed. Piped:\naddress, kind, platform ID, URL per line; `--json`: `[{ address, kind, platformId, url }]`. It needs\na `prisma` CLI release that includes it; 8.0.0-rc.26 does not.\n\n**Using an address with platform commands.** A `prisma project|service|postgres|bucket`\ncommand takes `@<environment>:<address>` in place of the platform ID\n(`prisma service logs @pr-42:shop.api`); no environment means production. It\nacts on that one row. Deleting a service, database or bucket this way leaves\nthe deploy state alone, so the next deploy recreates it; deleting the Project\nremoves its deploy state too. It needs a `prisma` CLI release newer than\n8.0.0-rc.28.\n\n**Removing an app** with every environment is a platform command: find the Project\nid with `prisma project list`, then `prisma project delete <id> --confirm <id>`,\nand check `prisma project list` again to confirm it is gone. It works while the\napp's services are running. Don't write a script for this.\n\n**Destroying one environment** is the `destroy` operation, and its\n`environment` is required, even for production; it has no default and a call\nwithout it fails with `DEPLOY.ENVIRONMENT_REQUIRED`:\n\n```ts\nawait destroy({ entry: 'module.ts', environment: 'pr-42', config });\nawait destroy({ entry: 'module.ts', environment: 'production', config });\n```\n\nDestroying any environment other than production\ndeletes its Branch after removing its resources. Destroying production\nremoves only the resources inside the production Branch, never the Branch\nitself directly; once the Project is empty it is deleted too, and that\ndeletion takes the production Branch with it. A Project still holding\nanother environment's resources is kept. Destroy never creates anything:\ndestroying a\nnever-deployed environment fails rather than standing one up.\n\n**Upgrading from stages.** `--stage <name>` is now `--environment <name>`;\n`destroy({ target })` is now `destroy({ environment })`, with production as\n`'production'`; the `--report` file's `stage` field is now `environment`, at\n`version` 2. Keep `@prisma/composer-prisma-cloud` on the same Composer version\nas the Composer that runs the deploy. An older extension would read every\nenvironment as production, so deploy and destroy refuse it with\n`DEPS.EXTENSION_INCOMPATIBLE`.\n\n**The engine underneath is alchemy.** Convergence is executed by [alchemy](https://alchemy.run), a third-party infrastructure-as-code engine that arrives as an ordinary, exactly-pinned npm dependency of `@prisma/composer` (2.0.0-beta.87 at this library version). Your code never imports or configures it; consult alchemy's own docs for the engine itself. What matters operationally:\n\n`prisma deploy` runs alchemy inside the `prisma` process through alchemy's programmatic API: no generated file and no child process. Its progress prints as one step per resource, and a failure is `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, with credentials redacted, or `DEPLOY.INTERRUPTED` after Ctrl-C, which releases the environment's lease. `prisma dev` runs alchemy in the `prisma` process too, each converge in a new worker thread, so an edit to your app definition applies on the next rebuild. Three kinds of edit need `prisma dev` restarted, and it says so: adding or removing a node, making the root pass on an input field it did not pass on at start, and changing which platform variables the app reads. The `destroy` operation runs alchemy inside the process that calls it, the same way as deploy. The alchemy that runs is the one installed beside the app's `@prisma/composer`, so the app needs no direct `alchemy` dependency, and no global Alchemy installation is needed.\n\n1. No command writes a stack file or starts the alchemy CLI. An engine failure surfaces as `DEPLOY.ENGINE_FAILED` carrying the engine's own errors whole, credentials redacted, for deploy and destroy alike. A structured error, such as the ORM's, keeps its code, `why`, next actions, docs link and the structured error it was caused by: they print in the CLI's error layout, and its next actions stay `{ kind, label, command?, … }` objects, and are data in `failure.meta.reasons`, in the `--report` file's `failure.reasons` and on `prisma dev`'s `converge-failed` events. Only the copy sent to the Prisma Cloud build is shortened, to 5000 characters, by cutting the middle of the longest `why`.\n2. Destroy runs the same preparation as deploy, assembly included, so **an app must be built before it can be torn down**.\n3. alchemy is why the `effect` pin exists: it resolves the `effect`\n   constellation, and a hoisted newer `effect` halts every command (failure\n   mode 1 below).\n\n**The deploy report** ends with the app's own topology: authored names, the\nplatform resource each became, and public URLs. Read ids out of it rather\nthan hunting in the Console. A URL appears only where the address is\ngenuinely public: a service prints one, a database never does, and a\nnode whose product is secret material reports no resource line at all.\n\n**Connection contract refusals.** A connection declares the values it needs\nby name; a producer that omits one fails the deploy, naming the edge, the\nparam, and what the producer did supply:\n\n```text\nConnection input \"auth.db\" declares param \"url\", but its producer \"db\" did not\nsupply it — the producer's outputs carry [host].\n```\n\nThis is a deploy-time refusal, not a broken deploy, and it can appear on an\napp whose code didn't change (the gap used to pass silently as `undefined`\nand crash the consumer at boot). Fix whichever end is wrong; don't mark the\nparam `optional` unless absent really is legal. Only reachable if you\nauthored the connection or an extension on one side.\n\n**Driving deploys from code.** A script imports only\n`@prisma/composer/control`; the extensions' `/control` entries are imported\nonly by `prisma.config.ts` (ADR-0017). `@prisma/composer/control` exposes typed\n`deploy`, `destroy`, `dev`, `devUrl`, `devStop`, and `log` returning structured\nresults; `prisma deploy`, `prisma dev`, `prisma dev url` and `prisma dev stop`\nrender `deploy`, `dev`, `devUrl` and `devStop`. Each takes\na required `config: { value, file }` (`ComposerConfigSource`): the `composer`\nexport of your `prisma.config.ts` and that file's path; a relative `file`\nresolves against `cwd`, so build it from `import.meta.url`. The operations\nnever look for a config file, but refuse what the CLI refuses before any work\nstarts (`CONFIG.FIELD_UNKNOWN` for the whole export instead of its `composer`\nproperty, `CONFIG.FILE_RETIRED`, `CONFIG.FILE_MISSING`); the deploy re-imports\n`file`, so `value` must be its `composer` export. Failures come back as\n`{ ok: false, failure }` with a dotted `failure.code` from a closed registry\n(e.g. `ASSEMBLE.BUILD_FAILED`, `DEPLOY.ENGINE_FAILED`,\n`DEPS.EXECUTOR_UNLOADABLE`); branch on the code, not the message. A\nnon-structured rejection out of an operation is a bug in composer, not an\nexpected failure.\n\n## Local development\n\n`prisma dev` runs the whole app on this machine, wired as it deploys,\nagainst local emulators. No cloud credentials are needed or read. Concepts\nthat surprise:\n\n1. It runs the same pipeline as deploy, so **build first**, exactly like\n   deploy, except for a service that runs a dev server (below). It watches\n   built output and restarts a service when its build changes.\n   **Dev servers.** A service whose build adapter declares one runs it in\n   place of its artifact, with no flag: every `nextjs()` service runs\n   `next dev` (the app's own `next`, resolved from `appDir`), and a `node()`\n   service runs its `dev` argv when it has one. It runs on the service's\n   instance and URL, with the deployment's environment variables: `service.load()`,\n   `service.input()` and `service.port()` work exactly as deployed, so never add a\n   `process.env` fallback for plain `next dev`. It also keeps the shell's\n   environment variables; Composer's values win. `dev` prints ``<address>: runs\n   `<command>` in <dir>`` before the app comes up and streams the dev\n   server's output prefixed `[<address>]` (other services' logs are not\n   streamed). Source edits are the dev server's own hot reload; `dev` watches\n   the entry and every app file it imports, applies an edit to them on the\n   next rebuild (adding or removing a node, passing on a new root input field, or changing which platform variables the app reads needs `dev` restarted, and it says so), and restarts a dev server only when its environment variables changed\n   (``<address>: its environment changed; `<command>` restarted``). It has no\n   terminal (no colours or key shortcuts). The standalone build is not run\n   locally, so a standalone-only\n\n<!-- [TRUNCATED AT 50KB] -->\n\n<!-- File: skills/README.md (Tokens: ~1172 | Category: anthropic-skill) -->\n# Prisma Composer skills\n\nAgent skills for [Prisma Composer](https://github.com/prisma/composer) — one\n`SKILL.md` that teaches an LLM agent how to write, test, and deploy a Prisma\nApp without re-deriving the API from documentation each time.\n\n## What's in the box\n\nOne skill, `prisma-composer-core-concepts`, covering the whole story: the mental model\n(Modules, `compute()`, `service.load()`), RPC contracts, databases, reusable\nmodules (cron/storage/streams), config params, secrets, testing\n(`mockService`/`bootstrapService`), deploying (`prisma deploy`,\nenvironments, removing an app or an environment), and the production pitfalls. Composer's surface is small\nenough for one skill; there is no router or per-topic cluster.\n\n## Install\n\nThe skill ships inside the `@prisma/composer` tarball, so installing the\npackage is what brings it in. `prisma skills sync` (from the `prisma` CLI)\ncopies it out of `node_modules` into the skill directories the agent runtimes\nread — `.claude/skills/`, `.cursor/skills/`, `.agents/skills/`,\n`.windsurf/skills/`:\n\n```bash\npnpm add @prisma/composer\npnpm add -D prisma\npnpm prisma skills sync\n```\n\nAdd it to your project's `postinstall` so an upgrade brings the matching skill\nwith it:\n\n```jsonc\n// package.json\n\"scripts\": {\n  \"postinstall\": \"prisma skills sync || exit 0\"\n}\n```\n\nIn a monorepo (a pnpm, npm or Yarn workspace), put the hook in the `package.json` at the workspace root (the directory with `pnpm-workspace.yaml`, or the `package.json` that lists `workspaces`), not in a workspace package's: hooks in several packages run at the same time and can leave the skill copy at the root missing a file. The root's sync installs the skills of every workspace package. List `prisma` there as a dev dependency, at the version your packages use, so the root's hook can find the command. If `prisma` warns with `SKILLS.MEMBER_LEFTOVER`, a workspace package still has something an earlier `prisma` put there: move the hook to the root, and delete the other files the warning names, such as old skill copies.\n\nThe version you read is then always the version you installed: the skill's\nfrontmatter carries `metadata.library: \"@prisma/composer\"` and a\n`metadata.library_version` stamped by the release that built the tarball\n([`scripts/set-version.ts`](../scripts/set-version.ts);\n[`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs)\nproves it against the packed artifact).\n\n### Without installing the package\n\nThe GitHub source stays available for anyone who wants the skill without\n`@prisma/composer` in their project:\n\n```bash\nnpx skills add prisma/composer\n```\n\nThe [`skills` CLI](https://npmjs.com/package/skills) installs it at the\nproject level for the agent runtimes it detects (`-a <agent>` to pick one).\nNothing keeps this copy in step with your packages, so pick the git ref\nmatching your `@prisma/composer` version by hand and re-do it on every\nupgrade.\n\n## Authoring rules\n\nThe skill is the agent-condensed mirror of the human guides in\n[`docs/guides/`](../docs/guides/) — the guides are canonical for humans; a\nsurface change lands in both. For anyone editing the skill:\n\n- **Verify every claim while drafting, not in a final pass.** Every import\n  must resolve against a `packages/9-public/*` export map, and every CLI\n  flag/command against `packages/0-framework/3-tooling/cli/`. If ripgrep finds\n  nothing, the surface doesn't ship — name it under *What Composer doesn't do\n  yet* instead of extrapolating.\n- **The skill must be self-contained.** It gets installed into other repos, so\n  no link may resolve outside `skills/prisma-composer-core-concepts/`. Repo\n  docs may be\n  named in prose (\"`docs/design/10-domains/testing.md` in the prisma/composer\n  repo\"), never linked relatively.\n- **Teach concepts, not procedures.** Name the moving parts and the command\n  that reveals each piece of state; reserve numbered steps for one-safe-path\n  operations.\n- **Leave the `metadata` stamp alone.** `metadata.library` names the npm\n  package the skill ships inside, and `metadata.library_version` is rewritten\n  by [`scripts/set-version.ts`](../scripts/set-version.ts) on every release —\n  hand-editing the version, or dropping either key, breaks the release script\n  and [`scripts/check-skill-packaging.mjs`](../scripts/check-skill-packaging.mjs).\n  They live under `metadata` because the Agent Skills spec defines the\n  top-level keys and reserves that map (string → string) for publisher\n  extensions. A new skill needs both keys, with any placeholder version.\n- **Folder name and frontmatter `name` must match** — the runtimes key on the\n  frontmatter, humans on the folder.\n\nMaintainer-facing skills (release process, commit conventions) live in\n[`../skills-contrib/`](../skills-contrib/), not here.\n\n<!-- File: .claude/agents/domain-modeler.md (Tokens: ~1296 | Category: subagent-persona) -->\n---\nname: domain-modeler\ndescription: Research and write DDD-style domain models for external systems (e.g. Cloudflare/Wrangler) as structured docs under docs/design/04-inspirations/.\ntools: Read, Write, Bash, WebFetch\ncolor: blue\nmodel: inherit\n---\n\nYou are a domain modeling and domain research specialist.\n\nYour job is to take a target system (product + tooling) and produce a **DDD-style written domain description**: ubiquitous language, core concepts, relationships, user workflows, and behavioral/execution flows — written as a small library of docs that can be reused in later design discussions.\n\nThis agent is designed to be “set loose”: you do the research, make reasonable modeling calls, and leave behind a coherent, cross-linked documentation set.\n\n## Core responsibilities\n\n1. **Capture ubiquitous language**\n   - Build a glossary of the system’s key terms as *users* use them (and note internal/mechanical terms separately).\n   - Prefer the product’s native vocabulary over invented terms; call out synonyms and overloaded words.\n\n2. **Model the domain (things + relationships + behaviors)**\n   - Produce a conceptual domain map (relationships between the core concepts).\n   - Enumerate the primary operations (“verbs”) on those concepts.\n   - Document behavioral relationships: what triggers what, what depends on what, what must be true.\n\n3. **Model the user mental model + UX workflows**\n   - Document the user’s day-to-day mental model.\n   - Capture the common workflows (happy paths + sharp edges) as step-by-step flows.\n\n4. **Separate stable research from evolving takeaways**\n   - Keep “how the system works” relatively stable in research docs.\n   - Keep “what Prisma Composer should do because of it” in a separate takeaways doc that can evolve.\n\n5. **Be explicit about uncertainty**\n   - Track open questions and assumptions at the end of each doc.\n   - When unsure, write the best current model and clearly label it as an assumption.\n\n## Workflow (every time)\n\n### Step 0: Anchor on the repo’s doc system (read-first)\n\nRead:\n- `docs/design/README.md`\n- `docs/design/99-process/README.md`\n- `docs/design/04-inspirations/README.md`\n- Any existing inspiration docs for the target system (if present)\n\nGoal: match the house style and keep outputs discoverable and consistent.\n\n### Step 1: Define scope + output location\n\nDecide:\n- The **target system name** (e.g. “Cloudflare”, “Cloudflare Wrangler”, “Cloudflare Workers + Wrangler”).\n- What is in-scope vs out-of-scope (product surfaces, runtime primitives, billing/account, etc.).\n\nCreate (or update) a research library folder:\n- `docs/design/04-inspirations/<System>/`\n\nIf a single-file inspiration note already exists (e.g. `docs/design/04-inspirations/cloudflare.md`), treat it as a short overview and keep the detailed model in the folder.\n\n### Step 2: Research (prefer primary sources)\n\nUse official docs and product references first (then reputable secondary sources).\n\nWhile researching, continuously extract:\n- **Nouns** (things): resources, identifiers, configuration objects, runtimes, projects, accounts.\n- **Verbs** (operations): create/update/deploy/bind/route/observe/debug/rollback.\n- **Rules** (invariants): what must always hold; what configurations are invalid; what is “the unit of deployment”.\n- **Workflows** (UX): “day 1” setup, deploy, local dev, preview/staging, rollout, rollback, debugging.\n- **Control-plane vs runtime split** (if applicable): author-time/build-time/deploy-time vs runtime execution.\n\n### Step 3: Write the DDD artifacts (structured library)\n\nProduce this set of files (mirrors the `TanStack/` pattern):\n\n- `README.md`\n  - what this library covers, what to read, key sources\n- `glossary.md`\n  - terms + definitions; note “user-facing?”; include synonyms/aliases\n- `domain-map.md`\n  - a conceptual relationship map (use Mermaid where useful)\n- `operations.md`\n  - the primary operations on core concepts (CRUD + lifecycle + operational verbs)\n- `user-domain.md`\n  - the user mental model and how it maps to underlying mechanics\n- `execution-flows.md`\n  - the “always happening” flows (deploy lifecycle, routing, local dev loops, etc.)\n- `takeaways-for-prisma-composer.md`\n  - explicitly evolving: what Prisma Composer should emulate/adapt, plus design questions raised\n\nWriting guidelines:\n- Prefer **small, scannable** docs over one huge one.\n- Keep each doc focused; cross-link instead of duplicating.\n- Include **1–2 diagrams** when they materially improve comprehension.\n- Keep a short **Open questions / assumptions** section at the bottom of each file.\n\n### Step 4: Integrate with the inspiration index\n\nUpdate `docs/design/04-inspirations/README.md` to list the new folder (or new key docs) so the library is discoverable.\n\n### Step 5: Finish with a “what changed” summary\n\nWhen done, summarize:\n- Files created/updated\n- Key domain concepts discovered (5–10 bullets)\n- The most important workflows (3–5 bullets)\n- Open questions / unknowns (explicit list)\n\n## Output expectations\n\nWhen asked to “model Cloudflare + Wrangler”, a successful output usually includes:\n\n- A new folder: `docs/design/04-inspirations/Cloudflare/` (or similarly named)\n- The standard library docs listed above, cross-linked and consistent\n- A takeaways doc that cleanly separates “research facts” from “Prisma Composer implications”\n\n## Guardrails\n\n- Do **not** change Prisma Composer’s core domain docs (`docs/design/03-domain-model/`, `docs/design/10-domains/`) unless the user explicitly asks you to translate research into Prisma Composer design changes.\n- Do **not** create ADRs unless the user explicitly indicates a decision has been made.\n- Prefer documenting what you can verify; label inferred models as assumptions.\n\n<!-- File: packages/1-prisma-cloud/2-shared-modules/auth/README.md (Tokens: ~4845 | Category: plugin-manifest) -->\n# @internal/auth\n\nSignup, login, sessions, and JWT verification as a composed module wrapping\n[Better Auth](https://better-auth.com) (in-process TypeScript library — not a\nremote IdP), published as `@prisma/composer-prisma-cloud/auth`. One dedicated\nCompute service; the schema ships as a Prisma ORM extension pack; the\ninstance secret is platform-minted.\n\n## Contract scope\n\nThree ports, one service behind them — least privilege is a WIRING choice:\n\n- **`api`** (a raw HTTP port, `rawHttpContract` from `@prisma/composer/http`)\n  — the public Better Auth surface\n  (`/api/auth/*`): signup, login, logout, self-service account deletion,\n  JWKS, token minting. Publicly reachable, with no service key (unlike the\n  rpc ports) — it IS the authentication: Better Auth authenticates each\n  request itself (logout and account deletion need a signed-in session)\n  and rate limits it. Two consumer dependencies bind to it:\n  - `rawHttp()` from `@prisma/composer/http` → `{ url, fetch }` — what\n    `authProxy()` consumes. Any raw HTTP slot accepts this port, so a test\n    double or another auth server can fill the same slot.\n  - `jwtVerifier()` → `verify(token)` — stateless JWT verification over the\n    instance's JWKS (jose remote JWKS, 30 s clock tolerance). Resolves\n    `null` for ANY invalid token content; throws only on operational\n    errors (JWKS unreachable). No DB access — that is its whole value.\n- **`session`** (rpc) — consumer-facing online checks: `getSession(token)`\n  (null for unknown/expired/banned-owner — one shape, no error; a revoked\n  session is a deleted row, so this is the instant-logout read) and\n  `getUser(id)` (profile rendering off a JWT `sub` without admin wiring).\n- **`admin`** (rpc) — the tier-1 admin path: `findUser` (exactly one of\n  id/email; email match case-insensitive), `listUsers` (query/banned\n  filters, keyset cursor), `listSessions`, `revokeSession`,\n  `revokeUserSessions` (idempotent deletes), `banUser` (ban implies\n  revoke, atomically), `unbanUser`, `createUser` (see Provisioning\n  accounts below), `setEmailVerified`, `removeUser` (see Deleting\n  accounts below).\n\nWire each port only where it belongs: the app gets `api` + `session`; the\nback office alone gets `admin`.\n\n`/api/auth/*` is the browser surface. Better Auth origin-checks any request\nthat looks like it came from a browser — one carrying a cookie, an\n`Origin`/`Referer`, or any `Sec-Fetch-*` header — and refuses a missing\n`Origin` with `403 MISSING_OR_NULL_ORIGIN`. Node's built-in `fetch` sends\n`Sec-Fetch-Mode` on every request, so a Node script calling `/api/auth/*`\n(directly or through `authProxy`) is refused unless it sends an `Origin`\nthat is in `trustedOrigins` (the module's `baseUrl`). Server-to-server work\nbelongs on the rpc ports instead.\n\n## Golden-path wiring\n\n```ts\n// module.ts (the root)\nimport { appRoot, resolve } from '@prisma/composer';\nimport { serviceOrigin } from '@prisma/composer-prisma-cloud';\nimport { auth } from '@prisma/composer-prisma-cloud/auth';\nimport { postgres } from '@prisma/composer-prisma-cloud/orm';\nimport { appContract } from './src/contract.ts';\nimport apiService from './src/api/service.ts';\n\nexport default appRoot('app', ({ environment, provision }) => {\n  const db = provision(\n    postgres({\n      name: 'database',\n      contract: appContract,\n      config: './prisma.config.ts',\n      targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),\n    }),\n    { id: 'database' },\n  );\n  const identity = provision(auth(), {\n    id: 'auth',\n    deps: { db },\n    input: { baseUrl: serviceOrigin('app.api') }, // the PUBLIC app origin\n  });\n  provision(apiService, {\n    id: 'api',\n    deps: { authApi: identity.api, verifier: identity.api, session: identity.session },\n  });\n});\n```\n\nEvery deploy migrates the database to its `targetRef`. Here `prisma dev` migrates to the contract the commit emits, and a deploy to the environment `production` migrates to the ref `migrations/app/refs/production.json`, which you commit after planning a migration: `prisma migration ref set production <newest migration directory>`.\n\n```ts\n// src/api/service.ts: the app service declares its three dependencies\nimport { rawHttp } from '@prisma/composer/http';\nimport { rpc } from '@prisma/composer/service-rpc';\nimport { authSessionContract, jwtVerifier } from '@prisma/composer-prisma-cloud/auth';\n\nexport default compute({\n  name: 'api',\n  deps: { authApi: rawHttp(), verifier: jwtVerifier(), session: rpc(authSessionContract) },\n  build: node({ module: import.meta.url, entry: 'server.js' }),\n});\n```\n\n```ts\n// in the app service: first-party cookies via the proxy (the browser golden path)\nimport { authProxy } from '@prisma/composer-prisma-cloud/auth';\n\nconst { authApi, verifier } = service.load();\nconst proxy = authProxy(authApi);\n// route /api/auth/* → proxy(request); verify API calls with verifier.verify(<bearer>)\n```\n\nThe database is a BOUNDARY dependency: the root decides dedicated vs shared. `baseUrl` is the public origin browsers see (scheme+host, no trailing slash, no path) — bind it with `serviceOrigin('<app>.<service>')`, the service's full address, so each environment trusts its own URL, or a field of the root's input, such as `input.AUTH_BASE_URL`, for a custom domain. The instance secret is platform-minted inside the module; rotation is unsupported in v1 (rotating would invalidate every session and the encrypted jwks rows).\n\nA complete, deployable copy of this wiring lives in `examples/auth`.\n\n## Provisioning accounts\n\nAn account an operator creates goes through the `admin` port, server to\nserver — never through the browser sign-up surface:\n\n```ts\n// in a service wired to `identity.admin`\nconst { admin } = service.load();\nconst { user } = await admin.createUser({\n  email: 'ops@example.com',\n  name: 'Ops',\n  password: 'a-long-passphrase',   // optional; omit for a magic-link-only account\n  emailVerified: true,             // optional; default false\n});\n```\n\n`createUser` writes exactly what Better Auth's own sign-up writes — the\n`user` row and, with a password, a `credential` account hashed by Better\nAuth's own hasher — and sends no mail. The contract input applies the same\nchecks sign-up does (a well-formed email, a password of 8–128 characters),\nso a caller mistake is a 400 at the rpc boundary; a duplicate email\n(case-insensitive) is refused by the handler. Every refusal reaches a typed\nrpc client as a thrown error, so a script cannot mistake it for success. `setEmailVerified({ userId, emailVerified })` flips\nthe flag a created account needs before `requireEmailVerification` lets it\nsign in (`user: null` for an unknown id).\n\nA deployed stack's rpc ports are reachable only by consumers in its graph:\na script on a laptop cannot call `admin.createUser`. The application\nexposes its own operator route (allowlisted however it sees fit) from a\nservice wired to `admin`, and that route makes the call.\n\nInvite-only applications close self-service sign-up with a module setting,\nenforced by Better Auth itself, instead of filtering their proxy:\n\n```ts\nprovision(auth({ signUp: 'closed' }), { id: 'auth', deps: { db, email: mail.send }, input: { baseUrl: … } });\n```\n\n`signUp: 'closed'` sets `emailAndPassword.disableSignUp` and the magic-link\nplugin's `disableSignUp`: `/api/auth/sign-up/email` answers `400\nEMAIL_PASSWORD_SIGN_UP_DISABLED`, and a magic link requested for an unknown\nemail is still sent but completes to an `error=new_user_signup_disabled`\nredirect with no user created. Sign-in for existing accounts is unchanged.\nDefault `'open'`. Nothing about origin, CSRF, or `trustedOrigins` changes\neither way.\n\n## Deleting accounts\n\nA signed-in user deletes their own account through Better Auth's\n`POST /api/auth/delete-user`, reached through `authProxy()` like the rest\nof `/api/auth/*`:\n\n```ts\n// browser, signed in (cookie through the proxy)\nawait fetch('/api/auth/delete-user', {\n  method: 'POST',\n  headers: { 'content-type': 'application/json' },\n  body: JSON.stringify({ password }), // optional when the session is < 24 h old\n});\n```\n\nIt needs a signed-in session (`401` otherwise), deletes only that\nsession's user (there is no `userId` parameter), and demands the current\n`password` (`400 INVALID_PASSWORD`) or a session younger than 24 hours\n(`400 SESSION_EXPIRED` — sign in again; magic-link users have no password).\n\nAn operator deletes an account through the `admin` port, server to server\n— this module's database-direct rpc, not Better Auth's admin-session API:\n\n```ts\n// in a service wired to `identity.admin`\nconst { removed } = await admin.removeUser({ userId });\n```\n\n`removed: false` means no such user, so a retried deletion is not an\nerror. No mail is sent.\n\nBoth paths delete the `user` row, its sessions, and its accounts. Pending\nverification tokens are left to expire: an unused magic link (the email,\n5 minutes) or reset (the user id, 1 hour); Better Auth deletes expired\ntokens the next time it checks any token. Your own rows follow your foreign\nkey onto `auth:User`: `onDelete: Cascade` deletes them with the user,\n`Restrict` refuses the deletion, and without an FK nothing links them.\nData outside the database (uploaded files, other stores) needs your own\ncleanup first — route that deletion through your service and\n`removeUser`. Already-minted JWTs keep verifying until they expire\n(≤ 15 min, see Sessions & JWTs); `session.getSession(token)` is `null`\nimmediately.\n\n## The pack\n\nBetter Auth's tables (`user`, `session`, `account`, `verification`, `jwks` —\nPostgres schema `auth`) ship as a Prisma ORM extension pack with authored\nmigrations — Better Auth's own migrator never runs anywhere. Consumers:\n\n```ts\n// prisma.config.ts\nimport authPack from '@prisma/composer-prisma-cloud/auth/pack';\nexport default defineConfig({ ..., extensions: [authPack] });\n```\n\nRun `prisma migration plan` once — it materialises the pack's shipped\nmigrations into `migrations/auth/` — and deploy: the ONE migration step\ncreates and evolves the auth tables beside your own, marker-signed per\nspace. On a shared database your own contract can FK `auth:User`\n(cross-space relations are non-navigable in the generated client; the value\nis the real constraint):\n\n```prisma\nmodel Profile {\n  id     String @id\n  userId String @unique\n  user   auth:User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n```\n\nUpgrade procedure: bump this package → `prisma migration plan` (the new\nshipped migrations materialise) → deploy. The deploy preflight fails loudly\nwhen a wired database's config is missing the pack or is at a stale head.\nA version whose section below says otherwise needs those steps instead.\n\n### Upgrading to a required `targetRef`\n\nThe app's database now needs `targetRef`, and every deploy runs the ORM's migrate to it, for the auth pack's contract space as for the app's. Add `targetRef` to the app's `postgres({ ... })` as shown above, commit a ref per environment you deploy with `prisma migration ref set <environment> <newest migration directory>` (run where the app's `prisma.config.ts` is), and remove any placeholder `db: { connection: … }` from that `prisma.config.ts`. The auth pack's own space always migrates to its shipped head.\n\n### Upgrading to Prisma ORM 8.0.0-rc.26\n\nPrisma ORM 8.0.0-rc.26 computes every contract hash in a new way, so the auth pack's storage hash moves from `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d` to `cb2e6cac77e993f93581b354f39af672267ae9c5888a156e68c00bb9087f769e`. The tables do not change. Follow [Upgrading to Prisma ORM's new contract hashes](../../../../docs/guides/deploying.md#upgrading-to-prisma-orms-new-contract-hashes): its script rewrites your copy of the auth pack's migrations in `migrations/auth/` with your own, and `prisma db sign` signs the auth pack's space with your app's.\n\nA database that only `startLocalAuthServer` uses, such as one your tests create, has no project to run `prisma db sign` from. Point the server at a fresh database instead: on a database it set up under an earlier version, it now stops with the ORM's `CONTRACT.PRISMA_SPACE_BEHIND` and changes nothing.\n\n### Upgrading to Composer 0.34.0\n\nComposer 0.34.0 moves to Prisma ORM 8.0.0-rc.20. The auth pack's contract no longer stores its `Tstz` type alias: each column stores its own type. The tables do not change, but the auth pack's storage hash does, from `0df0ef0989ec3dd95124dde6303fbe0572bbab08bebf00abff6a7955cadd786e` to `24a0762cac2c89426d118c9a9a81876ebcf32eba11789722d7c907ba710dc60d`. Your app keeps its own copy of the auth pack's migrations (`migrations/auth/` and the snapshot in `migrations/snapshots/0df0ef…/`), and Prisma ORM rc.20 refuses to load that snapshot as it is. Every database's marker also still holds the old hash. Until you follow these steps, `prisma deploy` and `prisma dev` fail at the migration step: first with `Contract-space contract validation failed for \"auth\"`, and after the script in step 3 with an error that the database is at a contract no migration of contract space `\"auth\"` reaches.\n\n1. Commit your work, so the changes below can be reviewed and undone with git.\n2. Upgrade `@prisma/composer`, `@prisma/composer-cli` and `@prisma/composer-prisma-cloud` to 0.34.0, `@prisma/orm-postgres` to 8.0.0-rc.20, and `prisma` to 8.0.0-rc.26 or later. An earlier `prisma` cannot read an rc.20 contract, so `contract emit` and `db sign` fail with `Cannot use 'in' operator to search for 'kind' in typeAlias`.\n3. From the app's root, copy the Prisma skills into the project and run the ORM's type-alias script. Node does not run a TypeScript file from inside `node_modules`, which is why the script runs from the copy:\n\n   ```sh\n   prisma skills sync\n   node .agents/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts\n   ```\n\n   It renames `migrations/snapshots/0df0ef…/` to `migrations/snapshots/24a0762…/` and rewrites `migrations/auth/0001_init/migration.json` and `migrations/auth/refs/head.json`. It prints `0df0ef… -> 24a0762…`.\n4. Run `prisma contract emit`. For an app whose own contract has no type aliases, this only moves the version stamps in `contract.json` and `contract.d.ts`.\n5. Run `prisma db sign --db <url>` against every database of the app: production, each other environment and the local dev database. The database does not change; only its marker moves to the new hash. It prints `auth: signed 24a0762… (was 0df0ef…)`.\n   - **Deployed environments.** A deploy never prints a connection string. Copy each database's connection string from the Prisma Console: the app's Project for production, and the Branch named after the environment for any other environment.\n   - **The local dev database.** It must be running: `prisma db sign --db \"$(prisma dev url database)\"`, where `database` is your auth database's node address. A `prisma dev` that fails stops the app, and `prisma dev url` reports only a running database, so sign before you run `prisma dev` on the new version. A `prisma dev --detach` started before the upgrade keeps the database running. If the database is already stopped, start over with `prisma dev --fresh`, which deletes the local data.\n6. Deploy and run `prisma dev` as usual.\n\nThe script also gives the rewritten `0001_init` migration a new hash, and each database's migration history keeps the old one. So `prisma migration status` no longer shows the auth pack's earlier migrations as applied, although it still reports the database as up to date. `prisma db migrate` does not run them again.\n\n## Sessions & JWTs\n\nStateless JWTs by default: 15-minute TTL, EdDSA via the instance's JWKS at\n`/api/auth/jwks`. Verified claims: `sub` (userId), `sid` (sessionId),\n`email`, `emailVerified`, `exp`. Cookie sessions last 7 days (rolling,\nrefreshed daily).\n\nThe trade-off is explicit: a revoked/banned session's already-minted JWTs\nkeep verifying until they expire (≤ 15 min). A route that needs instant\nlogout opts in per call with `session.getSession(token)` — a revoked\nsession is a deleted row. `iss`/`aud` are not validated in v1: the verifier\nonly trusts keys fetched from the wired instance, and instances never share\nkeys.\n\n## Local dev\n\n```ts\nimport { startLocalAuthServer } from '@prisma/composer-prisma-cloud/auth/testing';\n\nconst server = await startLocalAuthServer({ databaseUrl }); // e.g. `prisma dev`\n// server.url            → real Better Auth + the real port handlers\n// server.capturedEmails → { template, to, url } per send — read your\n//                          verification / magic links straight from here\n```\n\nReal Better Auth, the real handlers, the same fetch topology as production; the pack's schema applies idempotently at boot; a fixed dev secret; rpc runs keyless. No cloud credentials anywhere.\n\nThe helper applies the schema with the Prisma ORM your app installs (`@prisma/orm-postgres`, a required peer, and `@prisma/orm-toolchain`, which Composer depends on). It carries no copy of its own.\n\n## Email flows\n\nVerification, password reset, and magic-link emails deliver through the\n[email module](../email/README.md), wired as a boundary dependency:\n\n```ts\nconst mail = provision(email(), { id: 'mail', input: { /* deliveryMode, from, deliveryCredential */ } });\nconst identity = provision(auth(), {\n  id: 'auth',\n  deps: { db, email: mail.send },\n  input: { baseUrl: serviceOrigin('shop.web') },\n});\n```\n\nSignup requires verification (`requireEmailVerification: true`; the\nverification send fires on signup, and verifying auto-signs-in; an\n`admin.createUser` account skips the mail and is verified when created\nwith `emailVerified: true`). Magic links expire after 5 minutes. The three templates ship with the module —\nminimal semantic HTML plus a plain-text part; every interpolation is\nHTML-escaped, and a link whose origin differs from `baseUrl` fails the\nsend rather than going out.\n\nDelivery is fire-and-forget from auth's perspective: a failed send is\nlogged, never thrown (a down mail path must not brick signup), and each\nsend carries a deterministic idempotency key, so Better Auth retries\ncan't double-deliver. The email module's outbox is the operational\nrecord — read delivery state back through its `outbox` port.\n\nLocally, `startLocalAuthServer` captures sends in `capturedEmails` by\ndefault, or accepts an `email` sender hydrated against the email module's\nown local server so the outbox-readback path is the one production uses.\n`examples/auth` runs the full loop both ways: signup → verification link\nread back from the outbox → verify → login → magic link.\n\n## Embedded mode\n\nArrives with slice S4: `createEmbeddedAuth()` (`./embedded`) — the same\n`buildAuthOptions()` mounted in your own service, for the fully-in-process\nshape.\n\n## The SPA alternative\n\nDocumented fully in S2 alongside the browser flows: talk to the `api` port's\norigin directly with `Authorization: Bearer` (the bearer plugin is enabled),\nat the cost of the first-party-cookie golden path.\n\n## Limits (v1)\n\nNo social providers (mechanism reserved, none ship) · no organizations /\n2FA / passkeys / username / phone · no secret rotation · no impersonation · admin web UI is tier 2+ (the `admin` port is tier 1) ·\nrpc bodies cap at 1 MiB.\n\n<!-- File: packages/1-prisma-cloud/2-shared-modules/email/README.md (Tokens: ~3185 | Category: plugin-manifest) -->\n# `@prisma/composer-prisma-cloud/email`\n\nTransactional email as a Prisma Composer module. It is an ordinary module: a\nCompute service backed by a module-provisioned Prisma Postgres (every email is\nstored first, then delivery is attempted — the outbox), exposing two\nindependent ports: `send` (deliver a rendered email) and `outbox` (query every\nemail the module has handled). Templates are declared and rendered\n**consumer-side**; the wire carries only rendered mail.\n\nShips as the `@prisma/composer-prisma-cloud/email` subpath (like `/storage`\nand `/cron`).\n\n## Contract scope\n\nTwo ports, three ops:\n\n| Port | Op | Notes |\n| --- | --- | --- |\n| `send` | `send` | `{ templateId, to, cc?, bcc?, replyTo?, subject, html, text?, idempotencyKey }` → `{ id, status, error? }`. `to` 1–50 entries; `idempotencyKey` 1–256 chars. |\n| `outbox` | `getEmail` | `{ id }` → `{ email }` (`null` for an unknown id — never an error). |\n| `outbox` | `listEmails` | Optional `to`/`templateId`/`status`/`cursor`/`limit` filters (AND-combined; `to` matches any recipient) → `{ emails, nextCursor? }`, newest-first, keyset-paginated. `limit` 1–200, default 50. |\n\n`status` is one of `stored` (mode `none`), `queued` (real modes, transient),\n`sent`, `failed`. `send` never throws for a delivery failure — failure is\ndata (`status: 'failed'`, `error` set); it throws only for transport,\nvalidation, or database errors.\n\n`from` is not part of `send`'s input — the sender address is module config\n(one per module instance); a template cannot override it.\n\n## Envelope\n\n**No attachments** in v1. service-rpc request/response bodies cap at **1\nMiB**, so a rendered email (subject + html + text) must fit inside that.\n**Retention: none** — every sent email's full body is stored, unredacted,\nforever (no expiry, no deletion, no redaction). Do not put anything in a\ntemplate you would not want to live in the database indefinitely.\n\n## Wiring\n\nProvision `email()` in a module and declare template-typed dependencies on\nits two ports:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { email, emailDeliveryModes } from '@prisma/composer-prisma-cloud/email';\nimport { variable } from '@prisma/composer-prisma-cloud';\nimport { type } from 'arktype';\n\nexport default appRoot(\n  'app',\n  {\n    input: type({\n      EMAIL_DELIVERY_MODE: type.enumerated(...emailDeliveryModes),\n      EMAIL_FROM: 'string',\n    }),\n  },\n  ({ input, provision }) => {\n    const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));\n    const mail = provision(email(), {\n      id: 'email',\n      input: {\n        deliveryMode: input.EMAIL_DELIVERY_MODE,\n        from: input.EMAIL_FROM,\n        deliveryCredential,\n      },\n    });\n    provision(appService, { deps: { email: mail.send } });\n    provision(adminService, { deps: { outbox: mail.outbox } });\n  },\n);\n```\n\n```ts\n// consumer service — templates declare the client's shape. Interpolated\n// values are HTML-escaped before going into markup — `render` runs on\n// whatever data the caller supplies, so treat it as untrusted the same way\n// you would any other template.\nimport { defineTemplates, emailSender } from '@prisma/composer-prisma-cloud/email';\nimport { type } from 'arktype';\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#39;');\n}\n\nconst templates = defineTemplates({\n  verification: {\n    data: type({ link: 'string' }),\n    render: ({ link }) => ({\n      subject: 'Verify your email',\n      html: `<p><a href=\"${escapeHtml(link)}\">Verify</a></p>`,\n      text: `Verify: ${link}`,\n    }),\n  },\n});\n\nexport default compute({ deps: { email: emailSender(templates) }, /* … */ });\n```\n\n```ts\n// consumer server\nconst { email } = service.load();\nawait email.verification({ to: user.email, data: { link } });\n```\n\nThe outbox port needs no custom factory — declare `deps: { outbox:\nrpc(emailOutboxContract) }` and get the generated client directly.\n\n## Using react-email\n\n`render` may be synchronous or async — the sender method awaits either.\nThis module neither depends on nor imports react-email; a template's\n`render` just calls react-email's own `render()` and returns its result:\n\n```tsx\n// emails/welcome.tsx — a plain react-email component\nimport { Body, Container, Html, Text } from '@react-email/components';\n\nexport function WelcomeEmail({ name }: { name: string }) {\n  return (\n    <Html lang=\"en\">\n      <Body>\n        <Container>\n          <Text>Welcome, {name}!</Text>\n        </Container>\n      </Body>\n    </Html>\n  );\n}\n```\n\n```tsx\n// templates.tsx\nimport { render } from '@react-email/render';\nimport { WelcomeEmail } from './emails/welcome.tsx';\n\nconst templates = defineTemplates({\n  welcome: {\n    data: type({ name: 'string' }),\n    render: async ({ name }) => ({\n      subject: `Welcome, ${name}!`,\n      html: await render(<WelcomeEmail name={name} />),\n      text: await render(<WelcomeEmail name={name} />, { plainText: true }),\n    }),\n  },\n});\n```\n\nJSX interpolation (`{name}` above) escapes automatically — React escapes\ntext children by construction, so a react-email template needs no manual\n`escapeHtml` the way a plain-function template does. See\n[`examples/email`](../../../../examples/email)'s `welcome` template for\nthe full worked version, alongside `verification` as a plain function —\nboth authoring styles side by side.\n\nOne deploy caveat: `prisma deploy` loads your module graph with\nNode's own loader, which cannot transform JSX — a `.tsx` file imported by\nyour topology fails with `Unknown file extension \".tsx\"`. Precompile the\ntemplates file in your app's own build and import the compiled output, as\n[`examples/email/scripts/build.ts`](../../../../examples/email/scripts/build.ts)\ndoes (see the matching `gotchas.md` entry).\n\n## Values per environment\n\n`deliveryMode`, `from` and `deliveryCredential` are the module's `input`. `deliveryMode` is `resend`, `smtp` or `none`, exported as `emailDeliveryModes` (and the type `EmailDeliveryMode`): bind it to one of those literals, or to a field of your root's input declared from `emailDeliveryModes`, as above, so the root's schema checks it before anything is created. With Zod, declare the field as `z.enum(emailDeliveryModes)`. A plain platform variable may hold any text, so binding its value to `deliveryMode` fails to compile. Bind `from` to a literal, a field of your root's input or the value of a `variable(...)` node, so it can vary per environment. `deliveryCredential` is a `secretString()` field: bind it to the value of a `variable.secret(...)` node the app root provisions. `deliveryMode` and `from` are wrapped fields (`field()`), so a module that passes its own wrapped field of the same type on can bind them too. `deliveryUrl` is a factory option (`email({ deliveryUrl })`), static per app: it defaults to `https://api.resend.com` and follows the mode.\n\nIn the sample above, `EMAIL_DELIVERY_MODE` and `EMAIL_FROM` are root input fields: set them in the shell that runs the deploy. `EMAIL_DELIVERY_CREDENTIAL` is a platform secret: set it on the platform with `prisma project env add`.\n\n| Name | Where it is set | Production | Preview |\n| --- | --- | --- | --- |\n| `EMAIL_DELIVERY_MODE` | the deploy shell | `resend` (or `smtp`) | `none` |\n| `EMAIL_FROM` | the deploy shell | `noreply@myapp.com` | anything (unused when `none`) |\n| `EMAIL_DELIVERY_CREDENTIAL` | the platform | Resend API key / SMTP password | any non-empty value, which preflight requires even though the service never reads it |\n\nPreview needs a credential because the email service's input schema requires it in every mode, so an environment that never delivers still sets a non-empty value. A schema can make a secret field optional (ADR-0042); this one does not. `gotchas.md` records this.\n\n## Delivery policy\n\nShared by both real backings (`resend`, `smtp`):\n\n- Per-attempt timeout: **10 s**.\n- Up to **3 attempts** (1 initial + 2 retries), delayed **500 ms then\n  2000 ms** between them (no jitter).\n- Retryable: thrown/network errors, HTTP 429, HTTP 5xx (Resend); SMTP\n  connection errors and response codes 421/450/451/452.\n- Not retryable (fails immediately): any other Resend 4xx (including 409\n  idempotency conflicts — those should be unreachable given the outbox's\n  own row-level dedup; if one surfaces, it is not masked); any other SMTP\n  response code, including permanent 5xx rejections.\n- The outbox row's `attempts` accumulates the count each delivery\n  invocation actually made (1–3 under the policy above) — a future\n  redelivery from the outbox adds its own tries to the running total.\n- Stored `error` string: `` resend <status> <name>: <message> `` (Resend,\n  parsed from its error body; falls back to the raw response text if\n  unparseable) or `` smtp <responseCode>: <message> `` (SMTP protocol\n  rejection). A connection-level failure (no response code) stores the raw\n  error message with no prefix, for either backing.\n\n**SMTP: \"accepted\" is not \"delivered\".** `status: 'sent'` for an SMTP send\nmeans the relay accepted the message for submission — nothing more. SMTP\ngives no delivery confirmation; `providerMessageId` is nodemailer's\n`info.messageId` (or `null`).\n\n**SMTP: a timeout retry can duplicate a send.** The per-attempt timeout\nonly stops the module from waiting on a slow relay — it does not cancel\nthe in-flight SMTP transaction. If the timeout fires, the shared policy\nretries; a slow relay can still accept the first attempt's message after\nthe retry has already started, delivering the same email twice. This is a\ndeliberate retry-semantics tradeoff (at-least-once, not exactly-once) and\nstays as pinned — the only fix that removes the possibility is not\nretrying on timeout, which would trade a rare duplicate for a more common\nfalse failure on a merely slow relay.\n\n## Idempotency\n\n`idempotencyKey` is required on every `send` call and must be **unique per\nlogical send**. A repeated key returns the original row — status, id, and\nall — with no new delivery attempt, even if the payload differs. This is a\ndurable, row-level guarantee (a unique constraint on `idempotency_key`),\nindependent of and stronger than service-rpc's own in-memory replay cache.\n\n`emailSender`'s per-template methods make `idempotencyKey` optional: omit\nit and a fresh UUID is minted on every call, so that call gets no dedup\nprotection against its own retries. If your own retry logic re-invokes a\nsend method after a transient failure, capture the key from the first\nattempt and pass it explicitly on the retry — the module does not\nremember it for you.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/email/testing` boots the same handler map\nover an in-memory store, `deliveryMode: 'none'`, loopback only, no auth —\nno cloud credentials, no Postgres:\n\n```ts\nimport { startLocalEmailServer } from '@prisma/composer-prisma-cloud/email/testing';\n\nconst server = await startLocalEmailServer(); // ephemeral port by default\n// server.url — point emailSender()/rpc(emailOutboxContract) clients at it.\nawait server.stop();\n```\n\n[`examples/email`](../../../../examples/email) is the worked example: a\n`mailer` app wired to `email()`, tested locally against this stand-in with\nno cloud credentials, and deployed to Prisma Cloud in `none` mode as the\nsmoke test.\n\nTests that exercise the real Resend/SMTP backings point `deliveryUrl` at a\nlocal fake instead of the real provider — a `Bun.serve` fake HTTP endpoint\nfor Resend, a minimal loopback SMTP responder for SMTP (see\n`delivery-resend.test.ts`/`delivery-smtp.test.ts`).\n\n## Manual resend check (not run in CI)\n\nA one-off, by-hand verification that a real send actually delivers — not\npart of the test suite or the deploy smoke, since it needs a real Resend\naccount:\n\n1. Set the environment's `EMAIL_DELIVERY_MODE` to `resend`, `EMAIL_FROM` to an\n   address on a domain verified with Resend, and `EMAIL_DELIVERY_CREDENTIAL`\n   to a real Resend API key.\n2. Send one template to a real inbox you control.\n3. Confirm the message arrives, and that the outbox row for it reads\n   `status: 'sent'` with a non-null `providerMessageId`.\n\n## Non-goals (v1)\n\nAttachments, cc/bcc size limits beyond the contract's, per-send `from`\noverride, batch/scheduled send, Resend webhooks, delivery-status polling,\nopen/click tracking, queue-backed async delivery (the outbox is the seam\nfor a later relay — no contract change needed), retention/redaction/\ndeletion, and an admin UI. react-email is not a dependency of this module\n— see \"Using react-email\" above for how a consumer wires it in.\n\n<!-- File: packages/1-prisma-cloud/2-shared-modules/storage/README.md (Tokens: ~1427 | Category: plugin-manifest) -->\n# `@prisma/composer-prisma-cloud/storage`\n\nS3-compatible object storage as a Prisma Composer module. It is an ordinary\nmodule: a Compute service that speaks the **S3 wire protocol**, backed by a\nmodule-provisioned Prisma Postgres (objects live in a single `bytea` column),\nwith SigV4 credentials minted at deploy. Consumers wire the module's `store`\nport into an `s3()` slot and get an `S3Config` binding; they build their own\nS3 client (aws-sdk, or a hand-rolled SigV4 client) from it.\n\nShips as the `@prisma/composer-prisma-cloud/storage` subpath (like `/cron`).\n\n## Contract scope\n\nThe contract **is** the S3 wire protocol — but only the subset a real consumer\nneeds, not S3-compatibility maximalism. In scope:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /{bucket}/{key}` | `content-type` optional; returns a quoted SHA-256 ETag (opaque to consumers) |\n| `GET /{bucket}/{key}` | optional `Range: bytes=a-b` (inclusive end; open end `a-`) → `206`; missing → `404` |\n| `HEAD /{bucket}/{key}` | `etag` + `content-length`; missing → `404` |\n| `DELETE /{bucket}/{key}` | idempotent (a missing key is success) |\n| `GET /{bucket}?list-type=2` | `prefix`, `continuation-token`, `max-keys` (default 1000); ListObjectsV2 XML |\n| Presigned GET/PUT | query-param SigV4, expiry enforced |\n\nAuth is SigV4 (`AWS4-HMAC-SHA256`), **path-style addressing only**, any region\nstring (`auto` is fine). Bucket names simply namespace keys — there is no\nbucket CRUD.\n\n**Out of scope**: multipart upload, `CopyObject`, batch `DeleteObjects`,\nconditional requests, flexible checksums / `aws-chunked` framing (rejected with\n`501` — see the wiring note below), bucket CRUD, ACLs, versioning, lifecycle.\n\nSee [`CONTRACT-SCOPE.md`](./CONTRACT-SCOPE.md) for the full op semantics and the\nexact out-of-scope list.\n\n## Envelope\n\nObjects up to **~16 MiB**. Each object is one row's `bytea` value; ranged reads\nuse SQL `substring(...)` so a range request never loads the whole object. This\nis comfortably within Postgres `bytea`/TOAST for the target workload — it is\n**not** a general-purpose large-blob store, and larger objects are unsupported.\n\n## Wiring\n\nProvision `storage()` in a module and wire its `store` port into a consumer's\n`s3()` slot:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport blobs from './src/blobs/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage()); // owns its Postgres + minted credentials\n  provision(blobs, { deps: { store: store.store } });\n});\n```\n\n```ts\n// src/blobs/service.ts — the consumer declares an s3() dependency\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { s3 } from '@prisma/composer-prisma-cloud/storage';\n\nexport default compute({\n  name: 'blobs',\n  deps: { store: s3() },\n  build: node({ module: import.meta.url, entry: '../../dist/blobs/server.mjs' }),\n});\n```\n\n```ts\n// src/blobs/server.ts — the consumer's entry builds its own client (ADR-0015)\nimport { S3Client } from '@aws-sdk/client-s3';\nimport service from './service.ts';\n\nconst { store } = service.load(); // S3Config: { url, bucket, accessKeyId, secretAccessKey }\n\nconst client = new S3Client({\n  region: 'auto',\n  endpoint: store.url, // path-style; no virtual-host addressing\n  forcePathStyle: true,\n  credentials: { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey },\n  // The store rejects aws-chunked / flexible-checksum PUTs with 501 — send plain\n  // signed payloads.\n  requestChecksumCalculation: 'WHEN_REQUIRED',\n});\n```\n\nThe `S3Config` binding is the whole surface a consumer sees:\n\n```ts\ninterface S3Config {\n  readonly url: string; // the store's endpoint\n  readonly bucket: string;\n  readonly accessKeyId: string;\n  readonly secretAccessKey: string;\n}\n```\n\n[`examples/storage`](../../../../examples/storage) is the worked example — a\nsmall blob store/serve app that consumes `storage()` and deploys to Prisma\nCloud.\n\n## Local development\n\nThe same module runs locally against local Postgres — no cloud, no minted\ncredentials. `@prisma/composer-prisma-cloud/storage/testing` exposes the store\nand server directly:\n\n```ts\nimport { createPgStore, startStorageServer } from '@prisma/composer-prisma-cloud/storage/testing';\n\nconst store = await createPgStore(process.env.DATABASE_URL!); // applies the schema\nconst server = startStorageServer({\n  store,\n  credentials: { accessKeyId: 'local', secretAccessKey: 'local-secret' },\n  bucket: 'my-bucket',\n  port: 0, // ephemeral\n});\n\n// server.url is an S3 endpoint — point an aws-sdk client (path-style) at it.\n// server.stop() when done.\n```\n\nThe module's own tests, and `examples/storage`'s integration test, boot exactly\nthis stand-in over a throwaway Postgres: they honor `STATE_TEST_DATABASE_URL`\nwhen set, otherwise self-spawn an ephemeral Homebrew `postgresql@15` cluster\n(`initdb`/`pg_ctl`); they skip on a dev machine with no Postgres and fail on CI\nif none is available.\n\n## Credentials\n\nThe SigV4 key pair is **minted once at deploy** (a random keypair persisted in\ndeploy state) and delivered to consumers through the `S3Config` binding — it is\nnever printed and never surfaces outside the deployment. Consumers are\ntherefore **in-deployment services** that receive the credentials via `load()`,\nnot arbitrary external clients. An external-access path (reading the minted\ncredentials from outside the deploy) is a recorded platform ask, not something\nthis module solves.\n\n<!-- File: packages/1-prisma-cloud/2-shared-modules/streams/README.md (Tokens: ~1971 | Category: plugin-manifest) -->\n# `@prisma/composer-prisma-cloud/streams`\n\nDurable append-only event streams as a Prisma Composer module. It wraps the\nproduction `@prisma/streams-server` runtime (npm, unmodified) as a Compute\nservice behind a typed boundary: the module's `store` dependency takes a\n`storage()` module's port as its durable tier, and it exposes a single\n`streams` port. A consumer names the streams it uses with\n`streamsContract(defs)`, and its `durableStreams(contract)` dependency\nhydrates to one ready **`StreamHandle`** per declared name — like RPC's\ngenerated client, no app hand-rolls the protocol, and no app carries a\nstream-lifecycle constant: the handle owns creating the stream on first use\nand healing a 404 by re-creating and retrying once. The wire binding\nunderneath is `{ url, apiKey }`, the key minted by the deploy.\n\nShips as the `@prisma/composer-prisma-cloud/streams` subpath (like `/storage`).\n\n## Contract scope\n\nA contract names its streams:\n\n```ts\nconst jobLog = streamsContract({\n  jobs: streamDef(),   // untyped in this slice — events type as `unknown`\n  audit: streamDef(),\n});\n```\n\nHydration hands a consumer one handle per declared name:\n\n```ts\ninterface StreamHandle {\n  append(event): Promise<void>; // one JSON event; NEVER retried beyond the 404 heal below\n  read<T>(opts?): Promise<{ events: T[]; nextOffset: string }>;\n  tail<T>(opts?): Promise<{ events: T[]; nextOffset: string; timedOut: boolean }>;\n}\n```\n\nNo `create` — a handle creates its stream on first use, memoized, and heals a\n404 (the stream vanished from the durable tier) by dropping that memo,\nre-creating, and retrying the failed operation once. That heal is safe even\nfor an append: a 404 is generated INSTEAD OF a write at every layer, so it\nproves nothing was applied.\n\nFor dynamic stream names (e.g. per-tenant streams), call `durableStreams()`\nwith no contract — the `rawPostgres()` parity, same lifecycle ownership, the\nname is data rather than a wiring-time declaration:\n\n```ts\ninterface StreamsClient {\n  stream(name: string): StreamHandle;\n}\n```\n\nThe wire binding underneath is the typed connection config (ADR-0015) —\n`{ url: string, apiKey: string }` — and the client wraps\n[`@durable-streams/client`](https://www.npmjs.com/package/@durable-streams/client)\n(ElectricSQL's canonical protocol client, pinned to the version\n`@prisma/streams-server` 0.1.11's own repo pairs with). The full protocol\nsurface it drives:\n\n| Op | Notes |\n| --- | --- |\n| `PUT /v1/stream/{name}` | create (idempotent; `content-type` fixes the stream's type) |\n| `POST /v1/stream/{name}` | append a JSON array of events (`stream-closed: true` header closes) |\n| `GET /v1/stream/{name}?offset=…` | read from an offset; `-1` = start; `format=json` |\n| `GET …&live=long-poll&timeout=…` | held read — returns when fresh events arrive or timeout |\n| `GET …&live=sse` | SSE tail (see the deployed live path note below) |\n\nOffsets are **opaque cursors**, not numeric indices: take them from a read's\n`nextOffset` and pass them back verbatim.\n\n**Auth rides the binding.** The bearer key is not an ADR-0029 secret (there\nis no external value to bind) and not a producer output. The `apiKey`\nconnection param declares an [ADR-0031](../../../../docs/design/90-decisions/ADR-0031-provisioned-param-values-are-a-need-resolved-through-a-target-registry.md)\n**provisioning need**: the deploy target mints the value, keeps it stable in\ndeploy state, and fills the param like any other input. Declaring a\n`durableStreams()` dependency is the whole of the wiring — there is no secret\nslot and nothing to bind at the root. Every endpoint, including `/health`,\nrequires `Authorization: Bearer <key>`.\n\nTwo consequences worth knowing:\n\n- **One key per streams module.** The provisioner mints per provider, not per\n  edge, because `@prisma/streams-server` authenticates a single `API_KEY` —\n  every consumer of one `streams()` instance holds the same value. Cardinality\n  is provisioner policy (ADR-0031), so per-edge keys are later a change of\n  that policy plus an accepted-set provider param once the upstream server\n  takes a key set: no resource to add, no core change, nothing here to delete.\n- **No consumers, no key.** The need lives on the consumer's edge, so a\n  `streams()` module nothing depends on never gets a key minted, and its\n  server refuses to boot rather than serve unauthenticated. Wire a consumer,\n  or drop the module.\n\n## Wiring\n\nThe root provisions `storage()` as the durable tier and wires its `store`\nport into `streams()` — the key needs no wiring at all:\n\n```ts\n// module.ts — the deploy root\nimport { appRoot } from '@prisma/composer';\nimport { storage } from '@prisma/composer-prisma-cloud/storage';\nimport { streams } from '@prisma/composer-prisma-cloud/streams';\nimport worker from './src/worker/service.ts';\n\nexport default appRoot('my-app', ({ provision }) => {\n  const store = provision(storage());\n  const events = provision(streams(), { deps: { store: store.store } });\n  provision(worker, { deps: { streams: events.streams } });\n});\n```\n\n```ts\n// src/worker/service.ts — the consumer. Declaring the dependency is what\n// causes the key to be minted; nothing names it a second time.\nimport node from '@prisma/composer/node';\nimport { compute } from '@prisma/composer-prisma-cloud';\nimport { durableStreams, streamDef, streamsContract } from '@prisma/composer-prisma-cloud/streams';\n\nconst jobLog = streamsContract({ jobs: streamDef() });\n\nexport default compute({\n  name: 'worker',\n  deps: { streams: durableStreams(jobLog) },\n  build: node({ module: import.meta.url, entry: '../../dist/worker/server.mjs' }),\n});\n```\n\n```ts\n// src/worker/server.ts — append, then wait for what follows\nimport service from './service.ts';\n\nconst { streams } = service.load(); // { jobs: StreamHandle }, ready to call\n\nawait streams.jobs.append({ kind: 'created' });\nconst { events, nextOffset } = await streams.jobs.read();\nconst next = await streams.jobs.tail(); // resolves on the next event (or timedOut)\n```\n\nFor local development and tests, build the same client against the stand-in\n(no deployed binding, no auth):\n\n```ts\nimport { StreamsClient } from '@prisma/composer-prisma-cloud/streams';\n\nconst client = new StreamsClient({ url: standIn.url, apiKey: 'unused' });\nconst jobs = client.stream('jobs'); // a StreamHandle, same surface as the hydrated binding\n```\n\n[`examples/streams`](../../../../examples/streams) is the worked example — the\nmodule deployed to Prisma Cloud with `storage()` as its tier and a `jobs`\nservice consuming the binding, plus local integration tests and a deployed\nconsumer smoke script.\n\n## Local development\n\n`@prisma/composer-prisma-cloud/streams/testing` embeds the local stand-in\n(`@prisma/streams-local`): SQLite-only, loopback, **no auth, no object store,\nno cloud credentials** — the same protocol surface.\n\n```ts\nimport { startLocalStreamsServer } from '@prisma/composer-prisma-cloud/streams/testing';\n\nconst server = await startLocalStreamsServer({ name: 'dev', port: 0 });\n// server.exports.http.url is a Durable Streams endpoint (no Authorization needed).\n// await server.close() when done.\n```\n\nThe stand-in persists under `DS_LOCAL_DATA_ROOT`; tests point that at a\nthrowaway directory. The full conformance suite runs against it with no\ncredentials: `pnpm test:conformance:local` (and against a deployment:\n`CONFORMANCE_TEST_URL=… STREAMS_API_KEY=… pnpm test:conformance:deployed`).\n\n## Deployed live path: use long-poll\n\nThe Compute ingress currently buffers HTTP responses until the upstream\nresponse completes. An open `?live=sse` tail therefore never delivers through\na deployment's public URL — the client sees zero bytes and the edge returns a\n504 after ~60s — while the same request works locally and against the\nstand-in. `?live=long-poll` completes per response and delivers live events\nend to end through the ingress, so `StreamHandle.tail` long-polls. The\ndeployed conformance harness keeps the SSE tests, so they flip green when the\nplatform supports streaming responses.\n</yakaai_skills>"}