aidenlx/zotlit / .agents/skills/obsidian-services
obsidian-services
VerifiedService architecture for the Obsidian plugin: Effect services, the plugin runtime that composes them, and the plugin shell. Use when creating, modifying, or wiring services in apps/obsidian/src/services/ or editing zt-main.ts lifecycle code.
Service Architecture
Every plugin service is an Effect service (see Effect services).
Use the source as the canonical reference. Do not copy service/runtime/plugin-shell snippets out of this skill; read the current implementation before editing so examples cannot drift from real code.
Canonical Files
apps/obsidian/src/services/plugin-layer.ts:pluginLayer, the Effect graph and its build order.apps/obsidian/src/services/plugin-runtime.ts:createPluginRuntime— builds the runtime overpluginLayeron the caller's stack, awaits acquisition, then binds the edge handles, the runtime'sbridgeand the CLI runner, and returns them as one plain object.apps/obsidian/src/lib/effect-layer.tsandeffect-scope.ts: where a runtime or Scope meets anAsyncDisposableStack.apps/obsidian/src/zt-main.ts: plugin lifecycle ownership,await using,stack.move(), cleanup, and debug service access.apps/obsidian/src/lib/disposables.ts:Disposablehelpers forstack.use(...).
Workflow
- Open
apps/obsidian/src/services/plugin-layer.tsfor the Effect graph andapps/obsidian/src/services/plugin-runtime.tsfor howcreatePluginRuntimebuilds it and binds what the plugin shell reads. Treat these as authoritative. - Open
apps/obsidian/src/zt-main.tsbefore changing plugin load/unload behavior. Keep it a thin lifecycle shell. - For a new service, create
apps/obsidian/src/services/<service-name>/service.tsas an Effect service (see Effect services) and add its layer topluginLayer. When the plugin shell or a view calls it, read the tag once increatePluginRuntime(runtime.runSync(Tag)) and add it to the returned object; that code calls it through the runtime'sbridge. - Pass
plugin,plugin.app, and the values a registration needs explicitly through deps objects. Avoid module-global service lookups. - Use
apps/obsidian/src/lib/disposables.tshelpers when adapting Obsidian or DOM registrations intoDisposablevalues forstack.use(...). - Run the Obsidian package typecheck after edits.
Effect services
New services are Effect services: a Context.Service tag and a scoped Layer, composed in pluginLayer. createPluginRuntime builds that graph as a ManagedRuntime from buildRuntime (@/lib/effect-layer), whose disposal sits under everything the plugin shell puts on the stack, so the graph closes after the last shell registration. Settings and logging build below every other layer, so a service logs from its first line. UseLedger (apps/obsidian/src/services/use-ledger/) is the converted example; its __fixtures__.ts builds its layer over a fake App for tests.
- Import Effect from
effect; theeffectEntryVite plugin (apps/obsidian/scripts/effect-entry.ts) resolves it tosrc/lib/effect.ts. Its run entry points carry the browser scheduler and the logger, and no graph service. - The tag shape is Effect-native: each method with arguments is
Effect.fn("<Tag>.<method>"), a generator or a body that returns anEffect(Effect.fnUntracedon a per-message or per-item hot path; a test double stays a plain function). A member with no arguments is areadonlyEffectvalue traced withEffect.withSpan("<Tag>.<member>"), and callers writeyield* service.refresh, notservice.refresh()(effecttsgo/lazy-effectreports a zero-argument method); its test double is an Effect value too. Events are Streams and state:- What others watch is a
SubscriptionRef, exposed asSubscriptionRef.changes(ref): it replays the current value and ends when the layer's finalizer runsPubSub.shutdown(ref.pubsub). A stream that ends on a terminal state addsStream.takeUntil. - A discrete occurrence is a
PubSubexposed as a Stream. - A condition a late subscriber must still see (stopped, failed, finished) is state.
- What others watch is a
- Export the layer beside the tag as
layer<Name>(a function when it takes plain inputs). - The plugin shell and edge handles hold the tag's service and the runtime's
bridge(EffectBridge,@/lib/effect-bridge).createPluginRuntimereads the service once (release: runtime.runSync(Release)); consumers type their deps asPick<Release["Service"], …>besidePick<EffectBridge, …>and run each call through the bridge:runSync,runPromise,runPromiseExit(interrupted at unload, for a caller with its own closed answer),subscribe(stream, callback). A fire-and-forgetvoid bridge.runPromise(…)runs an Effect that cannot fail. - A state machine with concurrency of its own is Effect code in its layer, not a class: the Zotero Local API session (
zotero-local-api/session.ts,makeLocalApiSession) keeps its state inRefs, shares one request in flight between its callers through a slot, as the Capability Probe does, queues work per key with aSemaphore, forks background work on the layer's Scope so that closing the Scope interrupts and awaits it, bounds a request withEffect.timeoutOrElse, reads time from theClock, and cancels by interruption. A large state machine that coordinates none of that is Effect functions over one state record that its layer builds: the Annotation Repository core (annotation-repository/core/) takes theCoreStateas its first parameter,yield*s the services the record holds (ZoteroLocalApi["Service"],ZoteroReads["Service"],QueryClients["Service"]), and publishes its events through a callback the layer turns into Streams. The layer's membersyield*the core functions. Callbacks that a library calls (TanStack Query read and mutation functions) and theDisposablethatholdanswers are its edges, and run throughscopedBridge, the bridge over the layer's own Scope. - A layer reads the events of an Obsidian source that has a capability tag from the tag:
forkEach(filterTag(metadata.changes, "changed"), …)forMetadataCache(@/lib/obsidian-metadata-cache). A capability tag registers its listeners throughobsidianEventSource(@/lib/obsidian-event-source); the pattern is inapps/obsidian/policies/events.md→ Capability tags. A layer registers events from a source with no tag yet (vault,workspace, and one-shots such asonLayoutReady) throughobsidianEvents(@/lib/effect-obsidian-events). Any other Obsidian callback a layer registers runs its Effect through a runner made from the layer's context:const run = Effect.runSyncWith(yield* Effect.context<never>()). It keeps the layer's services and Clock, which the bare entry points lack. - Obsidian's
Appis theObsidianApptag (@/lib/obsidian-app). Time is the EffectClock, and dates in Effect code areDateTime;@/lib/effect-clockconverts them to theTemporal.Instantof plain code (toInstant,fromInstant,instantClock). - Resources live on the layer's Scope:
Effect.acquireRelease,Effect.addFinalizer, andacquireDisposable/acquireAsyncDisposablefor a value from outside Effect (rootpolicies/resource-disposal.md→ Effect code). - Put a side effect behind a tag of its own when a test must replace it.
LogOutputis the pattern:layerLoggingdrives LogTape through it, and its test supplies a fake whose work takesTestClocktime. - An Effect service has no
ready: the layer has finished building before anyone holds it. createPluginRuntimeawaits the layer graph (runtime.context()) before it reads any service, so a service anyone holds has finished acquiring. A layer's acquisition waits for exactly what its first answer needs, and no more. A wait on outside I/O (the Zotero database, a worker) is bounded withstartupBarrier(@/lib/effect-startup), which keeps the read running on the Scope past the bound. Acquisition settles and never fails the layer. A failed read becomes held state, logged with its fallback (UseLedger's saved Uses), because a layer that fails stops the plugin.- The
zotlit-serviceslint rules (apps/obsidian/scripts/oxlint-plugin-services.ts) enforce the mechanical rules. - A test fake of a service keeps its type: root
policies/testing-strategy.md→ Service fakes holds the pattern. - A view reads Effect services through view atoms, and its plain code (an Obsidian callback, a menu item) runs Effects on the leaf's view runner (
apps/obsidian/src/lib/view-runner.ts), made in the view's constructor and interrupted when the leaf closes:apps/obsidian/docs/adr/0082-obsidian-views-read-effect-services-through-view-atoms.mdholds the pattern catalogue, the pitfalls and the migration steps. A service a view reads joinsViewServicesinapps/obsidian/src/lib/view-atoms.ts.
Plugin Shell Notes
- Keep
zt-main.tsfocused on lifecycle wiring, action/menu/view registration, and cleanup. - Use the
await usingplusstack.move()pattern already implemented there for rollback-safe startup. - Do not treat the plugin
servicesgetter as normal dependency access. It is an escape hatch/debug surface; services receive deps throughpluginLayer, and shell registrations throughcreatePluginRuntime. - Wire Obsidian views by closure-capturing the needed services in the
registerViewfactory. - Compose with plain objects and functions in
createPluginRuntime; service wiring takes no ObsidianComponentsubclass, DI library or other runtime dependency.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |