Use when designing, reviewing, generating, or refactoring React applications built with Effector, effector-react, Farfetched, Atomic Router, @effector/next,...
数据分析
effect-ts
试用自动识别项目中的 Effect v3 或 v4 版本,产出符合 API 规范的 TypeScript 代码,覆盖错误建模、并发、依赖注入、Schema、HTTP、SQL 与 AI 等模块。
它能做什么
通过读取 package.json 自动判断已安装的是 Effect v3 还是 v4:新项目默认采用 v4,存量代码则保持原版语法不做改写。内置近 30 条常见 AI 幻觉的对照表,涵盖 Effect.catch 与 catchAll 的版本差异、Context.Service 与 Context.Tag 的区分、Schema.TaggedErrorClass 的正确写法、OtlpTracer.layer 的参数结构、JSON Schema 实际生成的是 Draft-07 而非 2020-12 等,并按任务类型按需加载对应的参考文档。可用于编写、审查、调试 Effect 代码,以及 async/await 转 Effect、v3 升级到 v4 的迁移工作。
什么时候用它
- 按已安装版本生成 Effect v3/v4 代码
- 排查 LLM 生成的不正确 Effect API
- 把 async/await 或 v3 代码迁移到 v4
- 搭建 Service、Layer、Stream、Schema、HTTP、SQL 或 AI 集成
技能文档
Effect-TS
Effect is a TypeScript library for building production-grade software with typed errors, structured concurrency, dependency injection, and built-in observability.
Version Detection
Before writing Effect code, detect which version the user is on:
# Check installed version
cat package.json | grep '"effect"'
- v4.x (recommended, the direction Effect is heading):
Context.Service,Effect.catch,Effect.forkChild,Schema.TaggedErrorClass - v3.x (stable, still common in production):
Context.Tag,Effect.catchAll,Effect.fork,Data.TaggedError
Note: v4 beta briefly used a
ServiceMapmodule, renamed back toContexton 2026-04-07 (PR #1961). If you seeServiceMap.*in any doc or older beta code, it is the currentContext.*. Both v3 and v4 importContextfrom"effect"; the exports inside differ (Context.Servicein v4 vsContext.Tagin v3).
Prefer v4 for new projects - it's where Effect is going. In an existing codebase, match the installed version: don't rewrite v3 code in v4 syntax unless asked. If the version is genuinely unclear, default to v4 and say so. v4 is still in beta, so pin an exact version (4.0.0-beta.x) and expect occasional API churn.
Primary Documentation Sources
v4 (primary):
- https://github.com/Effect-TS/effect-smol (v4 source + migration guides)
- https://github.com/Effect-TS/effect-smol/blob/main/LLMS.md (v4 LLM guide)
v3 (for existing codebases):
- https://effect.website/docs (v3 stable docs)
- https://effect.website/llms.txt (LLM topic index)
- https://effect.website/llms-full.txt (full docs for large context)
Both versions:
- https://tim-smart.github.io/effect-io-ai/ (concise API list)
AI Guardrails: Critical Corrections
LLM outputs frequently contain incorrect Effect APIs. Verify every API against the reference docs before using it.
Common hallucinations (both versions):
| Wrong (AI often generates) | Correct |
|---|---|
Effect.cachedWithTTL(...) | Cache.make({ capacity, timeToLive, lookup }) |
Effect.cachedInvalidateWithTTL(...) | cache.invalidate(key) / cache.invalidateAll() |
Effect.mapError(effect, fn) | Effect.mapError(fn) in pipe, or use Effect.catchTag |
import { Schema } from "@effect/schema" | import { Schema } from "effect" (v3.10+ and all v4) |
import { JSONSchema } from "@effect/schema" | import { JSONSchema } from "effect" (v3.10+) |
| JSON Schema Draft 2020-12 | Effect Schema generates Draft-07 |
| "thread-local storage" | "fiber-local storage" via FiberRef (v3) / Context.Reference (v4) |
| fibers are "cancelled" | fibers are "interrupted" |
| all queues have back-pressure | only bounded queues; sliding/dropping do not |
new MyError("message") | new MyError({ message: "..." }) (Schema errors take objects) |
v3-specific hallucinations:
| Wrong | Correct (v3) |
|---|---|
Effect.Service (function call) | class Foo extends Effect.Service()("id", {}) |
Effect.match(effect, { ... }) | Effect.match(effect, { onSuccess, onFailure }) |
Effect.provide(layer1, layer2) | Effect.provide(Layer.merge(layer1, layer2)) |
v4-specific hallucinations (AI may mix v3/v4):
| Wrong (v3 API used in v4 code) | Correct (v4) |
|---|---|
Context.Tag("X") (v3 shape) | Context.Service(id) or class syntax |
ServiceMap.Service / ServiceMap.Reference | Renamed back to Context.Service / Context.Reference on 2026-04-07 |
Effect.catchAll(fn) | Effect.catch(fn) |
Effect.fork(effect) | Effect.forkChild(effect) |
Effect.forkDaemon(effect) | Effect.forkDetach(effect) |
Data.TaggedError | Schema.TaggedErrorClass |
FiberRef.get(ref) | yield* References.X (a Context.Reference) |
yield* ref (Ref as Effect) | yield* Ref.get(ref) (Ref is no longer an Effect) |
yield* fiber (Fiber as Effect) | yield* Fiber.join(fiber) (Fiber is no longer Effect) |
Logger.Default / Logger.Live | Logger.layer (v4 naming convention) |
Schema.TaggedError | Schema.TaggedErrorClass |
Schema.makeUnsafe(input) | Schema.make(input) (throws SchemaError); also instance methods schema.makeOption(...), schema.makeEffect(...) |
ParseResult (from "effect") | SchemaIssue module + SchemaError class; narrow with Schema.isSchemaError |
HttpApiEndpoint.get(n, p).pipe(HttpApiEndpoint.setPath(...), setPayload(...), setSuccess(...)) | HttpApiEndpoint.get(n, p, { params, query, payload, success, error }) (object-option form) |
Otlp.layer({ url, serviceName }) | OtlpTracer.layer({ url, resource: { serviceName } }) + OtlpSerialization.layerJson + FetchHttpClient.layer |
import { HttpApi } from "@effect/platform" (v4) | import { HttpApi } from "effect/unstable/httpapi" |
| HttpApi endpoint schema errors are typed errors by default | In current v4 betas they default to defects unless transformed |
Read references/llm-corrections.md for the exhaustive corrections table.
Progressive Disclosure
Read only the reference files relevant to your task:
- Error modeling or typed failures →
references/error-modeling.md - Services, DI, or Layer wiring →
references/dependency-injection.md - Per-key dynamic layers (per-tenant resources,
LayerMap) →references/dependency-injection.md - Bridging Effect into non-Effect frameworks (Hono/Express,
ManagedRuntime) →references/dependency-injection.md - Retries, timeouts, or backoff →
references/retry-scheduling.md - Fibers, forking, or parallel work →
references/concurrency.md - Request batching, N+1 elimination, DataLoader pattern →
references/concurrency.md - Multi-provider fallback (
ExecutionPlan) →references/effect-ai.md/references/retry-scheduling.md - Streams, queues, or SSE →
references/streams.md - Framing streams (NDJSON / MessagePack encode-decode) →
references/streams.md - Running child processes / shelling out →
references/concurrency.md - Resource lifecycle or cleanup →
references/resource-management.md - Refreshable values (rotating credentials, polled config) →
references/resource-management.md - Reference-counted shared resources (
RcRef/RcMap) →references/resource-management.md - Schema validation or decoding →
references/schema.md - Branded / nominal types (
Brand) →references/schema.md - Logging, metrics, or tracing →
references/observability.md - HTTP clients or API calls →
references/http.md - HTTP API servers →
references/http.md(covers both client and server) - File uploads / multipart form-data →
references/http.md - LLM/AI integration →
references/effect-ai.md - Configuration, env vars, secrets →
references/configuration.md - SQL / database access →
references/sql.md - Command-line apps →
references/cli.md - Typed client/server RPC →
references/rpc.md - Sharded entities, durable workflows, event sourcing →
references/distributed.md - Transactional state (STM,
Tx*) →references/stm.md - Date/time handling →
references/datetime.md - Immutable nested updates (optics) →
references/optics.md - Graphs, dependency ordering, shortest paths, cycle detection →
references/graph.md - Pattern matching (
Match) →references/core-patterns.md - Pooling resources (
Pool) →references/resource-management.md - Fiber sets, SubscriptionRef, worker threads →
references/concurrency.md - Testing Effect code →
references/testing.md - Property-based testing / generating data from schemas →
references/testing.md - Migrating from async/await →
references/migration-async.md - Migrating from v3 to v4 →
references/migration-v4.md - Core types, gen, pipe, running →
references/core-patterns.md - Full wrong-vs-correct API table →
references/llm-corrections.md
Core Workflow
- Detect version from
package.jsonbefore writing any code - Clarify boundaries: identify where IO happens, keep core logic as
Effectvalues - Choose style: use
Effect.genfor sequential logic, pipelines for simple transforms. In v4, preferEffect.fn("name")for named functions - Model errors explicitly: type expected errors in the
Echannel; treat bugs as defects - Model dependencies with services and layers; keep interfaces free of construction logic
- Manage resources with
Scopewhen opening/closing things (files, connections, etc.) - Provide layers and run effects only at program edges (
NodeRuntime.runMainorManagedRuntime) - Verify APIs exist before using them - consult https://tim-smart.github.io/effect-io-ai/ or source docs
Starter Function Set
Start with these ~20 functions (the official recommended set):
Creating effects: Effect.succeed, Effect.fail, Effect.sync, Effect.tryPromise
Composition: Effect.gen (+ Effect.fn in v4), Effect.andThen, Effect.map, Effect.tap, Effect.all
Running: Effect.runPromise, NodeRuntime.runMain (preferred for entry points)
Error handling: Effect.catchTag, Effect.catch (v4) / Effect.catchAll (v3), Effect.orDie
Resources: Effect.acquireRelease, Effect.acquireUseRelease, Effect.scoped
Dependencies: Effect.provide, Effect.provideService
Key modules: Effect, Schema, Layer, Option, Result (v4) / Either (v3), Array, Match
DI (v4): Context.Service, Context.Reference, Layer.effect, Effect.fn("name")
DI (v3): Context.Tag, Context.Reference
Import Patterns
Always use barrel imports from "effect":
import { Context, Effect, Schema, Layer, Option, Stream } from "effect"
For companion packages, import from the package name. v3 and v4 differ here:
// v4 (recommended) - platform transports still separate, but HttpApi / observability
// moved under effect/unstable/*
import { NodeRuntime } from "@effect/platform-node"
import { FetchHttpClient } from "effect/unstable/http"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiBuilder, HttpApiScalar } from "effect/unstable/httpapi"
import { OtlpLogger, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"
// v3 (stable) companion packages
import { NodeRuntime } from "@effect/platform-node"
import { HttpClient } from "@effect/platform"
import { NodeSdk } from "@effect/opentelemetry"
Avoid deep module imports (effect/Effect) unless your bundler requires it for tree-shaking.
Output Standards
- Show imports in every code example
- Prefer
Effect.gen(imperative) for multi-step logic; pipelines for transforms - In v4, use
Effect.fn("name")instead of bareEffect.genfor named functions; useEffect.fnUntracedfor internal helpers that don't need a span/stack-frame - Never call
Effect.runPromise/Effect.runSyncinside library code - only at program edges - Use
NodeRuntime.runMainfor CLI/server entry points (handles SIGINT gracefully) - Use
ManagedRuntimewhen integrating Effect into non-Effect frameworks (Hono, Express, etc.) - Always
return yield*when raising an error in a generator (ensures TS understands control flow) - Avoid point-free/tacit usage: write
Effect.map((x) => fn(x))notEffect.map(fn)(generics get erased) - Keep dependency graphs explicit (services, layers, tags)
- State the
Effectshape when it helps design decisions
Agent Quality Checklist
Before outputting Effect code, verify:
- Every API exists (check against tim-smart API list or source docs)
- Imports are from
"effect"(not@effect/schema,@effect/io, etc.) - Version matches the user's codebase (v3 vs v4 syntax)
- Expected errors are typed in
E; unexpected failures are defects -
run*is called only at program edges, not inside library code - Resources opened with
acquireReleaseare wrapped inEffect.scoped - Layers are provided before running (no missing
Rrequirements) - Generator bodies use
yield*(notyieldwithout*) - Error raises in generators use
return yield*pattern
相关技能
Use when designing, reviewing, generating, or refactoring Feature-Sliced Design project structure for Effector ecosystem applications: layers, slices, segmen...
用 Vite 8、React 19、Hono 4、Tailwind v4、Biome 和 Vitest 这套技术栈搭建并开发类型安全的 TypeScript 应用。
解读 TypeScript 类型错误,设计 API、tsconfig 与 .d.ts 的类型方案。
Translate a TypeScript compiler error into plain English, find the smallest type boundary at fault, and prefer the smallest safe fix over suppression.
TanStack Query、Router、Start 在 React 全栈项目中的类型安全参考模式。