[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6K24YQVC2CSFDDHSY7NHHF4":3,"skill-same:01M6K24YQVC2CSFDDHSY7NHHF4":98},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M6K24YQVC2CSFDDHSY7NHHF4","zio-reference",null,"Use when writing ZIO Scala code — implementing services with ZLayer, handling typed errors vs defects, choosing concurrency primitives (Ref, Queue, Hub, STM, Semaphore), avoiding anti-patterns like blocking on ZIO threads, unsafe resource handling with ensuring, or overusing Task for business logic","linux-root\u002Fscala-zio-skills","linux-root","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F24811721?v=4","01M6K24S83Z6SMRT80J539Q6ZM","Watson Dinh","01M6K24SD6RMBG16S7WMWMK7R8",20,"MIT","https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"reference","zio reference","zio","patterns","copilot","unsafe","defects","for","implementing","code","threads","errors","semaphore","writing","opencode","anti-patterns","use","business","primitives","concurrency","2026-11-10 10:12:30",false,"---\nname: zio-reference\ndescription: Use when writing ZIO Scala code — implementing services with ZLayer, handling typed errors vs defects, choosing concurrency primitives (Ref, Queue, Hub, STM, Semaphore), avoiding anti-patterns like blocking on ZIO threads, unsafe resource handling with ensuring, or overusing Task for business logic\nlicense: MIT\ncompatibility: opencode,claude-code,copilot\n---\n\n# ZIO Coding Reference\n\nYou are an expert Scala\u002FZIO developer. Follow these rules strictly when generating ZIO code.\n\n## Core Concepts\n\n- **ZIO[R, E, A]**: Immutable effect description. `R` = environment (contravariant), `E` = error (covariant), `A` = success (covariant). Effects are descriptions, not running computations.\n- **Fibers**: Lightweight virtual threads managed by ZIO runtime. Millions can run concurrently. Fork starts one, join awaits it.\n- **ZLayer**: Recipe for constructing services from dependencies with effectful init\u002Ffinalize. Automates dependency graph wiring.\n- **Scope**: Resource lifetime manager. Finalizers run on success, failure, or interruption.\n- **Typed Errors vs Defects**: `E` channel = expected domain failures (compiler-checked). Defects = unexpected bugs captured in `Cause`, not in `E`.\n\n> Deep dive: references\u002Fcore-concepts.md\n\n## Coding Rules\n\n### Error Handling\n> Deep dive: references\u002Ferror-handling-deep-dive.md\n\n- Model domain errors as sealed trait ADTs: `sealed trait UserError; case class NotFound(id: UUID) extends UserError`\n- Use `ZIO.fail(NotFound(id))` not `ZIO.fail(new Exception(\"not found\"))`\n- Use `orDie` to shift `Throwable` to defect channel when unrecoverable: `ZIO.attempt(expr).orDie`\n- Use `refineToOrDie[SpecificError]` to keep one error type, defect the rest\n- Never swallow defects: `effect.tapDefect(c => ZIO.logErrorCause(\"Unexpected\", c))` not `effect.catchAllDefect(_ => ZIO.unit)`\n- Use `mapError` to unify error hierarchies across layers\n- Use `catchAll` for recovery, `foldZIO` for transforming both paths\n- Low-level: broad errors (`IOException`). High-level: refined domain ADTs or defects.\n- Use `Either` only when errors are unrelated and you want to avoid widening `E` to `Any`\n\n### Composition\n- For-comprehensions for sequential composition:\n  ```scala\n  for { user \u003C- getUser(id); _ \u003C- notify(user) } yield ()\n  ```\n- `*>` (zipRight) \u002F `\u003C*` (zipLeft) when discarding one result:\n  ```scala\n  Console.printLine(\"Starting\") *> runTask\n  ```\n\n### Dependencies (Service Pattern)\n- Trait defines interface (methods return `IO[E, A]` with `R = Any`)\n- Case class implements trait, receives dependencies via constructor\n- Companion object provides `ZLayer`\n```scala\ntrait Greeter { def sayHello(name: String): UIO[Unit] }\n\ncase class GreeterLive(console: Console) extends Greeter {\n  def sayHello(name: String): UIO[Unit] = console.printLine(s\"Hello, $name!\").orDie\n}\n\nobject Greeter {\n  val layer: URLayer[Console, Greeter] = ZLayer.derive[GreeterLive]\n}\n```\n\n### Resources\n- Always use `ZIO.acquireRelease` or `ZIO.acquireReleaseWith`, never `ensuring` for resource cleanup\n- Use `ZIO.scoped` for narrowest possible resource lifetime:\n  ```scala\n  ZIO.scoped { ZIO.acquireRelease(open)(r => ZIO.succeed(r.close())).flatMap(use) }\n  ```\n\n### Concurrency\n> Deep dive: references\u002Fconcurrency-and-fiber.md\n\n- Prefer `foreachPar`, `zipPar`, `race` over manual `fork`\u002F`join`\n- Always `join` or `interrupt` any manually forked fiber\n- Use `ZIO.attemptBlocking` or `ZIO.attemptBlockingIO` for blocking I\u002FO, never `ZIO.attempt`\n- Use `ZIO.uninterruptibleMask(restore => setup *> restore(task) *> cleanup)` for custom operators\n- Use `Ref` for single atomic state, `STM`\u002F`TRef` for multi-variable transactional updates\n- Don't wrap monolithic loops in `ZIO.succeed` — runtime can't interrupt inside them\n\n## Anti-Patterns (Never Do These)\n> Deep dive: references\u002Fanti-patterns.md\n\n| Anti-Pattern | Correct |\n|---|---|\n| `Task[A]` for business logic | `IO[DomainError, A]` with sealed trait ADT |\n| `val f = api(); ZIO.fromFuture(_ => f)` | `ZIO.fromFuture(ec => api()(ec))` |\n| `trait Svc { def get: ZIO[Database, E, A] }` | `case class LiveSvc(db: Database) extends Svc { def get: IO[E, A] }` |\n| `acquire.flatMap(r => use(r).ensuring(release(r)))` | `ZIO.acquireReleaseWith(acquire)(release)(use)` |\n| `ZIO.attempt(blockingIOCall())` | `ZIO.attemptBlockingIO(blockingIOCall())` |\n| `effect.catchAllDefect(_ => ZIO.unit)` | `effect.tapDefect(c => ZIO.logErrorCause(\"err\", c))` |\n| `effect.fork *> ZIO.unit` | `effect.fork.flatMap(_.join)` or use structured concurrency |\n| `ZIO.succeed(while(true) { ... })` | Recursive ZIO effect or `.forever` |\n| `object Svc { def method(a: A): ZIO[Svc, E, B] = ZIO.serviceWithZIO(_.method(a)) }` | Call `ZIO.serviceWithZIO[Svc](_.method(a))` directly at call sites |\n\n## Decision Guide: Which Abstraction?\n> Deep dive: references\u002Fwhen-to-use-what.md\n\n| Need | Use | Not |\n|---|---|---|\n| Service wiring + lifecycle | `ZLayer` | Manual instance passing |\n| Single shared mutable state | `Ref` | `var`, `AtomicReference` |\n| Multi-variable atomic updates | `STM` \u002F `TRef` | Multiple `Ref` updates |\n| Work distribution (one consumer per item) | `Queue` | `Hub` |\n| Broadcast (all consumers get every item) | `Hub` | `Queue` |\n| Retry with backoff \u002F repeat on schedule | `Schedule` | Manual recursion |\n| One-shot synchronization between fibers | `Promise` | `Queue`, `Ref` |\n| Limit concurrent access | `Semaphore` | Manual counting |\n| Incremental \u002F infinite data processing | `ZStream` | `ZIO` returning `List` |\n| Resource with finalization | `Scope` + `acquireRelease` | `ensuring` |\n| Low-level fiber control | `Fiber` + `fork` | Default; prefer `foreachPar`\u002F`zipPar` |\n\n## Key Patterns\n> More patterns: references\u002Fminimal-working-patterns.md | references\u002Fidioms.md\n\n### Service Pattern (Repository variant)\n```scala\ntrait UserRepo { def findById(id: UUID): IO[RepoError, Option[User]] }\n\ncase class PostgresUserRepo(ds: DataSource) extends UserRepo {\n  def findById(id: UUID): IO[RepoError, Option[User]] =\n    ZIO.attemptBlocking(query(ds, id)).mapError(DbError(_))\n}\n\nobject UserRepo {\n  val layer: ZLayer[DataSource, Nothing, UserRepo] = ZLayer.derive[PostgresUserRepo]\n}\n```\n\n### Background Worker\n```scala\ndef startWorker(queue: Queue[Job]): ZIO[Any, Nothing, Fiber.Runtime[Nothing, Nothing]] =\n  queue.take.flatMap(job => process(job).ignoreLogged).forever.forkDaemon\n```\n\n### Retry with Backoff\n```scala\nval policy = Schedule.exponential(1.second) && Schedule.recurs(5)\nZIO.attempt(unstableCall()).retry(policy)\n```\n\n### Parallel with Limit\n```scala\nZIO.foreachPar(urls)(fetch).withParallelism(10)\n```\n\n### HTTP Route (ZIO HTTP)\n```scala\nval route: Route[UserRepo, Nothing] =\n  Method.GET \u002F \"users\" \u002F uuid(\"id\") -> handler { (id: UUID, req: Request) =>\n    ZIO.serviceWithZIO[UserRepo](_.findById(id)).map {\n      case Some(user) => Response.json(user.toJson)\n      case None       => Response.notFound\n    }.orDie\n  }\n```\n","# ZIO Coding Reference\n\nYou are an expert Scala\u002FZIO developer. Follow these rules strictly when generating ZIO code.\n\n## Core Concepts\n\n- **ZIO[R, E, A]**: Immutable effect description. `R` = environment (contravariant), `E` = error (covariant), `A` = success (covariant). Effects are descriptions, not running computations.\n- **Fibers**: Lightweight virtual threads managed by ZIO runtime. Millions can run concurrently. Fork starts one, join awaits it.\n- **ZLayer**: Recipe for constructing services from dependencies with effectful init\u002Ffinalize. Automates dependency graph wiring.\n- **Scope**: Resource lifetime manager. Finalizers run on success, failure, or interruption.\n- **Typed Errors vs Defects**: `E` channel = expected domain failures (compiler-checked). Defects = unexpected bugs captured in `Cause`, not in `E`.\n\n> Deep dive: references\u002Fcore-concepts.md\n\n## Coding Rules\n\n### Error Handling\n> Deep dive: references\u002Ferror-handling-deep-dive.md\n\n- Model domain errors as sealed trait ADTs: `sealed trait UserError; case class NotFound(id: UUID) extends UserError`\n- Use `ZIO.fail(NotFound(id))` not `ZIO.fail(new Exception(\"not found\"))`\n- Use `orDie` to shift `Throwable` to defect channel when unrecoverable: `ZIO.attempt(expr).orDie`\n- Use `refineToOrDie[SpecificError]` to keep one error type, defect the rest\n- Never swallow defects: `effect.tapDefect(c => ZIO.logErrorCause(\"Unexpected\", c))` not `effect.catchAllDefect(_ => ZIO.unit)`\n- Use `mapError` to unify error hierarchies across layers\n- Use `catchAll` for recovery, `foldZIO` for transforming both paths\n- Low-level: broad errors (`IOException`). High-level: refined domain ADTs or defects.\n- Use `Either` only when errors are unrelated and you want to avoid widening `E` to `Any`\n\n### Composition\n- For-comprehensions for sequential composition:\n  ```scala\n  for { user \u003C- getUser(id); _ \u003C- notify(user) } yield ()\n  ```\n- `*>` (zipRight) \u002F `\u003C*` (zipLeft) when discarding one result:\n  ```scala\n  Console.printLine(\"Starting\") *> runTask\n  ```\n\n### Dependencies (Service Pattern)\n- Trait defines interface (methods return `IO[E, A]` with `R = Any`)\n- Case class implements trait, receives dependencies via constructor\n- Companion object provides `ZLayer`\n```scala\ntrait Greeter { def sayHello(name: String): UIO[Unit] }\n\ncase class GreeterLive(console: Console) extends Greeter {\n  def sayHello(name: String): UIO[Unit] = console.printLine(s\"Hello, $name!\").orDie\n}\n\nobject Greeter {\n  val layer: URLayer[Console, Greeter] = ZLayer.derive[GreeterLive]\n}\n```\n\n### Resources\n- Always use `ZIO.acquireRelease` or `ZIO.acquireReleaseWith`, never `ensuring` for resource cleanup\n- Use `ZIO.scoped` for narrowest possible resource lifetime:\n  ```scala\n  ZIO.scoped { ZIO.acquireRelease(open)(r => ZIO.succeed(r.close())).flatMap(use) }\n  ```\n\n### Concurrency\n> Deep dive: references\u002Fconcurrency-and-fiber.md\n\n- Prefer `foreachPar`, `zipPar`, `race` over manual `fork`\u002F`join`\n- Always `join` or `interrupt` any manually forked fiber\n- Use `ZIO.attemptBlocking` or `ZIO.attemptBlockingIO` for blocking I\u002FO, never `ZIO.attempt`\n- Use `ZIO.uninterruptibleMask(restore => setup *> restore(task) *> cleanup)` for custom operators\n- Use `Ref` for single atomic state, `STM`\u002F`TRef` for multi-variable transactional updates\n- Don't wrap monolithic loops in `ZIO.succeed` — runtime can't interrupt inside them\n\n## Anti-Patterns (Never Do These)\n> Deep dive: references\u002Fanti-patterns.md\n\n| Anti-Pattern | Correct |\n|---|---|\n| `Task[A]` for business logic | `IO[DomainError, A]` with sealed trait ADT |\n| `val f = api(); ZIO.fromFuture(_ => f)` | `ZIO.fromFuture(ec => api()(ec))` |\n| `trait Svc { def get: ZIO[Database, E, A] }` | `case class LiveSvc(db: Database) extends Svc { def get: IO[E, A] }` |\n| `acquire.flatMap(r => use(r).ensuring(release(r)))` | `ZIO.acquireReleaseWith(acquire)(release)(use)` |\n| `ZIO.attempt(blockingIOCall())` | `ZIO.attemptBlockingIO(blockingIOCall())` |\n| `effect.catchAllDefect(_ => ZIO.unit)` | `effect.tapDefect(c => ZIO.logErrorCause(\"err\", c))` |\n| `effect.fork *> ZIO.unit` | `effect.fork.flatMap(_.join)` or use structured concurrency |\n| `ZIO.succeed(while(true) { ... })` | Recursive ZIO effect or `.forever` |\n| `object Svc { def method(a: A): ZIO[Svc, E, B] = ZIO.serviceWithZIO(_.method(a)) }` | Call `ZIO.serviceWithZIO[Svc](_.method(a))` directly at call sites |\n\n## Decision Guide: Which Abstraction?\n> Deep dive: references\u002Fwhen-to-use-what.md\n\n| Need | Use | Not |\n|---|---|---|\n| Service wiring + lifecycle | `ZLayer` | Manual instance passing |\n| Single shared mutable state | `Ref` | `var`, `AtomicReference` |\n| Multi-variable atomic updates | `STM` \u002F `TRef` | Multiple `Ref` updates |\n| Work distribution (one consumer per item) | `Queue` | `Hub` |\n| Broadcast (all consumers get every item) | `Hub` | `Queue` |\n| Retry with backoff \u002F repeat on schedule | `Schedule` | Manual recursion |\n| One-shot synchronization between fibers | `Promise` | `Queue`, `Ref` |\n| Limit concurrent access | `Semaphore` | Manual counting |\n| Incremental \u002F infinite data processing | `ZStream` | `ZIO` returning `List` |\n| Resource with finalization | `Scope` + `acquireRelease` | `ensuring` |\n| Low-level fiber control | `Fiber` + `fork` | Default; prefer `foreachPar`\u002F`zipPar` |\n\n## Key Patterns\n> More patterns: references\u002Fminimal-working-patterns.md | references\u002Fidioms.md\n\n### Service Pattern (Repository variant)\n```scala\ntrait UserRepo { def findById(id: UUID): IO[RepoError, Option[User]] }\n\ncase class PostgresUserRepo(ds: DataSource) extends UserRepo {\n  def findById(id: UUID): IO[RepoError, Option[User]] =\n    ZIO.attemptBlocking(query(ds, id)).mapError(DbError(_))\n}\n\nobject UserRepo {\n  val layer: ZLayer[DataSource, Nothing, UserRepo] = ZLayer.derive[PostgresUserRepo]\n}\n```\n\n### Background Worker\n```scala\ndef startWorker(queue: Queue[Job]): ZIO[Any, Nothing, Fiber.Runtime[Nothing, Nothing]] =\n  queue.take.flatMap(job => process(job).ignoreLogged).forever.forkDaemon\n```\n\n### Retry with Backoff\n```scala\nval policy = Schedule.exponential(1.second) && Schedule.recurs(5)\nZIO.attempt(unstableCall()).retry(policy)\n```\n\n### Parallel with Limit\n```scala\nZIO.foreachPar(urls)(fetch).withParallelism(10)\n```\n\n### HTTP Route (ZIO HTTP)\n```scala\nval route: Route[UserRepo, Nothing] =\n  Method.GET \u002F \"users\" \u002F uuid(\"id\") -> handler { (id: UUID, req: Request) =>\n    ZIO.serviceWithZIO[UserRepo](_.findById(id)).map {\n      case Some(user) => Response.json(user.toJson)\n      case None       => Response.notFound\n    }.orDie\n  }\n```\n",{"name":5,"license":15,"description":7,"compatibility":44},"opencode,claude-code,copilot","main","89a19690e1007cafa7a71d30a3a825cd49072ca4","skills\u002Fzio-reference",0,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills","https:\u002F\u002Fgithub.com\u002Flinux-root","https:\u002F\u002Fw47s0n.com","Functional Programmer\r\n ___Great things take time . . .","2026-09-20 09:55:26",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add linux-root\u002Fscala-zio-skills --skill zio-reference",{"tool":60,"command":61},"bunx","bunx skills add linux-root\u002Fscala-zio-skills --skill zio-reference",{"tool":63,"command":64},"pnpm","pnpm dlx skills add linux-root\u002Fscala-zio-skills --skill zio-reference","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002FSKILL.md",true,[68,74,78,82,86,90,94],{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Fanti-patterns.md","REFERENCE","参考文档",5320,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fanti-patterns.md",{"path":75,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Fconcurrency-and-fiber.md",4137,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fconcurrency-and-fiber.md",{"path":79,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fcore-concepts.md",2503,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fcore-concepts.md",{"path":83,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Ferror-handling-deep-dive.md",3366,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Ferror-handling-deep-dive.md",{"path":87,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fidioms.md",5175,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fidioms.md",{"path":91,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Fminimal-working-patterns.md",4106,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fminimal-working-patterns.md",{"path":95,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fwhen-to-use-what.md",4489,"https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzio-reference\u002Freferences\u002Fwhen-to-use-what.md",[99],{"skillNo":100,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":39},"01M6K24V3Q23W6BEG1XN3HNF2Z","https:\u002F\u002Fgithub.com\u002Flinux-root\u002Fscala-zio-skills\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fzio-reference\u002FSKILL.md",[],[19,21,20]]