GeezerVison is showing github.com — refactor(effect): unify service namespaces and align naming (#18093) · gregoryg/opencode@a800583
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/opencode/AGENTS.md +30-46Lines changed: 30 additions & 46 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| 9 | 9 | - **Output**: creates `migration/<timestamp>_<slug>/migration.sql` and `snapshot.json`. | 10 | 10 | - **Tests**: migration tests should read the per-folder layout (no `_journal.json`). | 11 | 11 |
| 12 | | -# opencode Effect guide | | 12 | +# opencode Effect rules | 13 | 13 |
| 14 | | -Instructions to follow when writing Effect. | | 14 | +Use these rules when writing or migrating Effect code. | 15 | 15 |
| 16 | | -## Schemas | | 16 | +See `specs/effect-migration.md` for the compact pattern reference and examples. | 17 | 17 |
| 18 | | -- Use `Schema.Class` for data types with multiple fields. | 19 | | -- Use branded schemas (`Schema.brand`) for single-value types. | 20 | | - | 21 | | -## Services | 22 | | - | 23 | | -- Services use `ServiceMap.Service<ServiceName, ServiceName.Service>()("@console/<Name>")`. | 24 | | -- In `Layer.effect`, always return service implementations with `ServiceName.of({ ... })`, never a plain object. | 25 | | - | 26 | | -## Errors | 27 | | - | 28 | | -- Use `Schema.TaggedErrorClass` for typed errors. | 29 | | -- For defect-like causes, use `Schema.Defect` instead of `unknown`. | 30 | | -- In `Effect.gen`, prefer `yield* new MyError(...)` over `yield* Effect.fail(new MyError(...))` for direct early-failure branches. | 31 | | - | 32 | | -## Effects | | 18 | +## Core | 33 | 19 |
| 34 | 20 | - Use `Effect.gen(function* () { ... })` for composition. | 35 | | -- Use `Effect.fn("ServiceName.method")` for named/traced effects and `Effect.fnUntraced` for internal helpers. | 36 | | -- `Effect.fn` / `Effect.fnUntraced` accept pipeable operators as extra arguments, so avoid unnecessary `flow` or outer `.pipe()` wrappers. | 37 | | -- **`Effect.callback`** (not `Effect.async`) for callback-based APIs. The classic `Effect.async` was renamed to `Effect.callback` in effect-smol/v4. | 38 | | - | 39 | | -## Time | 40 | | - | | 21 | +- Use `Effect.fn("Domain.method")` for named/traced effects and `Effect.fnUntraced` for internal helpers. | | 22 | +- `Effect.fn` / `Effect.fnUntraced` accept pipeable operators as extra arguments, so avoid unnecessary outer `.pipe()` wrappers. | | 23 | +- Use `Effect.callback` for callback-based APIs. | 41 | 24 | - Prefer `DateTime.nowAsDate` over `new Date(yield* Clock.currentTimeMillis)` when you need a `Date`. | 42 | 25 |
| 43 | | -## Errors | | 26 | +## Schemas and errors | | 27 | + | | 28 | +- Use `Schema.Class` for multi-field data. | | 29 | +- Use branded schemas (`Schema.brand`) for single-value types. | | 30 | +- Use `Schema.TaggedErrorClass` for typed errors. | | 31 | +- Use `Schema.Defect` instead of `unknown` for defect-like causes. | | 32 | +- In `Effect.gen` / `Effect.fn`, prefer `yield* new MyError(...)` over `yield* Effect.fail(new MyError(...))` for direct early-failure branches. | 44 | 33 |
| 45 | | -- In `Effect.gen/fn`, prefer `yield* new MyError(...)` over `yield* Effect.fail(new MyError(...))` for direct early-failure branches. | | 34 | +## Runtime vs Instances | 46 | 35 |
| 47 | | -## Instance-scoped Effect services | | 36 | +- Use the shared runtime for process-wide services with one lifecycle for the whole app. | | 37 | +- Use `src/effect/instances.ts` for per-directory or per-project services that need `InstanceContext`, per-instance state, or per-instance cleanup. | | 38 | +- If two open directories should not share one copy of the service, it belongs in `Instances`. | | 39 | +- Instance-scoped services should read context from `InstanceContext`, not `Instance.*` globals. | 48 | 40 |
| 49 | | -Services that need per-directory lifecycle (created/destroyed per instance) go through the `Instances` LayerMap: | | 41 | +## Preferred Effect services | 50 | 42 |
| 51 | | -1. Define a `ServiceMap.Service` with a `static readonly layer` (see `FileWatcherService`, `QuestionService`, `PermissionService`, `ProviderAuthService`). | 52 | | -2. Add it to `InstanceServices` union and `Layer.mergeAll(...)` in `src/effect/instances.ts`. | 53 | | -3. Use `InstanceContext` inside the layer to read `directory` and `project` instead of `Instance.*` globals. | 54 | | -4. Call from legacy code via `runPromiseInstance(MyService.use((s) => s.method()))`. | | 43 | +- In effectified services, prefer yielding existing Effect services over dropping down to ad hoc platform APIs. | | 44 | +- Prefer `FileSystem.FileSystem` instead of raw `fs/promises` for effectful file I/O. | | 45 | +- Prefer `ChildProcessSpawner.ChildProcessSpawner` with `ChildProcess.make(...)` instead of custom process wrappers. | | 46 | +- Prefer `HttpClient.HttpClient` instead of raw `fetch`. | | 47 | +- Prefer `Path.Path`, `Config`, `Clock`, and `DateTime` when those concerns are already inside Effect code. | | 48 | +- For background loops or scheduled tasks, use `Effect.repeat` or `Effect.schedule` with `Effect.forkScoped` in the layer definition. | 55 | 49 |
| 56 | | -### Instance.bind — ALS context for native callbacks | | 50 | +## Instance.bind — ALS for native callbacks | 57 | 51 |
| 58 | | -`Instance.bind(fn)` captures the current Instance AsyncLocalStorage context and returns a wrapper that restores it synchronously when called. | | 52 | +`Instance.bind(fn)` captures the current Instance AsyncLocalStorage context and restores it synchronously when called. | 59 | 53 |
| 60 | | -**Use it** when passing callbacks to native C/C++ addons (`@parcel/watcher`, `node-pty`, native `fs.watch`, etc.) that need to call `Bus.publish`, `Instance.state()`, or anything that reads `Instance.directory`. | | 54 | +Use it for native addon callbacks (`@parcel/watcher`, `node-pty`, native `fs.watch`, etc.) that need to call `Bus.publish`, `Instance.state()`, or anything that reads `Instance.directory`. | 61 | 55 |
| 62 | | -**Don't need it** for `setTimeout`, `Promise.then`, `EventEmitter.on`, or Effect fibers — Node.js ALS propagates through those automatically. | | 56 | +You do not need it for `setTimeout`, `Promise.then`, `EventEmitter.on`, or Effect fibers. | 63 | 57 |
| 64 | 58 | ```typescript | 65 | | -// Native addon callback — needs Instance.bind | 66 | 59 | const cb = Instance.bind((err, evts) => { | 67 | 60 | Bus.publish(MyEvent, { ... }) | 68 | 61 | }) | 69 | 62 | nativeAddon.subscribe(dir, cb) | 70 | 63 | ``` | 71 | | - | 72 | | -## Flag → Effect.Config migration | 73 | | - | 74 | | -Flags in `src/flag/flag.ts` are being migrated from static `truthy(...)` reads to `Config.boolean(...).pipe(Config.withDefault(false))` as their consumers get effectified. | 75 | | - | 76 | | -- Effectful flags return `Config<boolean>` and are read with `yield*` inside `Effect.gen`. | 77 | | -- The default `ConfigProvider` reads from `process.env`, so env vars keep working. | 78 | | -- Tests can override via `ConfigProvider.layer(ConfigProvider.fromUnknown({ ... }))`. | 79 | | -- Keep all flags in `flag.ts` as the single registry — just change the implementation from `truthy()` to `Config.boolean()` when the consumer moves to Effect. |
Collapse file Copy file name to clipboard +144Lines changed: 144 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +# Effect patterns | | 2 | + | | 3 | +Practical reference for new and migrated Effect code in `packages/opencode`. | | 4 | + | | 5 | +## Choose scope | | 6 | + | | 7 | +Use the shared runtime for process-wide services with one lifecycle for the whole app. | | 8 | + | | 9 | +Use `src/effect/instances.ts` for services that are created per directory or need `InstanceContext`, per-project state, or per-instance cleanup. | | 10 | + | | 11 | +- Shared runtime: config readers, stateless helpers, global clients | | 12 | +- Instance-scoped: watchers, per-project caches, session state, project-bound background work | | 13 | + | | 14 | +Rule of thumb: if two open directories should not share one copy of the service, it belongs in `Instances`. | | 15 | + | | 16 | +## Service shape | | 17 | + | | 18 | +For a fully migrated module, use the public namespace directly: | | 19 | + | | 20 | +```ts | | 21 | +export namespace Foo { | | 22 | + export interface Interface { | | 23 | + readonly get: (id: FooID) => Effect.Effect<FooInfo, FooError> | | 24 | + } | | 25 | + | | 26 | + export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Foo") {} | | 27 | + | | 28 | + export const layer = Layer.effect( | | 29 | + Service, | | 30 | + Effect.gen(function* () { | | 31 | + return Service.of({ | | 32 | + get: Effect.fn("Foo.get")(function* (id) { | | 33 | + return yield* ... | | 34 | + }), | | 35 | + }) | | 36 | + }), | | 37 | + ) | | 38 | + | | 39 | + export const defaultLayer = layer.pipe(Layer.provide(FooRepo.defaultLayer)) | | 40 | +} | | 41 | +``` | | 42 | + | | 43 | +Rules: | | 44 | + | | 45 | +- Keep `Interface`, `Service`, `layer`, and `defaultLayer` on the owning namespace | | 46 | +- Export `defaultLayer` only when wiring dependencies is useful | | 47 | +- Use the direct namespace form once the module is fully migrated | | 48 | + | | 49 | +## Temporary mixed-mode pattern | | 50 | + | | 51 | +Prefer a single namespace whenever possible. | | 52 | + | | 53 | +Use a `*Effect` namespace only when there is a real mixed-mode split, usually because a legacy boundary facade still exists or because merging everything immediately would create awkward cycles. | | 54 | + | | 55 | +```ts | | 56 | +export namespace FooEffect { | | 57 | + export interface Interface { | | 58 | + readonly get: (id: FooID) => Effect.Effect<Foo, FooError> | | 59 | + } | | 60 | + | | 61 | + export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Foo") {} | | 62 | + | | 63 | + export const layer = Layer.effect(...) | | 64 | +} | | 65 | +``` | | 66 | + | | 67 | +Then keep the old boundary thin: | | 68 | + | | 69 | +```ts | | 70 | +export namespace Foo { | | 71 | + export function get(id: FooID) { | | 72 | + return runtime.runPromise(FooEffect.Service.use((svc) => svc.get(id))) | | 73 | + } | | 74 | +} | | 75 | +``` | | 76 | + | | 77 | +Remove the `Effect` suffix when the boundary split is gone. | | 78 | + | | 79 | +## Scheduled Tasks | | 80 | + | | 81 | +For loops or periodic work, use `Effect.repeat` or `Effect.schedule` with `Effect.forkScoped` in the layer definition. | | 82 | + | | 83 | +## Preferred Effect services | | 84 | + | | 85 | +In effectified services, prefer yielding existing Effect services over dropping down to ad hoc platform APIs. | | 86 | + | | 87 | +Prefer these first: | | 88 | + | | 89 | +- `FileSystem.FileSystem` instead of raw `fs/promises` for effectful file I/O | | 90 | +- `ChildProcessSpawner.ChildProcessSpawner` with `ChildProcess.make(...)` instead of custom process wrappers | | 91 | +- `HttpClient.HttpClient` instead of raw `fetch` | | 92 | +- `Path.Path` instead of mixing path helpers into service code when you already need a path service | | 93 | +- `Config` for effect-native configuration reads | | 94 | +- `Clock` / `DateTime` for time reads inside effects | | 95 | + | | 96 | +## Child processes | | 97 | + | | 98 | +For child process work in services, yield `ChildProcessSpawner.ChildProcessSpawner` in the layer and use `ChildProcess.make(...)`. | | 99 | + | | 100 | +Keep shelling-out code inside the service, not in callers. | | 101 | + | | 102 | +## Shared leaf models | | 103 | + | | 104 | +Shared schema or model files can stay outside the service namespace when lower layers also depend on them. | | 105 | + | | 106 | +That is fine for leaf files like `schema.ts`. Keep the service surface in the owning namespace. | | 107 | + | | 108 | +## Migration checklist | | 109 | + | | 110 | +Done now: | | 111 | + | | 112 | +- [x] `AccountEffect` (mixed-mode) | | 113 | +- [x] `AuthEffect` (mixed-mode) | | 114 | +- [x] `TruncateEffect` (mixed-mode) | | 115 | +- [x] `Question` | | 116 | +- [x] `PermissionNext` | | 117 | +- [x] `ProviderAuth` | | 118 | +- [x] `FileWatcher` | | 119 | +- [x] `FileTime` | | 120 | +- [x] `Format` | | 121 | +- [x] `Vcs` | | 122 | +- [x] `Skill` | | 123 | +- [x] `Discovery` | | 124 | +- [x] `File` | | 125 | +- [x] `Snapshot` | | 126 | + | | 127 | +Still open and likely worth migrating: | | 128 | + | | 129 | +- [ ] `Plugin` | | 130 | +- [ ] `ToolRegistry` | | 131 | +- [ ] `Pty` | | 132 | +- [ ] `Worktree` | | 133 | +- [ ] `Installation` | | 134 | +- [ ] `Bus` | | 135 | +- [ ] `Command` | | 136 | +- [ ] `Config` | | 137 | +- [ ] `Session` | | 138 | +- [ ] `SessionProcessor` | | 139 | +- [ ] `SessionPrompt` | | 140 | +- [ ] `SessionCompaction` | | 141 | +- [ ] `Provider` | | 142 | +- [ ] `Project` | | 143 | +- [ ] `LSP` | | 144 | +- [ ] `MCP` |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/account/effect.ts +14-19Lines changed: 14 additions & 19 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -108,8 +108,8 @@ const mapAccountServiceError = | 108 | 108 | ), | 109 | 109 | ) | 110 | 110 |
| 111 | | -export namespace AccountService { | 112 | | - export interface Service { | | 111 | +export namespace AccountEffect { | | 112 | + export interface Interface { | 113 | 113 | readonly active: () => Effect.Effect<Option.Option<Account>, AccountError> | 114 | 114 | readonly list: () => Effect.Effect<Account[], AccountError> | 115 | 115 | readonly orgsByAccount: () => Effect.Effect<readonly AccountOrgs[], AccountError> | @@ -124,11 +124,11 @@ export namespace AccountService { | 124 | 124 | readonly login: (url: string) => Effect.Effect<Login, AccountError> | 125 | 125 | readonly poll: (input: Login) => Effect.Effect<PollResult, AccountError> | 126 | 126 | } | 127 | | -} | 128 | 127 |
| 129 | | -export class AccountService extends ServiceMap.Service<AccountService, AccountService.Service>()("@opencode/Account") { | 130 | | - static readonly layer: Layer.Layer<AccountService, never, AccountRepo | HttpClient.HttpClient> = Layer.effect( | 131 | | - AccountService, | | 128 | + export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Account") {} | | 129 | + | | 130 | + export const layer: Layer.Layer<Service, never, AccountRepo | HttpClient.HttpClient> = Layer.effect( | | 131 | + Service, | 132 | 132 | Effect.gen(function* () { | 133 | 133 | const repo = yield* AccountRepo | 134 | 134 | const http = yield* HttpClient.HttpClient | @@ -148,8 +148,6 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 148 | 148 | mapAccountServiceError("HTTP request failed"), | 149 | 149 | ) | 150 | 150 |
| 151 | | - // Returns a usable access token for a stored account row, refreshing and | 152 | | - // persisting it when the cached token has expired. | 153 | 151 | const resolveToken = Effect.fnUntraced(function* (row: AccountRow) { | 154 | 152 | const now = yield* Clock.currentTimeMillis | 155 | 153 | if (row.token_expiry && row.token_expiry > now) return row.access_token | @@ -218,11 +216,11 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 218 | 216 | ) | 219 | 217 | }) | 220 | 218 |
| 221 | | - const token = Effect.fn("AccountService.token")((accountID: AccountID) => | | 219 | + const token = Effect.fn("Account.token")((accountID: AccountID) => | 222 | 220 | resolveAccess(accountID).pipe(Effect.map(Option.map((r) => r.accessToken))), | 223 | 221 | ) | 224 | 222 |
| 225 | | - const orgsByAccount = Effect.fn("AccountService.orgsByAccount")(function* () { | | 223 | + const orgsByAccount = Effect.fn("Account.orgsByAccount")(function* () { | 226 | 224 | const accounts = yield* repo.list() | 227 | 225 | const [errors, results] = yield* Effect.partition( | 228 | 226 | accounts, | @@ -237,7 +235,7 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 237 | 235 | return results | 238 | 236 | }) | 239 | 237 |
| 240 | | - const orgs = Effect.fn("AccountService.orgs")(function* (accountID: AccountID) { | | 238 | + const orgs = Effect.fn("Account.orgs")(function* (accountID: AccountID) { | 241 | 239 | const resolved = yield* resolveAccess(accountID) | 242 | 240 | if (Option.isNone(resolved)) return [] | 243 | 241 |
| @@ -246,7 +244,7 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 246 | 244 | return yield* fetchOrgs(account.url, accessToken) | 247 | 245 | }) | 248 | 246 |
| 249 | | - const config = Effect.fn("AccountService.config")(function* (accountID: AccountID, orgID: OrgID) { | | 247 | + const config = Effect.fn("Account.config")(function* (accountID: AccountID, orgID: OrgID) { | 250 | 248 | const resolved = yield* resolveAccess(accountID) | 251 | 249 | if (Option.isNone(resolved)) return Option.none() | 252 | 250 |
| @@ -270,7 +268,7 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 270 | 268 | return Option.some(parsed.config) | 271 | 269 | }) | 272 | 270 |
| 273 | | - const login = Effect.fn("AccountService.login")(function* (server: string) { | | 271 | + const login = Effect.fn("Account.login")(function* (server: string) { | 274 | 272 | const response = yield* executeEffectOk( | 275 | 273 | HttpClientRequest.post(`${server}/auth/device/code`).pipe( | 276 | 274 | HttpClientRequest.acceptJson, | @@ -291,7 +289,7 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 291 | 289 | }) | 292 | 290 | }) | 293 | 291 |
| 294 | | - const poll = Effect.fn("AccountService.poll")(function* (input: Login) { | | 292 | + const poll = Effect.fn("Account.poll")(function* (input: Login) { | 295 | 293 | const response = yield* executeEffectOk( | 296 | 294 | HttpClientRequest.post(`${input.server}/auth/device/token`).pipe( | 297 | 295 | HttpClientRequest.acceptJson, | @@ -337,7 +335,7 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 337 | 335 | return new PollSuccess({ email: account.email }) | 338 | 336 | }) | 339 | 337 |
| 340 | | - return AccountService.of({ | | 338 | + return Service.of({ | 341 | 339 | active: repo.active, | 342 | 340 | list: repo.list, | 343 | 341 | orgsByAccount, | @@ -352,8 +350,5 @@ export class AccountService extends ServiceMap.Service<AccountService, AccountSe | 352 | 350 | }), | 353 | 351 | ) | 354 | 352 |
| 355 | | - static readonly defaultLayer = AccountService.layer.pipe( | 356 | | - Layer.provide(AccountRepo.layer), | 357 | | - Layer.provide(FetchHttpClient.layer), | 358 | | - ) | | 353 | + export const defaultLayer = layer.pipe(Layer.provide(AccountRepo.layer), Layer.provide(FetchHttpClient.layer)) | 359 | 354 | } |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/account/index.ts +7-7Lines changed: 7 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5,20 +5,20 @@ import { | 5 | 5 | type AccountError, | 6 | 6 | type AccessToken, | 7 | 7 | AccountID, | 8 | | - AccountService, | | 8 | + AccountEffect, | 9 | 9 | OrgID, | 10 | | -} from "./service" | | 10 | +} from "./effect" | 11 | 11 |
| 12 | | -export { AccessToken, AccountID, OrgID } from "./service" | | 12 | +export { AccessToken, AccountID, OrgID } from "./effect" | 13 | 13 |
| 14 | 14 | import { runtime } from "@/effect/runtime" | 15 | 15 |
| 16 | | -function runSync<A>(f: (service: AccountService.Service) => Effect.Effect<A, AccountError>) { | 17 | | - return runtime.runSync(AccountService.use(f)) | | 16 | +function runSync<A>(f: (service: AccountEffect.Interface) => Effect.Effect<A, AccountError>) { | | 17 | + return runtime.runSync(AccountEffect.Service.use(f)) | 18 | 18 | } | 19 | 19 |
| 20 | | -function runPromise<A>(f: (service: AccountService.Service) => Effect.Effect<A, AccountError>) { | 21 | | - return runtime.runPromise(AccountService.use(f)) | | 20 | +function runPromise<A>(f: (service: AccountEffect.Interface) => Effect.Effect<A, AccountError>) { | | 21 | + return runtime.runPromise(AccountEffect.Service.use(f)) | 22 | 22 | } | 23 | 23 |
| 24 | 24 | export namespace Account { | |
|