[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7801468DT12TXAJSZV53S0Q":3,"skill-same:01M7801468DT12TXAJSZV53S0Q":55},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7801468DT12TXAJSZV53S0Q","effect-v4-services-layers",null,"Use when defining Effect v4 services or wiring Layers — the `Context.Service` class form (type params first, then the id), Layer construction (succeed\u002Feffect, scoped is gone), composition (mergeAll vs provide vs provideMerge), providing once at the boundary, and the memoization discipline that keeps a db pool or HTTP client from being built twice. Consult before reaching for any service or layer name you have not verified.","spencerbeggs\u002Feffected","spencerbeggs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F109114?v=4","01M77ZTHB70K5Y2VVTRCFY50A5","C. Spencer Beggs","01M77ZTHCC41NXBT3X906K6QM1",8,"MIT","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fbuilds\u002Fclaude\u002Fskills\u002Feffect-v4-services-layers\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: effect-v4-services-layers\ndescription: Use when defining Effect v4 services or wiring Layers — the `Context.Service` class form (type params first, then the id), Layer construction (succeed\u002Feffect, scoped is gone), composition (mergeAll vs provide vs provideMerge), providing once at the boundary, and the memoization discipline that keeps a db pool or HTTP client from being built twice. Consult before reaching for any service or layer name you have not verified.\n---\n\n# Services & Layers (Effect v4)\n\n**API surface** — existence, signatures and the source line citations below —\nverified by reading `packages\u002Feffect\u002Fsrc`. The **behavioural** claims (the\nmemoize-by-reference resource-count result, the two temporal-dead-zone\nresults, the sync-facade and requirement-union notes) were probed once and\nnot re-probed on every catalog advance; treat them as behavior to spot-check\nagainst a control before leaning on them for something load-bearing.\n\nA service is a typed key into the runtime's context; a layer is the recipe that\nbuilds it. Get three things right — the one service form, provide-once\ncomposition, and memoization by\nreference — and the wiring stays honest and cheap. For what any core module\n*is* and when to reach for it, see `effect-v4-module-index`; to settle whether a\nname exists at all, `effect-v4-source-lookup`.\n\n## One service form: `Context.Service`\n\n`Context.Tag`, `Context.GenericTag`, `Effect.Tag`, and `Effect.Service` are\n**all gone** — every service collapses to `Context.Service`. The class form\nis preferred; the id and shape live in one place:\n\n```ts\nimport { Context, Effect, Layer } from \"effect\"\n\nclass Database extends Context.Service\u003CDatabase, {\n readonly query: (sql: string) => Effect.Effect\u003Cstring>\n}>()(\"Database\") {}\n```\n\nArgument order is **type params first** via `Context.Service\u003CSelf, Shape>()`,\n**then** the id string via `(\"Database\")` — the id comes last, and there is no\n`Context.Tag`.\n\n**Tags are Effects.** A service key is a\nfirst-class Effect — `Context.Key\u003CIdentifier, Shape> extends\nEffect\u003CShape, never, Identifier>` (`Context.ts:68`) — so\n`yield* Database` works, and combinator-style consumer code like\n`Effect.flatMap(Database, (db) => …)` composes directly with no `.asEffect()`\nor unwrap step. Related gotcha when hunting the source: the module is\n`Context.ts`; there is no `ServiceMap.ts`.\n\nThe `Database` form above — `Context.Service\u003CSelf, Shape>()(\"id\")` with **no\n`make` option** — is the **contract-only** service: it declares a shape but\nbakes in no default impl. There is no `.layer` to inherit; wire it with a\nseparate `Layer.succeed(Database, { query: … })` bound to a named `const` (first\nboundary port). Reach for it when the implementation is supplied at the edge (or\ndiffers per environment) rather than owned by the service.\n\n**Shape-inferred `make` form** — implementation and API stay together, TS\nderives the shape. Prefer it when the impl is small; prefer the explicit\ngeneric shape when you want the contract stated before the code:\n\n```ts\nclass UserRepo extends Context.Service\u003CUserRepo>()(\"UserRepo\", {\n make: Effect.gen(function* () {\n  const config = yield* Config;\n  return { getById: (id: string) => Effect.succeed({ id, from: config.url }) };\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(ConfigLayer));\n}\n```\n\nTwo traps:\n\n- `make` stores the constructor effect but does **NOT** auto-generate a\n  layer — there is no `.Default`. Build the layer yourself (above).\n- There is **no `dependencies` option**. A service's needs are wired with\n  `Layer.provide`, not declared on the service.\n\n## Typing a value that implements a service's interface\n\nWhen a **factory returns an implementation** — a second `Layer` satisfying an\nexisting contract, a test double, a per-directory resolver — you need a name for\nthe service's *shape*, not for the service key. Two spellings resolve to the\nsame type, and one of them is the documented helper:\n\n```ts\n\u002F\u002F Preferred: the named helper in the Service namespace.\nfunction makeWorkspaceResolver(\n rootDir: string,\n): Context.Service.Shape\u003Ctypeof RegistryResolver> {\n return { resolve: (name) => Effect.succeed(`${rootDir}\u002F${name}`) };\n}\n\n\u002F\u002F Equivalent: indexed access through the key's witness property.\nfunction makeOther(dir: string): (typeof RegistryResolver)[\"Service\"] { ... }\n```\n\n`Context.Service.Shape\u003CT>` is `T extends Key\u003Cinfer _I, infer S> ? S : never`\n(`Context.ts:420`), and it sits in a namespace whose own doc example is titled\n\"Extracting service types\" — core states this as the way to name a service's\nshape, so **prefer it**. The indexed form works for the same reason it reads\nwell: `Context.Key\u003CIdentifier, Shape>` carries `readonly Service: Shape` as a\nreal property (`Context.ts:70`), so `(typeof Tag)[\"Service\"]` is an ordinary\nlookup rather than a trick. The sibling `Context.Service.Identifier\u003CT>` extracts\nthe `R`-channel identifier the same way.\n\n**The trap this replaces: the class instance type is not the shape.** Reaching\nfor the obvious annotation — the class's own name — does not compile:\n\n```ts\n\u002F\u002F WRONG. RegistryResolver (the instance type) is not { resolve: ... }.\nfunction makeWorkspaceResolver(dir: string): RegistryResolver { ... }\n\u002F\u002F error TS2353: Object literal may only specify known properties,\n\u002F\u002F and 'resolve' does not exist in type 'RegistryResolver'.\n```\n\nA class-form key's instance type is `ServiceClass.Shape\u003CIdentifier, Shape>`\n(`Context.ts:151`), a three-member wrapper — the `ServiceTypeId` brand, `key`,\nand a `Service` member holding the real shape. The interface you want is nested\none level inside it, which is exactly what both spellings above unwrap.\n\n**Taking a consumer's key over your shape?** Pin the shape. A\nparameter typed `Context.Key\u003CI, Shape>` or `Context.Service\u003CI, Shape>`\naccepts a key over a **wider** shape, because class keys compare structurally\nand method bivariance makes that covariant. The fix is\n`Context.Key\u003CI, S> & ([Shape] extends [S] ? unknown : never)` with\n`S extends Shape`; a key that adds members then errors as \"not assignable to\nparameter of type 'never'\". It cannot see through method-syntax parameter\nbivariance (a member redeclared as a method with a wider parameter still\npasses). If the shape is generic (`Shape\u003CA>`), also intersect\n`Context.Key\u003CI, Shape\u003CA>>`, or `A` is no longer inferred from the key. See\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n## Access a service: prefer `yield*`\n\n`yield*` on the class pulls the implementation and leaves the dependency\n**explicit in the effect's `R`**, where the type system tracks it:\n\n```ts\nconst program = Effect.gen(function* () {\n const db = yield* Database;\n return yield* db.query(\"SELECT 1\");\n});\n```\n\n`use` \u002F `useSync` are static accessors — the only ones; there is no generated\nproxy accessor per method. Reach for them sparingly — they hide *which* dependency you\npulled at the call site, making it easy to leak a service dep into a return\nvalue:\n\n```ts\nDatabase.use((db) => db.query(\"SELECT 1\")); \u002F\u002F Effect\u003Cstring, never, Database>\nConfig.useSync((c) => c.url);               \u002F\u002F pure callback ⇒ Effect\u003Cstring, never, Config>\n```\n\n`use` takes an effectful callback and returns `Effect\u003CA, E, R | Self>`;\n`useSync` takes a **pure** callback and returns `Effect\u003CA, never, Self>` (it just\nlets the accessor body be synchronous — both still return an `Effect`). There is\nno mapped-type proxy that mints an accessor per method: such a proxy **erases\ngenerics** — a `get\u003CT>(key): Effect\u003CT>` collapses to `Effect\u003Cunknown>` and\noverloads are lost — which is why `use`\u002F`useSync`, or plain `yield*`, are the\nwhole accessor story and preserve the real method signatures.\n\n**The class IS the Effect — there is no `.asEffect()`.** `class Database\nextends Context.Service\u003C...>()(\"Database\")` is itself an\n`Effect\u003CShape, never, Database>`, so pass the class wherever an Effect goes:\n`Effect.flatMap(Database, (db) => ...)`, `Database.pipe(Effect.map(...))`, or\nas a value typed `Effect.Effect\u003CDatabase[\"Service\"], never, Database>`.\n`.asEffect()` is `Effectable.Class`'s abstract method, not a service's;\ncalling it on a service class is a type error, not a conversion you forgot.\n\nFor a config knob \u002F feature flag with a default (not a full API), use\n`Context.Reference\u003CT>(id, { defaultValue: () => ... })` instead of a\nservice.\n\n## Layers: build, compose, provide once\n\n`Layer\u003CROut, E, RIn>` — `ROut` services produced, `E` construction\nfailures, `RIn` dependencies required to build.\n\n- **`Layer.succeed(Service)(impl)`** — a pure, already-built value; no deps,\n  no scope.\n- **`Layer.effect(Service)(effect)`** — effectful construction that may\n  depend on other services **and\u002For own a scoped resource** (db pool,\n  socket, worker). Its return type is `Layer\u003CI, E, Exclude\u003CR, Scope>>`: it\n  strips `Scope` from `R`. That is exactly why there is **no `Layer.scoped`** —\n  `Layer.effect` over an `Effect.acquireRelease` effect *is* the scoped\n  constructor:\n\n```ts\nconst DatabaseLayer = Layer.effect(Database)(\n Effect.gen(function* () {\n  const config = yield* Config;\n  const pool = yield* Effect.acquireRelease(\n   openPool(config.url),\n   (p) => p.close(),\n  );\n  return { query: (sql) => pool.run(sql) };\n }),\n);\n```\n\n`Layer.succeed` and `Layer.effect` are **dual**: the curried\n`Layer.effect(Service)(effect)` is primary, but the data-first\n`Layer.effect(Service, effect)` overload also works (handy for\n`Layer.effect(this, this.make)`). Both compile.\n\n### In a layer static, refer to the service as `this`\n\nA `layer` static that names its own class is fine **when the service is a class\ndeclaration** — `export class Db extends Context.Service...()` initializes the\nclass's inner binding before static initializers run, so `Layer.succeed(Db, …)`\ninside `Db`'s own body resolves.\n\nIt is a **temporal dead zone** when the service is a class **expression bound to\na `const`**, because then there is no inner binding and the name resolves to the\nouter `const`, which is still uninitialized while the class body evaluates:\n\n```ts\n\u002F\u002F THROWS at import time: \"Cannot access 'BunResolver' before initialization\"\nexport const BunResolver = class extends Context.Service()(\"BunResolver\", {}) {\n static layer = mk(BunResolver, …);   \u002F\u002F ← outer const, still in TDZ\n};\n\n\u002F\u002F Fine — `this` is the class, always:\nexport const BunResolver = class extends Context.Service()(\"BunResolver\", {}) {\n static layer = mk(this, …);\n};\n```\n\nProbed: the class-expression form throws, the `this` form does not,\nand the class-*declaration* form does not either.\n\n**Write `this` unconditionally.** It is correct in both forms, so it costs\nnothing and removes the whole question — and the failure it prevents is a\nfalse green:\n\n> The module throws **at import time** while **typechecking completely clean**.\n> The only signal is vitest reporting **`0 tests passed` with exit 0** for every\n> file that imports it. A suite that collects zero tests is not a passing suite.\n> See `effect-v4-testing`.\n\n**A second trigger, which fires on a class *declaration* too: a static that reads\na module-local `make` declared further down the file.** The rule above covers the\nclass's own name; this one covers anything the static initializer touches\neagerly:\n\n```ts\n\u002F\u002F THROWS at import: \"Cannot access 'make' before initialization\" — and typechecks clean\nexport class Repo extends Context.Service\u003CRepo, Shape>()(\"Repo\") {\n static readonly layer = Layer.effect(this, Effect.map(Dep, make));\n}\nconst make = (dep: Dep): Shape => ({ … });   \u002F\u002F ← evaluated AFTER the class body\n\n\u002F\u002F Fine — the arrow defers the read to layer-BUILD time:\n static readonly layer = Layer.effect(this, Effect.map(Dep, (dep) => make(dep)));\n```\n\n`Effect.map(Dep, make)` reads `make` while the static initializer runs — import\ntime; `(dep) => make(dep)` reads it when the layer is built. Same false green.\nThe arrow is correct in both declaration orders, so write it unconditionally.\n\n### Resolve a dependency once at construction — only when it is stable\n\nA service built with `Effect.gen` resolves whatever it `yield*`s **when the layer\nis built**. Right for a pool, a client, a decoded config; wrong for anything a\ncaller is meant to vary. **Stable ⇒ resolve in `make`** and every call shares the\ninstance. **Varying it is the point ⇒ read it per call**, keeping it in the\nmethod's `R`, so a caller's `Effect.provideService(op, Dep, other)` reaches the\ncode that uses it.\n\nGetting this backwards is **silent**. A `Repo` resolved at construction made\n`Repo.provide(…)` decorative: the wrapper compiled, ran, and changed nothing,\nbecause the service had already captured the ambient instance. Nothing in the\ntypes distinguishes the two — only a test that provides a *different* instance\nand asserts the difference does. (Caught that way in the github work.)\n\nName the primary layer **`layer`** (e.g. `Database.layer`), never `Default` or\n`Live`. Use suffixes for variants (`layerTest`). The one exception\nis the `index.ts` composite convenience export that merges two concept modules'\nprimary layers — `Default` is the idiomatic name there (see **Cycle-avoidance**\nbelow); it is not a service's own primary layer, so it does not violate this\nrule.\n\n### A layer static belongs to the module owning the dependency, not the service\n\n**Statics on one class share one module**, and a module is the unit of\nreachability — so a layer variant needing something the service's own module must\nnot reach moves out:\n\n> A layer-family static belongs to the module that **owns the dependency it\n> needs**, not to the module that **declares the service**.\n\nThree uses in the kit: `GitHubApp.clientLayer` (confines the JWT signer),\n`Workspaces.localExecLayer` (builds `@effected\u002Fcommands`' service, so `commands`\nkeeps zero `@effected\u002F*` edges), `GitHubCacheBlobStore.layer` (confines\n`@azure\u002Fstorage-blob`). Such a static is named for its **variant**, not `layer`.\nTest: *would putting this static on the service class make a dependency reachable\nfrom a consumer that does not use it?*\n\n### Swappable contracts: no ambient default, and ship values too\n\nWhen the implementation is a **policy choice** the consumer must make, two rules:\n\n1. **No ambient default in the composite layer.** `Layer.mergeAll` is\n   **last-wins**, so `Layer.mergeAll(myDetector, Pkg.layer())` — the natural\n   spelling of an override — silently loses to a merged-in default. Leave the\n   requirement in `R`: wiring that forgets to choose does not compile, and\n   consumers who never call the operation never supply a policy.\n2. **Ship every implementation as a VALUE as well as a layer** (`static readonly\n   npm: Shape` beside `static readonly layerNpm = Layer.succeed(this, this.npm)`).\n   A consumer composing *around* the default cannot use a layer without\n   re-entering the tag it is replacing; given the value, the wrapper is one\n   delegating `Layer.succeed`.\n\nReasoning and the `PublishabilityDetector` precedent:\n[references\u002Fservice-design.md](.\u002Freferences\u002Fservice-design.md), which also\ncarries the layer-static and value-only-service rules in full.\n\n### Composition operators\n\n| Operator | Feeds deps? | Keeps dep outputs? | Use for |\n| --- | --- | --- | --- |\n| `Layer.mergeAll(a, b, …)` | **no** | — (side by side) | combine outputs of independent layers |\n| `Layer.provide(target, deps)` | yes | **no** — only `target` | hide construction deps behind a narrow public layer |\n| `Layer.provideMerge(target, deps)` | yes | **yes** — target + deps | assemble larger app layers where downstream still needs the deps |\n\n> **Trap:** `Layer.mergeAll(ConfigLayer, DatabaseLayer)` does **not** satisfy\n> `DatabaseLayer`'s need for `Config` — merge only places them side by side.\n> Use `provide` \u002F `provideMerge` to actually feed a dependency.\n\n**Compose subsystems locally, assemble one app layer, `Effect.provide`\nonce at the boundary.** Keep subsystem wiring named and local; the app\nlayer should read as a high-level map:\n\n```ts\nconst DbSubsystem = Layer.provide(DatabaseLayer, ConfigLayer);\nconst AppLayer = Layer.mergeAll(DbSubsystem, HttpLayer).pipe(Layer.provide(Telemetry));\n\nEffect.runPromise(program.pipe(Effect.provide(AppLayer))); \u002F\u002F provide at the OUTERMOST edge\n```\n\n> **Cycle-avoidance (first boundary port):** put a composite layer that merges\n> two concept modules — e.g. `Default = Layer.mergeAll(A.noop, B.noop)` — in\n> `index.ts`, not in one of the concept modules. If it lived in module `A`, and\n> `B` imports `A`, the merge would pull `A → B → A` into a cycle\n> (`noImportCycles` is an error here). The entrypoint already depends on both\n> concept modules, so hanging the composite there keeps the concept modules\n> import-cycle-free.\n\nBusiness logic *requires* services (they stay in `R`); composition happens\nin layers; `Effect.provide` happens at the app \u002F test entry point.\n`Effect.provide` deep inside business logic is an anti-pattern — it hides\nwiring, blocks test substitution, and spawns many small runtimes. For\nseveral entry points (HTTP handlers, consumers, cron), build one\n`ManagedRuntime.make(AppLayer)` and run each entry against it.\n\n**Heterogeneous requirement unions need an up-front annotation.** Collecting\nseveral values generic in a requirements union (an array of resolvers, a list of\nlayers feeding one generic parameter) pins the type parameter from the **first**\nelement; the later, wider elements are rejected rather than widening the union.\nAnnotate the collection where it is built —\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n> **Type helpers are top-level.** `Layer.Success\u003Ctypeof L>` and\n> `Layer.Error\u003Ctypeof L>` are module-level type exports (v4 source\n> `Layer.ts:189` \u002F `:173` — resolve the tree via `effect-v4-source-lookup`).\n> There is no nested `Layer.Layer.Success` spelling to reach for.\n\n## Platform capabilities: require in R, never own a backend\n\nEffect v4's consolidated core **declares** the platform service contracts —\n`FileSystem`, `Path`, `Terminal`, `Stdio` as top-level `effect\u002F*` modules, and\n`ChildProcessSpawner` (subprocesses) under `effect\u002Fprocess` — while the\n**implementations** live in `@effect\u002Fplatform-*` (Node's `NodeServices.layer`\nprovides `ChildProcessSpawner | FileSystem | Path | Stdio | Terminal`\nin one layer; crypto is not in it — the `effect\u002Fcrypto` services such as\n`Digest` come from `NodeCrypto.layer` or a family layer like\n`NodeCrypto.layerDigest`, or core's `Digest.layerWebCrypto`; a consumer's own doc\ncomment saying `NodeServices.layer` provides crypto is stale, so fix it). All of these contracts are tagged `@stability unstable` — a\nminor `effect` release may change their shape — which does not change the\nrule below; it means a library re-verifies its usage when the installed\n`effect` moves. That split fixes the house default:\n\n- **A library that needs a platform capability requires the core-declared\n  service in its `R` channel** and the application provides the platform layer\n  once at the edge. Requiring-in-R is free — it adds no dependency edge and no\n  tier cost. This is how `walker`, `xdg` and `config-file` consume\n  `FileSystem`, and how anything subprocess-shaped consumes\n  `ChildProcessSpawner`.\n- **Taking `@effect\u002Fplatform-*` as a dependency edge is categorically\n  different** — it drags the platform package into every consumer's tree\n  (integrated tier). Do not conflate the two: \"platform-node is tier 3\" is a\n  statement about dependency edges, never about `R`.\n- Platform packages are legitimate **devDependencies for integration tests**,\n  and legitimate **dependencies only in applications and app-edge packages**\n  (a CLI binary, a server entrypoint).\n- **A direct `node:` import in library code is a code smell**, most of the\n  time. The sanctioned exceptions are documented Node-only overlays — a\n  default layer or a sync escape hatch — never a contract or a\n  business-logic path.\n\nBefore designing any service or seam, grep the core source — the\n`@stability unstable` namespace modules included, since they import exactly\nlike any other core module rather than living under a separate path — for an\nexisting contract (`effect-v4-source-lookup` resolves the tree). A parallel subprocess vocabulary (`Command`\u002F`CommandRunner` plus a\nhand-rolled `node:child_process` layer) survived four review gates in this repo\nbefore a source check found `effect\u002Fprocess` already declared all of it.\n\n## Sync facades: per-call service values, not layers\n\nA synchronous escape hatch over consumer-supplied ops (build-tool plugin hooks,\nconfig-time contexts) takes service **values** provided per call with\n`Effect.provideService` — never a Layer, so consecutive calls carrying different\nops cannot hit the memoize-by-reference trap below. The `FileSystem.makeNoop` \u002F\nhand-rolled-`Path` recipe and the honest `runSyncExit` unwrap:\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n## Memoization: layers build once, by reference\n\nWithin one provided layer graph, the same layer *value* is built exactly\nonce, however many composites reference it. Across `Effect.provide` calls\nthe rule depends on nesting: a provide's build adds its `MemoMap` to the\ncontext (`Layer.ts:678`), and a provide running **inside** it forks that\nmap (`CurrentMemoMap.forkOrCreate`, `Layer.ts:601`), so a nested provide\nreuses what the enclosing one built:\n\n```ts\nconst main = program.pipe(Effect.provide(DbSubsystem), Effect.provide(DbSubsystem));\n\u002F\u002F Built ONCE — the inner provide forks the outer provide's MemoMap.\n```\n\nProvides that are **not** nested — one after another, or siblings under a\ncommon parent — each start their own map and build again (probed: nested\n1 build, sequential 2, siblings under one outer provide 2). A warm-up\n`Effect.scoped(Layer.build(L))` followed by `program.pipe(Effect.provide(L))`\nis two sequential builds.\n\nIdentity is **by reference**, and that is the footgun. A function that\n*returns* a layer mints a **fresh reference every call**, defeating\nmemoization and building the underlying resource (pool, HTTP client,\ntelemetry) more than once:\n\n```ts\n\u002F\u002F BAD — two distinct references, resource built twice:\nconst AppLayer = Layer.mergeAll(makeDatabaseLayer(), makeDatabaseLayer());\n\n\u002F\u002F GOOD — call once, bind to a const, reuse the reference:\nconst DatabaseLayer = makeDatabaseLayer();\nconst AppLayer = Layer.mergeAll(DatabaseLayer, OtherLayer);\n```\n\nProbed, counting resource opens: an inline factory call at two\nprovide sites opened the resource **twice**; the same factory called once and\nbound to a `const` opened it **once**. The two-provide dedup is real, but it can\nonly dedup a reference it can recognize.\n\n**A parameterized layer static is exactly this shape.** `static readonly layer =\n(opts) => Layer.effect(...)` is a factory, and every `Svc.layer(opts)` at a\nprovide site is a fresh reference — the \"it's a static, so it must be a\nsingleton\" intuition is false.\n\nLearn the **symptoms**, because the type system reports nothing and the tests\nmostly pass:\n\n- two database connections opened against one file;\n- two ledgers \u002F caches \u002F counters, each holding half the writes;\n- **a `PubSub` where each subscriber sees only half the events** — the publisher\n  and the subscriber resolved *different* instances.\n\nAnything that looks like \"state mysteriously split in two\" is this bug until\nproven otherwise.\n\n**A cousin with a different fingerprint: two resolved copies of one package\nare two DISTINCT tag identities.** When a dependency graph resolves two\ncopies of one `@effected` package (a caret range and a newer 0.x minor\nresolving separately), a layer built from one copy does not satisfy a\nrequirement expressed by the other — and it surfaces as **\"service not\nprovided\" in a graph that visibly provides it**, never as a version error,\nsending the reader hunting a signature change that never happened (observed\n2026-08-14). Two checks answer different halves of it: `pnpm why\n@effected\u002F\u003Cpkg>` says what *resolves*, and grepping a bundle for the\n**fully-qualified tag id** (`@effected\u002F\u003Cpkg>\u002F\u003CService>`, one hit per copy —\nnever the bare class name, which also matches methods, logs and re-exports)\nsays what got *inlined*. Mechanism, diagnosis and mitigation →\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\nDiscipline — **bind layers to named constants**:\n\n- Prefer plain named layer `const`s over layer-returning factories.\n- Write a layer-returning function only when the layer genuinely depends on\n  runtime params — and even then, call it **once** and reuse the result.\n- If a subsystem depends on a parameterized layer, **leave that dependency\n  unprovided** and supply the concrete layer once **at the edge**. Don't\n  call the factory locally inside subsystem wiring — it breaks sharing and\n  hides the dep.\n\nAuto-memoization is a safety net for the multi-provide footgun, not a\nlicense to skip composition. Compose explicitly, provide once.\n\n**Opt out** when you deliberately want a fresh build (test isolation,\nindependent resource pools):\n\n- `Layer.fresh(layer)` — always builds with a fresh memo map, bypassing the\n  shared cache. It isolates only where it wraps: composed layers\n  (`Layer.provide`, `provideMerge`, `mergeAll`) are memoized by identity too,\n  so a composed `const` referenced twice is built once, and a `Layer.fresh`\n  dependency **inside** it is shared with it (probed: 1 build, where\n  `Layer.mergeAll(composed, Layer.fresh(composed))` builds 2). Wrap the\n  composed layer, not its dependency, when each site needs its own copy.\n- `Effect.provide(layer, { local: true })` — builds the layer and its\n  sublayers from a **local** memo map, isolated from other provides.\n\n## Test layers\n\nSwap the layer, not the code: business logic requires `Database`; production\nprovides `Database.layer`, tests provide a fake at the same boundary.\n\n- `Layer.succeed(Service)({ ... })` — a full hand-written fake.\n- `Layer.mock(Service, { ... })` — a **partial** mock; supply only the\n  members the test exercises. Any omitted effect-returning member fails with\n  an unimplemented defect if called, so the mock fails loudly instead of\n  silently returning `undefined`:\n\n```ts\nconst DatabaseTest = Layer.mock(Database, {\n query: (sql) => Effect.succeed(`mocked ${sql}`),\n});\n\nEffect.runPromise(program.pipe(Effect.provide(DatabaseTest)));\n```\n\nKeep test wiring explicit and close to the production composition style —\nthe Live\u002FTest difference should be one swapped layer at the edge, nothing\ndeeper.\n\n### `Layer.mock`'s optionality is earned, not given — and one plain member revokes it\n\n`Layer.mock(Service, impl)` takes `PartialEffectful\u003CS>`, not `Partial\u003CS>`\n(`Layer.ts:2354`). That type is not \"everything optional\" — it splits the shape\non one predicate:\n\n```ts\n\u002F\u002F Layer.ts:2279 — a member is OPTIONAL iff it matches AnyEffectOrStream; else REQUIRED\nexport type PartialEffectful\u003CA extends object> = Types.Simplify\u003C\n  & { [K in keyof A as A[K] extends AnyEffectOrStream ? K : never]?: A[K] }\n  & { [K in keyof A as A[K] extends AnyEffectOrStream ? never : K]: A[K] }\n>\n\u002F\u002F Layer.ts:2288 — AnyEffectOrStream = Effect | Stream | Channel, or a function returning one\n```\n\nSo **any non-effectful member is required in every single mock**: a sync\nfunction, a plain data property, a generic passthrough whose return type does\nnot resolve to `Effect`\u002F`Stream`\u002F`Channel`. Add one and every existing\n`Layer.mock` call site must now spell out that member — the partial mock has\nsilently degraded to `Layer.succeed` with extra ceremony. The type system\nreports it as \"missing property\" errors scattered across the test suite, far\nfrom the service shape that caused them.\n\n**House rule: no non-effectful members on a service shape.** A service is an IO\ncontract. A pure helper belongs on a static, a namespace, or a plain exported\nfunction next to the pure class that owns the algorithm — never inside the\n`Context.Service` shape. That keeps every member effect-valued, which keeps\nevery member optional, which keeps `Layer.mock` doing the one job it exists for.\n\n> **The wrong fix: wrapping the pure helper in `Effect.succeed` to satisfy the\n> rule.** It does buy back optionality — and it is the anti-pattern, not the\n> remedy. It makes every caller pay a `yield*` for a computation that cannot\n> fail, cannot suspend and needs no runtime; it hides a pure function inside an\n> IO contract where nobody will find it; and it makes the thing untestable\n> without a layer, which is exactly the cost the pure-core\u002Feffectful-edge split\n> (see `effect-v4-planning`, pillar 1) exists to avoid. **Move the member off\n> the shape. Do not decorate it into compliance.**\n\n**The one bounded exception: a shape that is entirely ONE immutable value.** The\nrule targets **mixed** shapes, where a pure member revokes the *methods'*\noptionality. A service whose whole contract is data — a resolved environment\nrecord, a set of discovered paths — has no behaviour to mock, so nothing\ndegrades: `Layer.succeed` is the correct and complete double, and `Layer.mock`\nwas never the tool. Apply the criterion, do not pattern-match it: *the entire\nshape is one immutable value with no mockable behaviour* — not \"mostly data\",\nnot \"the methods are trivial\". The boundary is sharp: **the moment a method\nappears, it is a service again**, and the rule above reapplies retroactively to\nevery field. Say so in the service's TSDoc when you declare one.\n\n### `dual` belongs on pure classes, never on a service shape\n\n`Function.dual` (the kit imports it as `Fn`) gives a combinator both the\ndata-first and data-last spelling — `Package.addDependency(pkg, name, spec)`\n*and* `pkg.pipe(Package.addDependency(name, spec))`. That is the right shape on\na **pure** class: `@effected\u002Fpackage-json`'s `Package` and `@effected\u002Fsemver`'s\n`Range` \u002F `SemVer` all use it, and they are pure Schema classes with no layer\nanywhere near them.\n\nPutting a dual member on a `Context.Service` shape costs more than it looks:\n\n- A dual member's declared type is an **overload pair**. Any override — in a\n  `Layer.mock` implementation, in a `Partial\u003CShape>` test-stub argument, in a\n  hand-written fake — must satisfy **both** overloads, not just the one the test\n  calls. The one-line stub that works for every other member\n  (`layerTest({ read: () => Effect.succeed(x) })`) stops compiling, and the fix\n  is to hand-write the full overloaded signature in the test.\n- It is also a non-effectful member by the rule above whenever the data-last\n  branch returns a function rather than an `Effect`, so it is `Layer.mock`-\n  required on top of being overload-shaped.\n\nThe two rules compose into one design instruction: **service shapes carry plain,\nsingle-signature, effect-returning methods. Everything cleverer lives on the\npure class.**\n","# Services & Layers (Effect v4)\n\n**API surface** — existence, signatures and the source line citations below —\nverified by reading `packages\u002Feffect\u002Fsrc`. The **behavioural** claims (the\nmemoize-by-reference resource-count result, the two temporal-dead-zone\nresults, the sync-facade and requirement-union notes) were probed once and\nnot re-probed on every catalog advance; treat them as behavior to spot-check\nagainst a control before leaning on them for something load-bearing.\n\nA service is a typed key into the runtime's context; a layer is the recipe that\nbuilds it. Get three things right — the one service form, provide-once\ncomposition, and memoization by\nreference — and the wiring stays honest and cheap. For what any core module\n*is* and when to reach for it, see `effect-v4-module-index`; to settle whether a\nname exists at all, `effect-v4-source-lookup`.\n\n## One service form: `Context.Service`\n\n`Context.Tag`, `Context.GenericTag`, `Effect.Tag`, and `Effect.Service` are\n**all gone** — every service collapses to `Context.Service`. The class form\nis preferred; the id and shape live in one place:\n\n```ts\nimport { Context, Effect, Layer } from \"effect\"\n\nclass Database extends Context.Service\u003CDatabase, {\n readonly query: (sql: string) => Effect.Effect\u003Cstring>\n}>()(\"Database\") {}\n```\n\nArgument order is **type params first** via `Context.Service\u003CSelf, Shape>()`,\n**then** the id string via `(\"Database\")` — the id comes last, and there is no\n`Context.Tag`.\n\n**Tags are Effects.** A service key is a\nfirst-class Effect — `Context.Key\u003CIdentifier, Shape> extends\nEffect\u003CShape, never, Identifier>` (`Context.ts:68`) — so\n`yield* Database` works, and combinator-style consumer code like\n`Effect.flatMap(Database, (db) => …)` composes directly with no `.asEffect()`\nor unwrap step. Related gotcha when hunting the source: the module is\n`Context.ts`; there is no `ServiceMap.ts`.\n\nThe `Database` form above — `Context.Service\u003CSelf, Shape>()(\"id\")` with **no\n`make` option** — is the **contract-only** service: it declares a shape but\nbakes in no default impl. There is no `.layer` to inherit; wire it with a\nseparate `Layer.succeed(Database, { query: … })` bound to a named `const` (first\nboundary port). Reach for it when the implementation is supplied at the edge (or\ndiffers per environment) rather than owned by the service.\n\n**Shape-inferred `make` form** — implementation and API stay together, TS\nderives the shape. Prefer it when the impl is small; prefer the explicit\ngeneric shape when you want the contract stated before the code:\n\n```ts\nclass UserRepo extends Context.Service\u003CUserRepo>()(\"UserRepo\", {\n make: Effect.gen(function* () {\n  const config = yield* Config;\n  return { getById: (id: string) => Effect.succeed({ id, from: config.url }) };\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(ConfigLayer));\n}\n```\n\nTwo traps:\n\n- `make` stores the constructor effect but does **NOT** auto-generate a\n  layer — there is no `.Default`. Build the layer yourself (above).\n- There is **no `dependencies` option**. A service's needs are wired with\n  `Layer.provide`, not declared on the service.\n\n## Typing a value that implements a service's interface\n\nWhen a **factory returns an implementation** — a second `Layer` satisfying an\nexisting contract, a test double, a per-directory resolver — you need a name for\nthe service's *shape*, not for the service key. Two spellings resolve to the\nsame type, and one of them is the documented helper:\n\n```ts\n\u002F\u002F Preferred: the named helper in the Service namespace.\nfunction makeWorkspaceResolver(\n rootDir: string,\n): Context.Service.Shape\u003Ctypeof RegistryResolver> {\n return { resolve: (name) => Effect.succeed(`${rootDir}\u002F${name}`) };\n}\n\n\u002F\u002F Equivalent: indexed access through the key's witness property.\nfunction makeOther(dir: string): (typeof RegistryResolver)[\"Service\"] { ... }\n```\n\n`Context.Service.Shape\u003CT>` is `T extends Key\u003Cinfer _I, infer S> ? S : never`\n(`Context.ts:420`), and it sits in a namespace whose own doc example is titled\n\"Extracting service types\" — core states this as the way to name a service's\nshape, so **prefer it**. The indexed form works for the same reason it reads\nwell: `Context.Key\u003CIdentifier, Shape>` carries `readonly Service: Shape` as a\nreal property (`Context.ts:70`), so `(typeof Tag)[\"Service\"]` is an ordinary\nlookup rather than a trick. The sibling `Context.Service.Identifier\u003CT>` extracts\nthe `R`-channel identifier the same way.\n\n**The trap this replaces: the class instance type is not the shape.** Reaching\nfor the obvious annotation — the class's own name — does not compile:\n\n```ts\n\u002F\u002F WRONG. RegistryResolver (the instance type) is not { resolve: ... }.\nfunction makeWorkspaceResolver(dir: string): RegistryResolver { ... }\n\u002F\u002F error TS2353: Object literal may only specify known properties,\n\u002F\u002F and 'resolve' does not exist in type 'RegistryResolver'.\n```\n\nA class-form key's instance type is `ServiceClass.Shape\u003CIdentifier, Shape>`\n(`Context.ts:151`), a three-member wrapper — the `ServiceTypeId` brand, `key`,\nand a `Service` member holding the real shape. The interface you want is nested\none level inside it, which is exactly what both spellings above unwrap.\n\n**Taking a consumer's key over your shape?** Pin the shape. A\nparameter typed `Context.Key\u003CI, Shape>` or `Context.Service\u003CI, Shape>`\naccepts a key over a **wider** shape, because class keys compare structurally\nand method bivariance makes that covariant. The fix is\n`Context.Key\u003CI, S> & ([Shape] extends [S] ? unknown : never)` with\n`S extends Shape`; a key that adds members then errors as \"not assignable to\nparameter of type 'never'\". It cannot see through method-syntax parameter\nbivariance (a member redeclared as a method with a wider parameter still\npasses). If the shape is generic (`Shape\u003CA>`), also intersect\n`Context.Key\u003CI, Shape\u003CA>>`, or `A` is no longer inferred from the key. See\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n## Access a service: prefer `yield*`\n\n`yield*` on the class pulls the implementation and leaves the dependency\n**explicit in the effect's `R`**, where the type system tracks it:\n\n```ts\nconst program = Effect.gen(function* () {\n const db = yield* Database;\n return yield* db.query(\"SELECT 1\");\n});\n```\n\n`use` \u002F `useSync` are static accessors — the only ones; there is no generated\nproxy accessor per method. Reach for them sparingly — they hide *which* dependency you\npulled at the call site, making it easy to leak a service dep into a return\nvalue:\n\n```ts\nDatabase.use((db) => db.query(\"SELECT 1\")); \u002F\u002F Effect\u003Cstring, never, Database>\nConfig.useSync((c) => c.url);               \u002F\u002F pure callback ⇒ Effect\u003Cstring, never, Config>\n```\n\n`use` takes an effectful callback and returns `Effect\u003CA, E, R | Self>`;\n`useSync` takes a **pure** callback and returns `Effect\u003CA, never, Self>` (it just\nlets the accessor body be synchronous — both still return an `Effect`). There is\nno mapped-type proxy that mints an accessor per method: such a proxy **erases\ngenerics** — a `get\u003CT>(key): Effect\u003CT>` collapses to `Effect\u003Cunknown>` and\noverloads are lost — which is why `use`\u002F`useSync`, or plain `yield*`, are the\nwhole accessor story and preserve the real method signatures.\n\n**The class IS the Effect — there is no `.asEffect()`.** `class Database\nextends Context.Service\u003C...>()(\"Database\")` is itself an\n`Effect\u003CShape, never, Database>`, so pass the class wherever an Effect goes:\n`Effect.flatMap(Database, (db) => ...)`, `Database.pipe(Effect.map(...))`, or\nas a value typed `Effect.Effect\u003CDatabase[\"Service\"], never, Database>`.\n`.asEffect()` is `Effectable.Class`'s abstract method, not a service's;\ncalling it on a service class is a type error, not a conversion you forgot.\n\nFor a config knob \u002F feature flag with a default (not a full API), use\n`Context.Reference\u003CT>(id, { defaultValue: () => ... })` instead of a\nservice.\n\n## Layers: build, compose, provide once\n\n`Layer\u003CROut, E, RIn>` — `ROut` services produced, `E` construction\nfailures, `RIn` dependencies required to build.\n\n- **`Layer.succeed(Service)(impl)`** — a pure, already-built value; no deps,\n  no scope.\n- **`Layer.effect(Service)(effect)`** — effectful construction that may\n  depend on other services **and\u002For own a scoped resource** (db pool,\n  socket, worker). Its return type is `Layer\u003CI, E, Exclude\u003CR, Scope>>`: it\n  strips `Scope` from `R`. That is exactly why there is **no `Layer.scoped`** —\n  `Layer.effect` over an `Effect.acquireRelease` effect *is* the scoped\n  constructor:\n\n```ts\nconst DatabaseLayer = Layer.effect(Database)(\n Effect.gen(function* () {\n  const config = yield* Config;\n  const pool = yield* Effect.acquireRelease(\n   openPool(config.url),\n   (p) => p.close(),\n  );\n  return { query: (sql) => pool.run(sql) };\n }),\n);\n```\n\n`Layer.succeed` and `Layer.effect` are **dual**: the curried\n`Layer.effect(Service)(effect)` is primary, but the data-first\n`Layer.effect(Service, effect)` overload also works (handy for\n`Layer.effect(this, this.make)`). Both compile.\n\n### In a layer static, refer to the service as `this`\n\nA `layer` static that names its own class is fine **when the service is a class\ndeclaration** — `export class Db extends Context.Service...()` initializes the\nclass's inner binding before static initializers run, so `Layer.succeed(Db, …)`\ninside `Db`'s own body resolves.\n\nIt is a **temporal dead zone** when the service is a class **expression bound to\na `const`**, because then there is no inner binding and the name resolves to the\nouter `const`, which is still uninitialized while the class body evaluates:\n\n```ts\n\u002F\u002F THROWS at import time: \"Cannot access 'BunResolver' before initialization\"\nexport const BunResolver = class extends Context.Service()(\"BunResolver\", {}) {\n static layer = mk(BunResolver, …);   \u002F\u002F ← outer const, still in TDZ\n};\n\n\u002F\u002F Fine — `this` is the class, always:\nexport const BunResolver = class extends Context.Service()(\"BunResolver\", {}) {\n static layer = mk(this, …);\n};\n```\n\nProbed: the class-expression form throws, the `this` form does not,\nand the class-*declaration* form does not either.\n\n**Write `this` unconditionally.** It is correct in both forms, so it costs\nnothing and removes the whole question — and the failure it prevents is a\nfalse green:\n\n> The module throws **at import time** while **typechecking completely clean**.\n> The only signal is vitest reporting **`0 tests passed` with exit 0** for every\n> file that imports it. A suite that collects zero tests is not a passing suite.\n> See `effect-v4-testing`.\n\n**A second trigger, which fires on a class *declaration* too: a static that reads\na module-local `make` declared further down the file.** The rule above covers the\nclass's own name; this one covers anything the static initializer touches\neagerly:\n\n```ts\n\u002F\u002F THROWS at import: \"Cannot access 'make' before initialization\" — and typechecks clean\nexport class Repo extends Context.Service\u003CRepo, Shape>()(\"Repo\") {\n static readonly layer = Layer.effect(this, Effect.map(Dep, make));\n}\nconst make = (dep: Dep): Shape => ({ … });   \u002F\u002F ← evaluated AFTER the class body\n\n\u002F\u002F Fine — the arrow defers the read to layer-BUILD time:\n static readonly layer = Layer.effect(this, Effect.map(Dep, (dep) => make(dep)));\n```\n\n`Effect.map(Dep, make)` reads `make` while the static initializer runs — import\ntime; `(dep) => make(dep)` reads it when the layer is built. Same false green.\nThe arrow is correct in both declaration orders, so write it unconditionally.\n\n### Resolve a dependency once at construction — only when it is stable\n\nA service built with `Effect.gen` resolves whatever it `yield*`s **when the layer\nis built**. Right for a pool, a client, a decoded config; wrong for anything a\ncaller is meant to vary. **Stable ⇒ resolve in `make`** and every call shares the\ninstance. **Varying it is the point ⇒ read it per call**, keeping it in the\nmethod's `R`, so a caller's `Effect.provideService(op, Dep, other)` reaches the\ncode that uses it.\n\nGetting this backwards is **silent**. A `Repo` resolved at construction made\n`Repo.provide(…)` decorative: the wrapper compiled, ran, and changed nothing,\nbecause the service had already captured the ambient instance. Nothing in the\ntypes distinguishes the two — only a test that provides a *different* instance\nand asserts the difference does. (Caught that way in the github work.)\n\nName the primary layer **`layer`** (e.g. `Database.layer`), never `Default` or\n`Live`. Use suffixes for variants (`layerTest`). The one exception\nis the `index.ts` composite convenience export that merges two concept modules'\nprimary layers — `Default` is the idiomatic name there (see **Cycle-avoidance**\nbelow); it is not a service's own primary layer, so it does not violate this\nrule.\n\n### A layer static belongs to the module owning the dependency, not the service\n\n**Statics on one class share one module**, and a module is the unit of\nreachability — so a layer variant needing something the service's own module must\nnot reach moves out:\n\n> A layer-family static belongs to the module that **owns the dependency it\n> needs**, not to the module that **declares the service**.\n\nThree uses in the kit: `GitHubApp.clientLayer` (confines the JWT signer),\n`Workspaces.localExecLayer` (builds `@effected\u002Fcommands`' service, so `commands`\nkeeps zero `@effected\u002F*` edges), `GitHubCacheBlobStore.layer` (confines\n`@azure\u002Fstorage-blob`). Such a static is named for its **variant**, not `layer`.\nTest: *would putting this static on the service class make a dependency reachable\nfrom a consumer that does not use it?*\n\n### Swappable contracts: no ambient default, and ship values too\n\nWhen the implementation is a **policy choice** the consumer must make, two rules:\n\n1. **No ambient default in the composite layer.** `Layer.mergeAll` is\n   **last-wins**, so `Layer.mergeAll(myDetector, Pkg.layer())` — the natural\n   spelling of an override — silently loses to a merged-in default. Leave the\n   requirement in `R`: wiring that forgets to choose does not compile, and\n   consumers who never call the operation never supply a policy.\n2. **Ship every implementation as a VALUE as well as a layer** (`static readonly\n   npm: Shape` beside `static readonly layerNpm = Layer.succeed(this, this.npm)`).\n   A consumer composing *around* the default cannot use a layer without\n   re-entering the tag it is replacing; given the value, the wrapper is one\n   delegating `Layer.succeed`.\n\nReasoning and the `PublishabilityDetector` precedent:\n[references\u002Fservice-design.md](.\u002Freferences\u002Fservice-design.md), which also\ncarries the layer-static and value-only-service rules in full.\n\n### Composition operators\n\n| Operator | Feeds deps? | Keeps dep outputs? | Use for |\n| --- | --- | --- | --- |\n| `Layer.mergeAll(a, b, …)` | **no** | — (side by side) | combine outputs of independent layers |\n| `Layer.provide(target, deps)` | yes | **no** — only `target` | hide construction deps behind a narrow public layer |\n| `Layer.provideMerge(target, deps)` | yes | **yes** — target + deps | assemble larger app layers where downstream still needs the deps |\n\n> **Trap:** `Layer.mergeAll(ConfigLayer, DatabaseLayer)` does **not** satisfy\n> `DatabaseLayer`'s need for `Config` — merge only places them side by side.\n> Use `provide` \u002F `provideMerge` to actually feed a dependency.\n\n**Compose subsystems locally, assemble one app layer, `Effect.provide`\nonce at the boundary.** Keep subsystem wiring named and local; the app\nlayer should read as a high-level map:\n\n```ts\nconst DbSubsystem = Layer.provide(DatabaseLayer, ConfigLayer);\nconst AppLayer = Layer.mergeAll(DbSubsystem, HttpLayer).pipe(Layer.provide(Telemetry));\n\nEffect.runPromise(program.pipe(Effect.provide(AppLayer))); \u002F\u002F provide at the OUTERMOST edge\n```\n\n> **Cycle-avoidance (first boundary port):** put a composite layer that merges\n> two concept modules — e.g. `Default = Layer.mergeAll(A.noop, B.noop)` — in\n> `index.ts`, not in one of the concept modules. If it lived in module `A`, and\n> `B` imports `A`, the merge would pull `A → B → A` into a cycle\n> (`noImportCycles` is an error here). The entrypoint already depends on both\n> concept modules, so hanging the composite there keeps the concept modules\n> import-cycle-free.\n\nBusiness logic *requires* services (they stay in `R`); composition happens\nin layers; `Effect.provide` happens at the app \u002F test entry point.\n`Effect.provide` deep inside business logic is an anti-pattern — it hides\nwiring, blocks test substitution, and spawns many small runtimes. For\nseveral entry points (HTTP handlers, consumers, cron), build one\n`ManagedRuntime.make(AppLayer)` and run each entry against it.\n\n**Heterogeneous requirement unions need an up-front annotation.** Collecting\nseveral values generic in a requirements union (an array of resolvers, a list of\nlayers feeding one generic parameter) pins the type parameter from the **first**\nelement; the later, wider elements are rejected rather than widening the union.\nAnnotate the collection where it is built —\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n> **Type helpers are top-level.** `Layer.Success\u003Ctypeof L>` and\n> `Layer.Error\u003Ctypeof L>` are module-level type exports (v4 source\n> `Layer.ts:189` \u002F `:173` — resolve the tree via `effect-v4-source-lookup`).\n> There is no nested `Layer.Layer.Success` spelling to reach for.\n\n## Platform capabilities: require in R, never own a backend\n\nEffect v4's consolidated core **declares** the platform service contracts —\n`FileSystem`, `Path`, `Terminal`, `Stdio` as top-level `effect\u002F*` modules, and\n`ChildProcessSpawner` (subprocesses) under `effect\u002Fprocess` — while the\n**implementations** live in `@effect\u002Fplatform-*` (Node's `NodeServices.layer`\nprovides `ChildProcessSpawner | FileSystem | Path | Stdio | Terminal`\nin one layer; crypto is not in it — the `effect\u002Fcrypto` services such as\n`Digest` come from `NodeCrypto.layer` or a family layer like\n`NodeCrypto.layerDigest`, or core's `Digest.layerWebCrypto`; a consumer's own doc\ncomment saying `NodeServices.layer` provides crypto is stale, so fix it). All of these contracts are tagged `@stability unstable` — a\nminor `effect` release may change their shape — which does not change the\nrule below; it means a library re-verifies its usage when the installed\n`effect` moves. That split fixes the house default:\n\n- **A library that needs a platform capability requires the core-declared\n  service in its `R` channel** and the application provides the platform layer\n  once at the edge. Requiring-in-R is free — it adds no dependency edge and no\n  tier cost. This is how `walker`, `xdg` and `config-file` consume\n  `FileSystem`, and how anything subprocess-shaped consumes\n  `ChildProcessSpawner`.\n- **Taking `@effect\u002Fplatform-*` as a dependency edge is categorically\n  different** — it drags the platform package into every consumer's tree\n  (integrated tier). Do not conflate the two: \"platform-node is tier 3\" is a\n  statement about dependency edges, never about `R`.\n- Platform packages are legitimate **devDependencies for integration tests**,\n  and legitimate **dependencies only in applications and app-edge packages**\n  (a CLI binary, a server entrypoint).\n- **A direct `node:` import in library code is a code smell**, most of the\n  time. The sanctioned exceptions are documented Node-only overlays — a\n  default layer or a sync escape hatch — never a contract or a\n  business-logic path.\n\nBefore designing any service or seam, grep the core source — the\n`@stability unstable` namespace modules included, since they import exactly\nlike any other core module rather than living under a separate path — for an\nexisting contract (`effect-v4-source-lookup` resolves the tree). A parallel subprocess vocabulary (`Command`\u002F`CommandRunner` plus a\nhand-rolled `node:child_process` layer) survived four review gates in this repo\nbefore a source check found `effect\u002Fprocess` already declared all of it.\n\n## Sync facades: per-call service values, not layers\n\nA synchronous escape hatch over consumer-supplied ops (build-tool plugin hooks,\nconfig-time contexts) takes service **values** provided per call with\n`Effect.provideService` — never a Layer, so consecutive calls carrying different\nops cannot hit the memoize-by-reference trap below. The `FileSystem.makeNoop` \u002F\nhand-rolled-`Path` recipe and the honest `runSyncExit` unwrap:\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\n## Memoization: layers build once, by reference\n\nWithin one provided layer graph, the same layer *value* is built exactly\nonce, however many composites reference it. Across `Effect.provide` calls\nthe rule depends on nesting: a provide's build adds its `MemoMap` to the\ncontext (`Layer.ts:678`), and a provide running **inside** it forks that\nmap (`CurrentMemoMap.forkOrCreate`, `Layer.ts:601`), so a nested provide\nreuses what the enclosing one built:\n\n```ts\nconst main = program.pipe(Effect.provide(DbSubsystem), Effect.provide(DbSubsystem));\n\u002F\u002F Built ONCE — the inner provide forks the outer provide's MemoMap.\n```\n\nProvides that are **not** nested — one after another, or siblings under a\ncommon parent — each start their own map and build again (probed: nested\n1 build, sequential 2, siblings under one outer provide 2). A warm-up\n`Effect.scoped(Layer.build(L))` followed by `program.pipe(Effect.provide(L))`\nis two sequential builds.\n\nIdentity is **by reference**, and that is the footgun. A function that\n*returns* a layer mints a **fresh reference every call**, defeating\nmemoization and building the underlying resource (pool, HTTP client,\ntelemetry) more than once:\n\n```ts\n\u002F\u002F BAD — two distinct references, resource built twice:\nconst AppLayer = Layer.mergeAll(makeDatabaseLayer(), makeDatabaseLayer());\n\n\u002F\u002F GOOD — call once, bind to a const, reuse the reference:\nconst DatabaseLayer = makeDatabaseLayer();\nconst AppLayer = Layer.mergeAll(DatabaseLayer, OtherLayer);\n```\n\nProbed, counting resource opens: an inline factory call at two\nprovide sites opened the resource **twice**; the same factory called once and\nbound to a `const` opened it **once**. The two-provide dedup is real, but it can\nonly dedup a reference it can recognize.\n\n**A parameterized layer static is exactly this shape.** `static readonly layer =\n(opts) => Layer.effect(...)` is a factory, and every `Svc.layer(opts)` at a\nprovide site is a fresh reference — the \"it's a static, so it must be a\nsingleton\" intuition is false.\n\nLearn the **symptoms**, because the type system reports nothing and the tests\nmostly pass:\n\n- two database connections opened against one file;\n- two ledgers \u002F caches \u002F counters, each holding half the writes;\n- **a `PubSub` where each subscriber sees only half the events** — the publisher\n  and the subscriber resolved *different* instances.\n\nAnything that looks like \"state mysteriously split in two\" is this bug until\nproven otherwise.\n\n**A cousin with a different fingerprint: two resolved copies of one package\nare two DISTINCT tag identities.** When a dependency graph resolves two\ncopies of one `@effected` package (a caret range and a newer 0.x minor\nresolving separately), a layer built from one copy does not satisfy a\nrequirement expressed by the other — and it surfaces as **\"service not\nprovided\" in a graph that visibly provides it**, never as a version error,\nsending the reader hunting a signature change that never happened (observed\n2026-08-14). Two checks answer different halves of it: `pnpm why\n@effected\u002F\u003Cpkg>` says what *resolves*, and grepping a bundle for the\n**fully-qualified tag id** (`@effected\u002F\u003Cpkg>\u002F\u003CService>`, one hit per copy —\nnever the bare class name, which also matches methods, logs and re-exports)\nsays what got *inlined*. Mechanism, diagnosis and mitigation →\n[references\u002Fedge-cases.md](.\u002Freferences\u002Fedge-cases.md).\n\nDiscipline — **bind layers to named constants**:\n\n- Prefer plain named layer `const`s over layer-returning factories.\n- Write a layer-returning function only when the layer genuinely depends on\n  runtime params — and even then, call it **once** and reuse the result.\n- If a subsystem depends on a parameterized layer, **leave that dependency\n  unprovided** and supply the concrete layer once **at the edge**. Don't\n  call the factory locally inside subsystem wiring — it breaks sharing and\n  hides the dep.\n\nAuto-memoization is a safety net for the multi-provide footgun, not a\nlicense to skip composition. Compose explicitly, provide once.\n\n**Opt out** when you deliberately want a fresh build (test isolation,\nindependent resource pools):\n\n- `Layer.fresh(layer)` — always builds with a fresh memo map, bypassing the\n  shared cache. It isolates only where it wraps: composed layers\n  (`Layer.provide`, `provideMerge`, `mergeAll`) are memoized by identity too,\n  so a composed `const` referenced twice is built once, and a `Layer.fresh`\n  dependency **inside** it is shared with it (probed: 1 build, where\n  `Layer.mergeAll(composed, Layer.fresh(composed))` builds 2). Wrap the\n  composed layer, not its dependency, when each site needs its own copy.\n- `Effect.provide(layer, { local: true })` — builds the layer and its\n  sublayers from a **local** memo map, isolated from other provides.\n\n## Test layers\n\nSwap the layer, not the code: business logic requires `Database`; production\nprovides `Database.layer`, tests provide a fake at the same boundary.\n\n- `Layer.succeed(Service)({ ... })` — a full hand-written fake.\n- `Layer.mock(Service, { ... })` — a **partial** mock; supply only the\n  members the test exercises. Any omitted effect-returning member fails with\n  an unimplemented defect if called, so the mock fails loudly instead of\n  silently returning `undefined`:\n\n```ts\nconst DatabaseTest = Layer.mock(Database, {\n query: (sql) => Effect.succeed(`mocked ${sql}`),\n});\n\nEffect.runPromise(program.pipe(Effect.provide(DatabaseTest)));\n```\n\nKeep test wiring explicit and close to the production composition style —\nthe Live\u002FTest difference should be one swapped layer at the edge, nothing\ndeeper.\n\n### `Layer.mock`'s optionality is earned, not given — and one plain member revokes it\n\n`Layer.mock(Service, impl)` takes `PartialEffectful\u003CS>`, not `Partial\u003CS>`\n(`Layer.ts:2354`). That type is not \"everything optional\" — it splits the shape\non one predicate:\n\n```ts\n\u002F\u002F Layer.ts:2279 — a member is OPTIONAL iff it matches AnyEffectOrStream; else REQUIRED\nexport type PartialEffectful\u003CA extends object> = Types.Simplify\u003C\n  & { [K in keyof A as A[K] extends AnyEffectOrStream ? K : never]?: A[K] }\n  & { [K in keyof A as A[K] extends AnyEffectOrStream ? never : K]: A[K] }\n>\n\u002F\u002F Layer.ts:2288 — AnyEffectOrStream = Effect | Stream | Channel, or a function returning one\n```\n\nSo **any non-effectful member is required in every single mock**: a sync\nfunction, a plain data property, a generic passthrough whose return type does\nnot resolve to `Effect`\u002F`Stream`\u002F`Channel`. Add one and every existing\n`Layer.mock` call site must now spell out that member — the partial mock has\nsilently degraded to `Layer.succeed` with extra ceremony. The type system\nreports it as \"missing property\" errors scattered across the test suite, far\nfrom the service shape that caused them.\n\n**House rule: no non-effectful members on a service shape.** A service is an IO\ncontract. A pure helper belongs on a static, a namespace, or a plain exported\nfunction next to the pure class that owns the algorithm — never inside the\n`Context.Service` shape. That keeps every member effect-valued, which keeps\nevery member optional, which keeps `Layer.mock` doing the one job it exists for.\n\n> **The wrong fix: wrapping the pure helper in `Effect.succeed` to satisfy the\n> rule.** It does buy back optionality — and it is the anti-pattern, not the\n> remedy. It makes every caller pay a `yield*` for a computation that cannot\n> fail, cannot suspend and needs no runtime; it hides a pure function inside an\n> IO contract where nobody will find it; and it makes the thing untestable\n> without a layer, which is exactly the cost the pure-core\u002Feffectful-edge split\n> (see `effect-v4-planning`, pillar 1) exists to avoid. **Move the member off\n> the shape. Do not decorate it into compliance.**\n\n**The one bounded exception: a shape that is entirely ONE immutable value.** The\nrule targets **mixed** shapes, where a pure member revokes the *methods'*\noptionality. A service whose whole contract is data — a resolved environment\nrecord, a set of discovered paths — has no behaviour to mock, so nothing\ndegrades: `Layer.succeed` is the correct and complete double, and `Layer.mock`\nwas never the tool. Apply the criterion, do not pattern-match it: *the entire\nshape is one immutable value with no mockable behaviour* — not \"mostly data\",\nnot \"the methods are trivial\". The boundary is sharp: **the moment a method\nappears, it is a service again**, and the rule above reapplies retroactively to\nevery field. Say so in the service's TSDoc when you declare one.\n\n### `dual` belongs on pure classes, never on a service shape\n\n`Function.dual` (the kit imports it as `Fn`) gives a combinator both the\ndata-first and data-last spelling — `Package.addDependency(pkg, name, spec)`\n*and* `pkg.pipe(Package.addDependency(name, spec))`. That is the right shape on\na **pure** class: `@effected\u002Fpackage-json`'s `Package` and `@effected\u002Fsemver`'s\n`Range` \u002F `SemVer` all use it, and they are pure Schema classes with no layer\nanywhere near them.\n\nPutting a dual member on a `Context.Service` shape costs more than it looks:\n\n- A dual member's declared type is an **overload pair**. Any override — in a\n  `Layer.mock` implementation, in a `Partial\u003CShape>` test-stub argument, in a\n  hand-written fake — must satisfy **both** overloads, not just the one the test\n  calls. The one-line stub that works for every other member\n  (`layerTest({ read: () => Effect.succeed(x) })`) stops compiling, and the fix\n  is to hand-write the full overloaded signature in the test.\n- It is also a non-effectful member by the rule above whenever the data-last\n  branch returns a function rather than an `Effect`, so it is `Layer.mock`-\n  required on top of being overload-shaped.\n\nThe two rules compose into one design instruction: **service shapes carry plain,\nsingle-signature, effect-returning methods. Everything cleverer lives on the\npure class.**\n",{"name":5,"description":7},"main","11d6b3ae59538b0e16ad67c315ecb0c25fcb0125","plugin\u002Fbuilds\u002Fclaude\u002Fskills\u002Feffect-v4-services-layers",2,"https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected","https:\u002F\u002Fgithub.com\u002Fspencerbeggs","2026-11-14 07:03:25",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add spencerbeggs\u002Feffected --skill effect-v4-services-layers",{"tool":37,"command":38},"bunx","bunx skills add spencerbeggs\u002Feffected --skill effect-v4-services-layers",{"tool":40,"command":41},"pnpm","pnpm dlx skills add spencerbeggs\u002Feffected --skill effect-v4-services-layers","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fbuilds\u002Fclaude\u002Fskills\u002Feffect-v4-services-layers\u002FSKILL.md",true,[45,51],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002Fedge-cases.md","REFERENCE","参考文档",12879,"https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fbuilds\u002Fclaude\u002Fskills\u002Feffect-v4-services-layers\u002Freferences\u002Fedge-cases.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"references\u002Fservice-design.md",6630,"https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fbuilds\u002Fclaude\u002Fskills\u002Feffect-v4-services-layers\u002Freferences\u002Fservice-design.md",[56,63,70,77,84,91],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M780NVTD800KMFV869YNZED6","testing-actions","Use when writing or reviewing tests for @effected\u002Fgithub-actions, @effected\u002Fgithub, @effected\u002Fsbom or @effected\u002Fcommands — stubbing the GitHub API, writing a service's layerTest or makeTest double, testing the pre\u002Fmain\u002Fpost lifecycle through Action.run, or debugging why a test hits the real network or hangs.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Ftesting-actions\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M780NPDSGFC0FCP7696NW11J","supply-chain-attestation","Use when generating a CycloneDX SBOM, checking NTIA minimum elements, building an in-toto statement or a SLSA provenance predicate, signing into a Sigstore DSSE bundle, or uploading an attestation to GitHub.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Fsupply-chain-attestation\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M780NGP4QNZDH8T8Q8WZ18SA","structuring-an-action","Use when laying out a new GitHub Action repository on the @effected suite, deciding where a piece of code belongs (an entry point, a step, a shared service, a shim), or reviewing an existing action's file structure against the canonical shape.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Fstructuring-an-action\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M780NCD52H1Y03FS83WJ8BT5","running-commands-and-tools","Use when running a subprocess in Effect v4, spawning a command, capturing stdout\u002Fstderr\u002Fexit code, checking whether a CLI tool is installed or which copy to run, running a package-manager script through the project's launcher, detaching a background process, or redacting a secret from argv or captured output.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Frunning-commands-and-tools\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M780N823DWNRMSY5X2NT5MSR","release-and-publish","Use when publishing a package to npm, reading the npm registry from Effect v4, checking whether a version is already published, cutting a release tag or GitHub release from an action, applying a release-age gate, or deriving tracking tags for GitHub Actions distribution.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Frelease-and-publish\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M780MXRF6H20KCESTSSFB3HQ","hardening-a-parser-port","Use when porting or writing a recursive-descent parser, lexer, or tree-walker over untrusted text in the @effected monorepo — the class of hardening the cloud reviewer scans for on every migration. Covers stack-overflow depth guards (on EVERY recursion surface, which a facade has N of — not two), numeric bound guards that must reject NaN and non-integers, code-point range checks scoped to formats with wide escapes, prototype-pollution, control-character rejection, and the invariant that malformed input must fail through the typed error channel, never as an unhandled defect.","https:\u002F\u002Fgithub.com\u002Fspencerbeggs\u002Feffected\u002Fblob\u002Fmain\u002Fplugin\u002Fskills\u002Fhardening-a-parser-port\u002FSKILL.md",[],[]]