Skip to content

Latest commit

 

History

History
194 lines (144 loc) · 11.7 KB

AGENTS.md

File metadata and controls

194 lines (144 loc) · 11.7 KB

AGENTS.md

Guidance for AI agents working in this repository.

Overview

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.

Workflow

  1. Read relevant skill files before coding (see below).
  2. Keep diffs minimal and scoped to the task.
  3. Run targeted tests: bun test src/lib/<module>.
  4. Run bun check before finishing (lint, format, typecheck).
  5. Add or update docs in /docs when adding a module or changing public API (see Documentation).
  6. Do not commit or push unless explicitly asked.

Agent Skills

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.

Repo Constraints

  • Zero runtime dependencies - do not add packages without strong reason.
  • Imports - use .js extensions in TypeScript imports (from "./types.js").
  • Module layout - each package under src/lib/<name>/ typically has index.ts, types.ts, errors.ts, and colocated *.test.ts. Keep index.ts a 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). Keep index.test.ts for package-level or cross-cutting coverage. Pure types.ts needs no test file.
  • Package names - name semola/<name> after what the module ships (wire format, domain noun), not a vague umbrella. Prefer otel over observability when the surface is OTLP-shaped.
  • Types - In new or modified library source, define types in types.ts and 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> → TraceCarrier in types.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.ts or index.ts; consumers import from the defining file. Same-module barrel re-exports of that module's own public types are fine.
  • Errors - use mightThrow / mightThrowSync from semola/errors; define module-specific error classes in errors.ts.
  • Validation - Standard Schema in library code, not Zod-specific APIs.
  • Build - tsdown (not tsc for output).

Packages

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.

Tech Stack

  • Runtime: Bun
  • Language: TypeScript 7 (strict mode)
  • Linting/Formatting: Biomejs
  • Testing: Bun test
  • Schema: Standard Schema (framework-agnostic, works with Zod, Valibot, etc.)

Code Style

Clarity over compression

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."

Simplicity

  • 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 / hrtime are monotonic only), keep a small named helper - do not invent a fake "stdlib" wrapper.
  • Keep code breathing with blank lines between logical blocks.
  • Explicit if statements over ternaries. Do not use ternaries for control flow, assignments that branch, or nested conditions. Prefer early returns and plain if / 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 = () => { ... } (or const name = async () => { ... }), not function name(). Match existing Semola modules (api/validate.ts, api/dispatch.ts). Classes stay as class.
  • Prefer destructuring over indexed access when the shape is fixed (const [a, b] = parts, not parts[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 --stat before 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 any type. Infer types, avoid explicit return types. Use generics extensively.
  • No type predicates (value is Type return annotations) - use inline guards for narrowing.
  • No em-dashes; use regular hyphens.

Guards and control flow

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).

Error handling

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.

Dialect / adapter separation

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.

TypeScript edge cases

  • 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) not const v = options.validate; v(value).
  • Use explicit discriminant properties for union narrowing.
  • Avoid "flag" in obj when 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 const only; no per-entry as const on individual object literals inside the array.

Testing

  • Colocate tests with source (*.test.ts).
  • When a package is split into topical modules, give each implementation file its own <name>.test.ts. Use index.test.ts for cross-cutting package behavior. Extra suites (adversarial.test.ts) are fine on top of that.
  • Clear test names describing behavior.
  • Simple assertions without chains.

Commands

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

Documentation

  • New modules need a doc at docs/<module>.md (match existing module docs in /docs).
  • Each doc page needs YAML frontmatter with title and description for the Fumadocs site (apps/docs).
  • Update docs/meta.json sidebar 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/traces are fine when they are real URLs.

Boundaries

  • 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.