effect-v4-house-style
The house style for Effect v4 library code — module layout, naming, typed-error taxonomy, API-surface and TSDoc habits, layer conventions, test organization, and observability posture. Use when writing or reviewing any Effect v4 module and deciding how to lay out files, name things, shape errors, document exports, wire layers, or organize tests — or when asked why this codebase "looks the way it does". Distilled from the @effected kit with the DX-north-star package (semver), a parser engine (toml), a boundary package (config-file) and the app plane (app) as the evidence base. Cross-cutting rules only; Schema depth lives in effect-v4-schema, hardening in hardening-a-parser-port.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 8
- Forks
- 2
01 前言 Front Matter
- name
- effect-v4-house-style
- description
- The house style for Effect v4 library code — module layout, naming, typed-error taxonomy, API-surface and TSDoc habits, layer conventions, test organization, and observability posture. Use when writing or reviewing any Effect v4 module and deciding how to lay out files, name things, shape errors, document exports, wire layers, or organize tests — or when asked why this codebase "looks the way it does". Distilled from the @effected kit with the DX-north-star package (semver), a parser engine (toml), a boundary package (config-file) and the app plane (app) as the evidence base. Cross-cutting rules only; Schema depth lives in effect-v4-schema, hardening in hardening-a-parser-port.
03 SKILL.md 正文
Effect v4 house style
The rules that make the code read as one hand's work. Each rule is stated once here (or linked to the skill that owns it); when writing new code, match these before inventing a local convention.
Module layout
- One PascalCase file per public concept; the file name IS the API name.
SemVer.tsexportsSemVer. No generic suffixes (SemVerParserLive.ts), no one-class error files — an error class rides in the file of the concept that raises it. src/index.tsis the ONLY re-exporting module. Flat named re-exports, types marked explicitly (per-lineexport type { X }or inlineexport { type X, Y }— both occur in the kit), noexport *. Every other module imports explicitly from the defining module. A barrel anywhere else — or a namespace object collecting cross-module implementations — is forbidden: a namespace object that gathers implementations pulling different engines kills tree-shaking silently (measured in this kit: 506 bytes vs 129.4 kB).- Grouped statics are the sanctioned exception, and their form is a static
class: same-module variants of one concept ship as
export class X { private constructor() {} static readonly a = a; … }, never as anas constobject — anas constobject's member types are inferred in the built.d.ts, which silently drops every member's TSDoc. The line is same module, one concept — never cross-module, never one-per-engine. A same-named interface never blocks the class form, generic or not: the class merges with it when it declares the same type parameters (same count and names, no conflicting defaults; variance annotations are optional — a mismatch is TS2428), under abiome-ignorefornoUnsafeDeclarationMerging.ResolvedTsconfigandGitHubFixtures(a statics-only class merged with the fixture-map interface) are the precedents;ActionsOidcis the plain case with no same-named type at all. The holdout rule, stated once:- A same-named
typealias forces a holdout. A class cannot share its name with atype(TS2300, duplicate identifier) and atypecannot merge, so the value stays aconst—as const, or explicitly typed when its members need declared signatures — with the rationale and every member's TSDoc on the const. Forced:SpdxExpression(@effected/spdx),EncryptedCodecKey(@effected/config-file) andUiKey(@effected/cli-kit, whose same-named union is the key model itself). - A by-choice holdout is a same-named interface that describes the
values the container builds — a strategy's
name/resolve, a version accessor'sget/set, an event descriptor, an envelope. Merging it onto a statics-only class would hang those members on the class's instance type, which nothing ever constructs, so theas constobject is allowed for exactly that reason and no other. By choice:MergeStrategyandVersionAccess(@effected/config-file),EnvelopeandJsonlEvent(@effected/jsonl). - Everything else is the static class; a module-private
as constlookup table that is never exported is not a container and needs no exemption.
- A same-named
src/internal/holds the engine;index.tsnever exports from it. Composition-only packages own nointernal/at all — "no engine, only composition" is a legitimate shape.- The cycle firewall: the internal engine throws/returns raw untyped
carriers (
{ code, message, offset, length }records, plainErrorsubclasses); the facade catches, triages with orderedisXguards, and materializes the public Schema classes. The dependency edge runs facade → engine only. Sanctioned exception: the engine may import leaf value classes with no outward edges (aTomlNodethat imports onlyeffect). - File splits can be load-bearing for bundles, not just readability: two sibling modules that must not drag each other's dependencies (config vs SQLite) simply never import each other — document that the split is deliberate.
Naming
- No floating functions. Instance methods are canonical; cross-cutting
operations with no instance counterpart are
Function.dualstatics on the owning class (Range.satisfies,SemVer.truncate). Never give a static the same name as an instance method: API Extractor cannot resolve a{@link}to either, so derive data-last forms from anOrderinstead. - Copy a class instance by spreading it. A transform that must preserve
every field but one is
X.make({ ...x, field: next }), never a hand-listed literal that drops whatever field is added next — seeeffect-v4-schema. Schema.Classmember placement — one rule. Anything that produces or classifies a value is astatic: constructors and parsers (parse/parseResult—makeis reserved, seeeffect-v4-schema), decoders, combinators over the type, and stateless taxonomy/predicates on raw inputs. Anything that operates on an already-decoded instance is an instance method. Worked precedents in the kit:Manifest(staticschema/decode, instanceresolve()/toRecord()) andReleaseAgeGate(staticcombine/matchesExclude, instanceisExcluded/filterVersions). NotematchesExcludeappears in both shapes deliberately — the static takes the patterns as an argument, the instance method readsthis.exclude; when both are useful, the instance method delegates to the static rather than duplicating it. Two implementation agents each had to infer this rule by readingManifest, which is why it is written down here.- Service shape interfaces are
<Concept>Shape(VersionCacheShape,ConfigFileShape<A>). Options records are<Concept>Options, all fieldsreadonly, non-obvious defaults documented per field. - Errors are
<Concept><FailureNoun>Error— neverException, neverFailure. Structured code fields get a parallel<Concept><Stage>ErrorCodeliteral-union schema. - Per-operation failure unions are type-only aliases named
<Operation>Error(ConfigLoadError = A | B | C), each with TSDoc stating exactly what is excluded and why. A type-only union costs nothing and is not a namespace object. - String codecs are class statics named
FromString, explicitly typedSchema.Codec<Self, string>(the annotation breaks circular inference). - Static-namespace facades:
class X { private constructor() {} }withstatic readonlymembers, for schema/parse AND layer-factory facades alike — never theas constobject form, whose member TSDoc does not survive into the built.d.ts. The grouped-statics rule above is the one statement of which holdouts exist and why. Do not invent a third shape.
Typed error taxonomy
- Never a free-form
reason: stringfield. The token appears in TSDoc@remarksonly as the anti-pattern being named. Areasonfield typed as aSchema.Literalsunion (glob, lockfiles, tsconfig-json do this) is fine — the rule bans free-form strings, not the field name; new code should still prefer the<Concept><Stage>ErrorCodenaming below. Structured diagnostics carry a positional core:code(literal union),message,offset/length,line/character— the same shape across every format package, deliberately. - Foreign failures ride in
cause: Schema.Defect(), never stringified — the originalErrorinstance survives to the consumer. Schema issues ride inissue: Schema.Defect()(v4 exposes noSchemaforIssue; say so in the remarks). NormalizeSchemaErrorto a domain error at the boundary withEffect.catchTag("SchemaError", ...). messageis always a getter derived from structured fields at read time — never a stored, preformatted string.- Failure vs defect, the house line: malformed input fails through the
typed error channel, always (see
hardening-a-parser-port); bad wiring (an invalid namespace at layer construction, a NaN depth cap) dies as a defect, deliberately, and gets a regression test asserting it dies. A recoverable environmental failure (missing directory) must surface typed even when the underlying platform API would defect — neverorDieit away. - Caller-supplied callbacks: decide absorb-vs-defect by one rule — does
the callback's RESULT participate in the operation's outcome? A migration
upor avalidate(yes) stays a defect on throw — a contract violation; a fire-and-forget event hook (no —Effect<void>, discarded) is absorbed andlogDebug'd. Wrap callback invocation inEffect.suspendso a throw during construction dies the same way as one during execution. - Decorators widen, never flatten: a wrapper over a codec/service is
generic in the inner error and returns
Inner<E | NewError>— the inner error type survives in the union. - A parse failure carries an ARRAY of diagnostics even when only one is populated today — the array is the cross-package contract.
Sum types: a domain-named discriminant on Schema.Class variants
The kit's model for a sum type — production-proven by
@effected/github-actions' InstalledPackageManager and named "the model"
by its first consumer — is two (or more) Schema.Class variants carrying
Schema.tag on a domain-named discriminant (source, not _tag),
unioned via Schema.Union. Narrowing needs no ceremony
(x.source === "tool-cache" narrows), Schema.tag auto-fills the
discriminant in make so a double cannot mint a mismatched variant, and an
impossible state becomes unrepresentable rather than guarded (the consumer
deleted an Effect.die guard and its test on adoption). Prefer this over
one class with optionalKey fields plus a prose invariant.
Two adoption traps, both hit live and both documented on the worked
precedent's union TSDoc (PackageManagerInstaller.ts): the union's
inherited make typechecks against both variants and yields a
confusing two-branch error — construct the variant classes; and
Partial<Variant> includes the auto-filled tag field, so overrides-style
doubles want Partial<Omit<typeof Variant.Type, "source">>. The
Schema.tag mechanics live in effect-v4-schema's foreign-contracts
section.
API surface and TSDoc
- Every exported symbol carries
@public; everything ininternal/carries@internal. The inline class-factory + scoped_basesuppression idiom that keeps API Extractor at zero warnings is owned byeffect-api-extractor-bases— a package with no class factories carries no suppression at all. @remarksrecord WHY, not what — including naming the anti-pattern the shape rules out ("a flattenedreason: String(e)loses the cause") and the looks-right-but-isn't traps. Signature restatement is noise.@exampleblocks are runnable and minimal: pure APIs end withconsole.logand a// =>comment showing the literal output; boundary APIs show the layer-composition shape instead.- The bind-to-a-const warning is boilerplate, verbatim, on every
factory: any schema-producing or layer-returning function's TSDoc repeats
the house phrase — each call mints fresh derivation/memoization identity;
bind the result to a
constor the resource builds twice. Consistent wording beats novel prose.
When misuse is SILENT, document the wrong spelling and what it cost
For any API whose wrong call sequence typechecks, runs, and reports
success, ordinary "here is the right way" documentation does not work. The
reader is not looking anything up — they already believe they know the shape,
and nothing will contradict them. GitBranch.upsert
(packages/github/src/GitBranch.ts) is the worked example, mirrored as a
"Never" in packages/github/CLAUDE.md. Three ingredients, all cheap:
- Spell out the wrong sequence literally — "never
upsert(branch, targetHead)followed bycommitFiles". It must match what the reader is about to write, not only what they should write instead. Prose describing the correct shape never collides with a plan; the wrong spelling does. - State what it cost, concretely. The ~3-second window where the branch equals its base, an open PR with an empty diff, GitHub auto-closing it, a consumer losing its release PR while the run reported success. Severity is what converts "noted" into "stop".
- Name the consumer that hit it. That is how a reader recognizes their own code in the description.
It works. A port onto the kit read that docstring, recognized the sequence in the action it was porting, and flagged it as a decision needing a human ruling — finding a live bug instead of faithfully reproducing it. Literal parity would have carried the defect forward.
Apply it deliberately to the other ordering-sensitive and upsert-shaped surfaces, not just where someone has already been burned. The test for whether an API qualifies: would the wrong call go green? If yes, the anti-pattern belongs in the docstring.
Services and layers
The mechanics live in effect-v4-services-layers; the house habits:
- A service's layer(s) live in the same file as the service (
static readonly layeron the class). Naming:layer,layerTest,layerConfig,layerSqlite— neverDefault/Live. Layer.unwrap(Effect.gen(...))is the idiom for a layer that must read an ambient service before constructing its own value.- Composition vocabulary:
Layer.mergeAllfor independent siblings,Layer.provideMergeto satisfy AND expose,Layer.provideto satisfy without exposing. - Require core contracts in
R; never own a platform backend. Nonode:imports in productionsrc/— platform packages appear only as devDependencies for integration tests, and the consumer provides one platform layer at the edge. - Test layers provide their platform internally (
Layer.provide, not merge) soR = neverby construction, not by cast — pin it with a test comment: "if this fixture ever needs a platform import, the layer stopped doing its job." - Ambient identity over parameters: when two sibling layers must agree on an identity string (a namespace), the second reads it from the ambient service the first established — never a second string parameter that can drift. Pin the absence of the parameter with a regression test.
Test organization
The false-green catalogue and @effect/vitest mechanics live in
effect-v4-testing; the house habits:
- Tests in
__test__/, never co-located:*.test.tsunits at the top,integration/*.int.test.ts,e2e/*.e2e.test.ts.assert.*exclusively —expectdoes not appear.it.effectis the default mode. - Shared setup is one top-level
layer(...)((it) => {...})per group — notEffect.providerepeated per test body. Sanctioned deviation: when fixtures genuinely differ per test (different files on disk per case), alayerFor(...)helper per test is correct — but say so. - Fakes, not mocks — and fakes deliberately missing methods. A read-only fake filesystem implements exactly the operations the read path uses, so a test that unexpectedly writes fails loudly. Document each fake's restriction where it is defined.
- Shared guard-case fixtures: one exported case-matrix function
(
filenameGuardCases) consumed by every module with the same option, so a new rejected shape is added once and pins every guard. - Property tests state the invariant as a sentence ("round-trips decode(encode(v))") over the class schema as the arbitrary; comments cite the review/bug that motivated an exact bound.
- Corpus/compliance suites are loop-generated (one
it.effectper corpus file, name = relative path) and FIRST assert the corpus walk found the expected counts — a silently-empty walk is a false green. - A differential oracle is one pinned devDependency imported by exactly one test file, with the tiebreak written down: the spec corpus wins on disagreement.
- Integration tests assert on real side effects at the joined path, never an echoed option value — and include the "naive composition" control proving the defect the package exists to prevent.
Observability posture
Details in effect-v4-observability; the house numbers:
Effect.fn("Concept.op")on every fallible public boundary; nothing else. Pure/total helpers are plain functions; never-failing service methods are plain arrows; internal helpers shared by public spans are NOT wrapped, with a comment stating the caller already opened the span.- Log density is near zero. The one sanctioned
Effect.log*shape in a library islogDebugrecording a deliberately absorbed defect. No metrics in libraries — those belong to boundaries apps own. Libraries stay telemetry-agnostic; apps compose OTel at the edge. - A consumer-facing event stream (a domain
PubSub) is a FEATURE, not the observability channel — keep it separate from spans and say so in TSDoc.
Related skills
effect-v4-schema (Schema depth: Class-vs-Struct, optionality, make-vs-new,
brands — plus its references/house-style.md for Schema-specific house
patterns), effect-v4-services-layers (memoization discipline),
effect-v4-testing (false greens), effect-api-extractor-bases (the _base
idiom), hardening-a-parser-port (input hardening), effected-packages
(what the kit ships).
04 同仓库更多 Skills
testing-actions
Use when writing or reviewing tests for @effected/github-actions, @effected/github, @effected/sbom or @effected/commands — stubbing the GitHub API, writing a service's layerTest or makeTest double, testing the pre/main/post lifecycle through Action.run, or debugging why a test hits the real network or hangs.
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.
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.
running-commands-and-tools
Use when running a subprocess in Effect v4, spawning a command, capturing stdout/stderr/exit 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.
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.
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.