House style for afk. New code should be indistinguishable from what surrounds it; when in doubt, match the nearest file in the same tier. Citations point at real examples.
Non-negotiable; the reason for most rules below.
- Functional all the way. Pure functions, immutable data, side effects at the edges through Effect. No mutable shared state. The only classes are
Context.TagandData.TaggedError— never classes-with-behaviour. - Composition, never inheritance. Assemble behaviour from small services/layers and piped functions. No class hierarchy, ever.
- Code reads as a pipeline. Data flowing through transformations (
.pipe,Effect.gen), not imperative blocks mutating locals. - Domain-Driven naming. Use the glossary's words (Run, Run Plan, Backend, Owner, Golden Image, Ref). Need a word it lacks? Add it to the glossary first. Name the domain intent, not the mechanism.
Biome enforces it (cli/biome.json): bun run format writes, format:check verifies. Don't reformat surrounding code. Biome's linter is off; house rules run as GritQL plugins under cli/lint/ (bun run lint):
We have grit for rules that can't be enforced with formatting alone inside the lint folder.
- Services / adapters / tags / schemas:
PascalCase; file named after its primary export (Git.ts→Git). - Layers: name +
Live(GitLive,AwsBackendLive). A layer factory ismakeXxxLive. - Backend impls: provider prefix + interface (
AwsCompute/AwsComputeLive). - Constants:
SCREAMING_SNAKE_CASE, all inconstants.ts. - Locals:
camelCase; short abbreviations for yielded tags fine (const cfg = yield* ConfigService).
strict + noUncheckedIndexedAccess + noFallthroughCasesInSwitch.
readonlyon every field, property, and object-typed parameter.ReadonlyArray<T>, neverT[], at boundaries.import typefor type-only imports.- Indexed access is
T | undefined;!only after proving presence.
Service — Context.Tag class, interface inline as second type param, every member readonly, tag string = class name:
export class Subprocess extends Context.Tag("Subprocess")<
Subprocess,
{ readonly run: (cmd: string, args: ReadonlyArray<string>) => Effect.Effect<RunResult, SubprocessError> }
>() {}Layer — Layer.effect when it needs other tags (Effect.gen that yield*s deps, returns Tag.of({…})); Layer.succeed when it needs nothing. Always wrap the impl in Tag.of({…}).
export const GitLive = Layer.effect(
Git,
Effect.gen(function* () {
const sub = yield* Subprocess
return Git.of({ /* … */ })
}),
)gen vs .pipe — pick by readability. gen for imperative multi-step flows (command handlers, constructors); .pipe for single-value transform chains. Don't mix in one small op. Break long pipes one operator per line.
Pipelines over accumulator loops. When a body's job is to build a value (assemble a list, run checks, collect results), compose small named steps — don't push into a mutable local. Lift each unit to a named Effect<T>, assemble with Effect.all + Effect.map (independent) or Effect.flatMap (genuine data dependency). Reader scans names for what, opens one body for how. A for over results.push(…) is the smell this replaces.
// avoid — intent buried in an accumulator
const checks = []
for (const svc of services) {
checks.push(yield* probe(svc))
}
// prefer — each step named, assembly is one line
const probeAll = Effect.all(services.map(probe))- Not Effect-specific — governs plain helpers too, including the pre-runtime zone (
projectConfig.ts, thecli.tsBackend pick). A directory walk recursing to the filesystem root is tail-recursion, not a mutable loop (findProjectRoot). - Normalise so assembly is one flatten. Mismatched shapes? Lift every contributor to
Effect<ReadonlyArray<T>>and finishEffect.all([…]).pipe(Effect.map((gs) => gs.flat()))— reads as "gather, flatten," not nesting + spreads (CloudflareBackendDoctor.ts). - Branch a loaded result with
Effect.matchEffect, notEffect.either+_tag(which buries the branch). - Exception: a genuine dependent-effect chain (each
yield*consumes the previous) —genis the readable form. A deadline-gated poll with a real sleep (RunService.streamUntilTerminated,Ssm's wait) carries an explicit// biome-ignore lint/plugin/noloops: <reason>.
Functional core, imperative shell. Push pure decision logic out of the I/O gen.
- Core — plain function, data in/data out. No Effect, clock, randomness, I/O. Returns result and failures as data (an
Either<T, UserError>, or a record with an error field likeassembleRunPlan'scomposeError/warnings). - Shell — the
Layer/gen:yield*s effectful inputs, calls the core, performs the side effects its result gates, translates failures into the Effect channel. Non-deterministic seeds (randomUUID(), timestamps) are generated in the shell and injected, keeping the core deterministic. - Reward: a
bun testseam with no Layer — call the core, assert the return. Exemplarbackends/aws/AwsRunPlan.ts(tested byAwsRunPlan.test.ts), withAwsCompute.tsthe thin shell. - Don't force it where nothing pure exists to extract (same exception as above).
- A core output crossing a
Record<string, unknown>seam (e.g.PreparedRun.backendPlan): declare it a closedtype, notinterface— an interface's declaration-merging blocks direct assignment and forces a double cast. Unpack is a singleas(in-process reassertion, not a trust boundary — no Schema decode).
Errors
-
Every failure a
Data.TaggedErrorininfra/Errors.ts, in theAfkErrorunion — never scattered elsewhere.export class UserError extends Data.TaggedError("UserError")<{ readonly message: string readonly hint?: string }> {}
-
Computed messages via
override get message(). -
Never
throw.Effect.fail(new XxxError({…})); convert foreign throwables viaEffect.try/tryPromise'scatchorEffect.mapError. -
UserErroris user-facing; when the dev can fix it, give a concretehint:. -
Adapter errors wrap stderr with an
operationlabel (GitError,DockerError). -
Recovery —
Effect.catchAll(() => Effect.succeed(fallback))for best-effort reads only. Keep narrow; don't swallow errors you can act on.
All subprocess execution through the Subprocess tag — Bun.spawn only in infra/Subprocess.ts. run/runJson for captured output, runInteractive for TTY shells, stream for long-lived follows killed on interruption (registers a kill finalizer; runInteractive does not). Under --json an inherited child's stdout is redirected to stderr, so stdout stays parseable; stream is exempt, since there the child's output is the payload.
-
All in
schema/, each paired withtypeof X.Type.export const RunStatus = Schema.Literal("PROVISIONING", "RUNNING", "STOPPING", "STOPPED") export type RunStatus = typeof RunStatus.Type
-
Branded types for identifiers (
Schema.String.pipe(Schema.brand("RunId"))). -
Validate untrusted input with
Schema.decodeUnknown(X)(v).pipe(Effect.mapError(toDomainError))— never a bare cast across a process/file boundary.
-
One command per file; subcommand groups get a directory whose
index.tsdoes.pipe(Command.withSubcommands([…])). -
Options/Argsas module-level consts, each.withDescription.const ref = Options.text("ref").pipe(Options.optional) const command = Args.text({ name: "command" }).pipe(Args.repeated)
-
Command.make(name, options, handler), handler an arrow returningEffect.gen. Optional flags arrive asOption<T>— unwrap via._tag. -
Handlers
yield*services, route output throughOutput.emit, neverconsole.log.
A cost. Only to explain why something exists — never how/what the code says. Before writing, ask: does this add what the code can't? If not, delete it.
- Restates the code → delete.
- Earns its place: design rationale, non-obvious constraints (usually JSDoc on an exported tag/interface).
- Section banners fine for long composition files (
cli.ts). - Inline
//: lowercase, brief, rare.
Conventional Commits: <type>(<scope>): <subject>.
- Types:
feat,fix,chore,docs,refactor,test,build. - Scope = area touched (
cli,worker,aws,docs). - Subject: imperative, lowercase, no trailing period.
Two seams, no raw console.* elsewhere:
Output(infra/Output.ts) — results, to stdout,--json-aware viaemit({ data, human }). Keeps stdout clean JSON for… --json | jq.Logger(infra/Logger.ts) — diagnostics, to stderr, level-filtered.Effect.logWarning/logInfo/logDebug; it adds the prefix, so don't.
console.* allowed only inside those two sinks and the last-resort catchAllCause in cli.ts (runs outside all layers). A warning belongs on the Logger — routing it to stdout corrupts --json.
- Import a concrete backend (
AwsCompute) outsidebackends/aws/— depend on the tag. throw, send results anywhere butOutput, orBun.spawnoutside §5.- Add an npm dependency without need (
cli/bunfig.tomlpins exact versions). - Reformat unrelated code.