Guidance for AI agents working in this repository.
Semola is a zero-dependency TypeScript utility library for Bun: type-safe APIs, queues, pub/sub, caching, i18n, auth, workflows, ORM, and more. Each package is tree-shakeable via semola/<package-name> imports.
- Read relevant skill files before coding (see below).
- Keep diffs minimal and scoped to the task.
- Run targeted tests:
bun test src/lib/<module>. - Run
bun checkbefore finishing (lint, format, typecheck). - Add or update docs in
/docswhen adding a module or changing public API (see Documentation). - Do not commit or push unless explicitly asked.
Read each skill file and follow its instructions.
| Skill | When | Path |
|---|---|---|
| caveman | Default for communication (terse, accurate) | .agents/skills/caveman/SKILL.md |
| review-loop | After a feature lands: code review, fix, rethink, repeat until a review round finds nothing new | .agents/skills/review-loop/SKILL.md |
| pr-review | Before merge: one fresh subagent reviews the whole PR cold, verifies findings by running them, reports only | .agents/skills/pr-review/SKILL.md |
| rethink | Assume the implementation is wrong: recommend a smaller design, apply, re-review in a loop until nothing is left to cut | .agents/skills/rethink/SKILL.md |
Caveman is always on. Review-loop, pr-review, and rethink are task-triggered. Caveman affects prose only - never reduce code quality, test coverage, or correctness.
- Zero runtime dependencies - do not add packages without strong reason.
- Imports - use
.jsextensions in TypeScript imports (from "./types.js"). - Module layout - each package under
src/lib/<name>/typically hasindex.ts,types.ts,errors.ts, and colocated*.test.ts. Keepindex.tsa thin barrel when the implementation grows; split by topic (propagation.ts,otel.ts,tracer.ts) rather than one giant file. Prefer few topical files over deep folder trees. When split, each implementation file gets a matching<topic>.test.ts(propagation.ts→propagation.test.ts). Keepindex.test.tsfor package-level or cross-cutting coverage. Puretypes.tsneeds no test file. - Package names - name
semola/<name>after what the module ships (wire format, domain noun), not a vague umbrella. Preferoteloverobservabilitywhen the surface is OTLP-shaped. - Types - In new or modified library source, define types in
types.tsand import them from there. Do not introduce inline object types (const x: { a: string },fn(arg: { a: string }), inline return shapes) or inline union parameter types used at API boundaries (carrier: Headers | Record<string, string>→TraceCarrierintypes.ts). Existing inline shapes may stay until that code is touched. Tests may use inline shapes for fixtures. Do not re-export types from other modules'types.tsorindex.ts; consumers import from the defining file. Same-module barrel re-exports of that module's own public types are fine. - Errors - use
mightThrow/mightThrowSyncfromsemola/errors; define module-specific error classes inerrors.ts. - Validation - Standard Schema in library code, not Zod-specific APIs.
- Build -
tsdown(not tsc for output).
Modules live in src/lib/<name>/ and export via semola/<name>. Discover the current set from package.json exports and src/lib/ - do not maintain a static list here.
- Runtime: Bun
- Language: TypeScript 7 (strict mode)
- Linting/Formatting: Biomejs
- Testing: Bun test
- Schema: Standard Schema (framework-agnostic, works with Zod, Valibot, etc.)
Code should read like English. Prefer clarity over clever density.
- Prefer named functions/methods whose names state intent over inlined checks, nested ternaries, or compressed one-liners (
assertDestructiveAllowed,canAddColumnInPlace,writeMigrationFolder). - Prefer pure imperative code: early returns, blank lines between steps, separate
ifs for unrelated conditions. Avoid ternaries and&&/||chains for control flow. - More lines are fine when they make the story clearer. Do not shrink for shrink's sake ("deslop" that only compresses and hurts readability is wrong).
- Cut dead paths, duplicate branches, and clever indirection. Do not invent abstractions "for later."
- Keep helpers that already clarify intent (e.g.
requireBoolean,nonEmptyString,mightThrow). Do not inline those back to "simplify."
- Write minimal code, no over-engineering (fewest files, shortest working diff - not shortest unreadable line). Production-ready means correct wire/interop and lifecycle, not a full vendor SDK surface.
- Prefer Bun / Node / stdlib helpers when they exist. Do not hand-roll parsers or converters the platform already covers. When the platform has no fit (example: wall-clock Unix epoch nanos for OTLP;
Bun.nanoseconds/hrtimeare monotonic only), keep a small named helper - do not invent a fake "stdlib" wrapper. - Keep code breathing with blank lines between logical blocks.
- Explicit
ifstatements over ternaries. Do not use ternaries for control flow, assignments that branch, or nested conditions. Prefer early returns and plainif/else. Nullish coalescing (??) and optional chaining (?.) are fine. - Blank lines between if-statement groups, const definitions, and return statements inside functions.
- Module helpers use
const name = () => { ... }(orconst name = async () => { ... }), notfunction name(). Match existing Semola modules (api/validate.ts,api/dispatch.ts). Classes stay asclass. - Prefer destructuring over indexed access when the shape is fixed (
const [a, b] = parts, notparts[0]/parts[1]). - Prefer a named regex constant (or a simple alphabet string) for hex/format/wire checks. Collapse split-and-validate parsers (
parts.length !== 4) into one regex when the format is fixed. Do not invent char-code ranges, paired micro-helpers (isX/isXChar), or constant inflation that renames every literal (HTTP_STATUS_OK_MIN). - Opaque numbers - if a reader cannot tell what a numeric literal means from the surrounding name, name it or wrap it (
TRACE_FLAGS_HEX_WIDTH,formatTraceFlagsHex). Protocol field widths, magic lengths, and flag encodings count. Leave obvious literals alone (0,1, empty checks). - Delete unused types, error classes, and fields. Do not keep pass-through wrappers that only forward one call.
- A deslop/simplification pass should shrink the code. Check
git diff --statbefore reporting: excluding bug fixes, the pass should remove more lines than it adds (tests included). Do not add a helper, type, or test file to remove a single cast or line. Look for redundant tests too (one test whose assertions another already covers). Report bug-fix LoC separately from cleanup LoC. - No
anytype. Infer types, avoid explicit return types. Use generics extensively. - No type predicates (
value is Typereturn annotations) - use inline guards for narrowing. - No em-dashes; use regular hyphens.
Separate unrelated checks into their own if statements:
// bad
if (value instanceof Error && value.code === "ENOENT") return;
// good
if (!(value instanceof Error)) return;
if (value.code === "ENOENT") return;Same for early returns - no || / && combining unrelated conditions:
// bad: if (a || b) return;
// good: if (a) return; if (b) return;
// bad: if (column.isUnique && !column.isPrimaryKey) { ... }
// good:
if (column.isUnique) {
if (!column.isPrimaryKey) {
// ...
}
}Related conditions that express one intent may stay together when a named helper or clear name makes that intent obvious (isUniqueOrPrimary).
Use mightThrow / mightThrowSync from semola/errors instead of try-catch:
const [error, data] = await mightThrow(fetch(url));
if (error) throw new FetchError(error.message);Thrown values are always Error instances (library errors extend Error). Use error.message directly - never instanceof Error guards or ternaries when reading the message in code or docs.
Do not wrap a call in mightThrow only to re-throw the same error unchanged - let it propagate:
// bad
const [error, data] = await mightThrow(fetch(url));
if (error) throw error;
// good
const data = await fetch(url);Use mightThrow when you transform the error, branch on it, or need a tuple without try-catch for control flow.
When a module supports multiple adapters (or dialects), keep an adapter-driven design: a shared base plus per-adapter subclasses (or equivalent strategy objects).
- Adapter-specific behavior belongs on the adapter/dialect (override methods), not
if (adapter === "…")(or equivalent) scattered through generic helpers. - Do not collapse adapters into shared functions full of adapter branches.
- No inline object type literals in library source. Name the type in
types.ts. - Const type parameters for literal types.
- After a guard, prefer
?.over extracting a local -options.validate?.(value)notconst v = options.validate; v(value). - Use explicit discriminant properties for union narrowing.
- Avoid
"flag" in objwhen all union members declare the property (the check is always true). - Truthiness checks (
obj.flag) only work as discriminants when falsy values (false,0,"") are not valid states. - Array-level
as constonly; no per-entryas conston individual object literals inside the array.
- Colocate tests with source (
*.test.ts). - When a package is split into topical modules, give each implementation file its own
<name>.test.ts. Useindex.test.tsfor cross-cutting package behavior. Extra suites (adversarial.test.ts) are fine on top of that. - Clear test names describing behavior.
- Simple assertions without chains.
bun check # lint + format + typecheck (always run before finishing)
bun test # run all tests
bun test src/lib/api # run tests for a specific module
bun test --watch # watch mode
bun run build # build package
bun pm version <major|minor|patch> # bump version for publishing
bun pm version preminor --preid beta # first beta of next minor (npm tag beta)
bun pm version prerelease --preid beta # later betas (npm tag beta)
# Postgres integration (when SEMOLA_POSTGRES_URL is set):
# docker run -d --name semola-pg-test -e POSTGRES_USER=semola -e POSTGRES_PASSWORD=semola \
# -e POSTGRES_DB=semola -p 5432:5432 postgres:16-alpine
# SEMOLA_POSTGRES_URL=postgres://semola:semola@localhost:5432/semola bun test src/lib/orm- New modules need a doc at
docs/<module>.md(match existing module docs in/docs). - Each doc page needs YAML frontmatter with
titleanddescriptionfor the Fumadocs site (apps/docs). - Update
docs/meta.jsonsidebar order (and section separators) when adding a page. - Update existing docs when public API, behavior, or usage changes.
- Skip docs only for internal refactors with no user-facing change.
- Docs site:
bun run docs:dev(not part of the published package). - Write what the API does today. Do not use roadmap voice ("in v1", "no X yet", "coming soon", "for now"). Protocol path segments like OTLP
/v1/tracesare fine when they are real URLs.
- Do not add runtime dependencies.
- Do not commit or push unless explicitly asked.
- Do not refactor unrelated code while fixing a bug.
- Keep plans concise.
- No em-dashes in code comments or documentation.