agentleFS
molecule-devmolecule-dev/molecule/AGENTS.md

molecule

AGENTS.md45 starsChanged 4 days agoApache-2.0View on GitHub

Parallel-agent machine: before a release, any npm install, or killing a process, register with the shared presence registry: node "$(node scripts/lib/aggregate-root.mjs)/scripts/agent-presence.mjs" register --repo molecule --work "<what>" then list / claim --exclusive release / verify --pid <pid> — see docs/agent-presence.md in the aggregate. Claude Code sessions are auto-registered by hook. Before writing any import, literal value, or function call, apply this test: "If we swapped out the implementation behind this (different provider, different framework, different library, different database), would this line…

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

18 rules. About 0 are common, 7 are distinctive, and 11 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before writing any import, literal value, or function call, apply this test:

    line 11
  2. Very specific:

    Always export * from './module.js' in barrel files.

    line 54
  3. Very specific:

    All imports MUST use .js extensions.

    line 58
  4. Distinctive:

    Every provider MUST export a typed constant:

    line 72
  5. Very specific:

    Never omit the type annotation.

    line 78
  6. Very specific:

    Never use localStorage/sessionStorage/AsyncStorage directly.

    line 98
  7. Distinctive:

    Never hardcode user-visible strings (labels, placeholders, messages, aria-labels).

    line 102
  8. Very specific:

    All versions in dependencies, devDependencies, and optionalDependencies must be exact — no ^, ~, *, >=, or ranges.

    line 112
  9. Distinctive:

    When adding to a namespace that already has bonds, either pick a name that cannot be read as a provider of the parent, or state the kind in …

    line 157
  10. Very specific:

    All exported functions, classes, interfaces, types, and constants require JSDoc with description, @param, and @returns where applicable.

    line 167
  11. Very specific:

    Never discard a caught error silently.

    line 175
  12. Very specific:

    All providers for a category return the SAME types.

    line 288
  13. Distinctive:

    Keep DOM-only APIs (layout measurement, raw HTML injection, HTML5 drag-and-drop) out of features that are not inherently DOM.

    line 337
  14. Very specific:

    Every package with user-facing text has a companion locale bond (@molecule/{stack}-locales-{name}) providing translations in 79 languages.

    line 346
  15. Distinctive:

    All spacing follows an 8px grid (4px for tight spaces)

    line 356
  16. Very specific:

    Use semantic colors (success/warning/error/info) for status indicators

    line 357
  17. Very specific:

    All interactive elements must include data-mol-id attributes for AI agent interaction

    line 358
  18. Distinctive:

    Every screen must work in both light and dark themes

    line 359

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md — molecule.dev

Parallel-agent machine: before a release, any npm install, or killing a process, register with the shared presence registry: node "$(node scripts/lib/aggregate-root.mjs)/scripts/agent-presence.mjs" register --repo molecule --work "<what>" then list / claim --exclusive release / verify --pid <pid> — see docs/agent-presence.md in the aggregate. Claude Code sessions are auto-registered by hook.

The Decoupling Principle

Before writing any import, literal value, or function call, apply this test:

"If we swapped out the implementation behind this (different provider, different framework, different library, different database), would this line need to change?"

If yes — you are coupling to an implementation. Fix it:

  • Importing a concrete driver in a handler? → Use the abstract core interface instead.
  • Using a platform-specific API directly? → Accept it as an injectable parameter.
  • Writing CSS class names in a component? → Use getClassMap() from @molecule/app-ui instead. The ONLY packages that may contain CSS class names are ClassMap bond packages (e.g., @molecule/app-ui-tailwind).
  • Writing raw SQL in handler code? → Use the abstract DataStore methods.
  • Hardcoding user-facing text? → Use t('key', values, { defaultValue }).

This single principle generates every specific rule below. When in doubt, return to this test.


Project Overview

Composable, injectable modules for full-stack applications.

  • Backend packages: @molecule/api-*
  • Frontend packages: @molecule/app-*
  • Core packages define contracts (interfaces only, zero implementation)
  • Bond packages implement those contracts and are swappable at runtime
  • Bond wiring: bond('category', provider) (singleton) or bond('category', 'name', provider) (named) at startup, require('category') anywhere

Rules

1. Module Organization

Split code into logical modules. NEVER put implementation code in index.ts.

src/
├── types.ts        # Types, interfaces, enums only
├── provider.ts     # setProvider/getProvider/hasProvider
├── [feature].ts    # Feature-specific logic
├── utilities.ts    # Helper functions
└── index.ts        # ONLY export * from './module.js' — barrel exports only

Always export * from './module.js' in barrel files. Never export { name } from or export type { Name } from.

2. ESM with .js Extensions

All imports MUST use .js extensions. TypeScript, ES2022, NodeNext module resolution.

// Correct
export * from './types.js'
import { DatabaseConfig } from '@molecule/api-database/types.js'

// Wrong
export * from './types'
import { DatabaseConfig } from '@molecule/api-database/types'

3. Typed Provider Exports

Every provider MUST export a typed constant:

export const provider: InterfaceType = { ... }

Never omit the type annotation. The core interface package is always a peerDependency.

4. No Concrete Dependencies in Core Packages

Core packages (packages/api/core/*, packages/app/core/*) contain ONLY interfaces and types. Zero implementation code, zero concrete library imports.

5. No CSS Class Names Outside ClassMap Bonds

No CSS class names ("flex", "p-4", "btn-primary", "items-center", etc.) may appear in ANY package except ClassMap bond packages (e.g., @molecule/app-ui-tailwind). This includes templates, components, tests, and generated code. Use getClassMap() from @molecule/app-ui instead. Swapping one styling library for another should only require changing the ClassMap bond — nothing else.

Inline styles must never conflict with ClassMap classes. Inline styles have higher CSS specificity than classes — setting background, border, color, etc. inline will silently override any ClassMap class controlling the same property (e.g., cm.surface, cm.borderBPrimary). If a property is managed by a ClassMap class, do not set it inline.

Before using any ClassMap class, check what it resolves to. ClassMap classes are defined in the bond package (e.g., @molecule/app-ui-tailwind/src/components.ts). Read the actual definition to understand what CSS properties it sets — do not guess. This takes seconds and prevents cascading mistakes.

6. No Raw SQL in Handlers

Handler code uses abstract DataStore methods (findOne, findMany, create, updateById, deleteById). Raw SQL only in database bond packages, migration scripts, or complex queries wrapped in dedicated functions.

7. No Hardcoded Storage

Never use localStorage/sessionStorage/AsyncStorage directly. Accept StorageAdapter as a parameter. Default to in-memory, not localStorage.

8. All UI Text Through i18n

Never hardcode user-visible strings (labels, placeholders, messages, aria-labels). Use:

t('key', values, { defaultValue: 'English fallback' })

Translations live in companion locale bond packages (@molecule/{stack}-locales-{name}), NOT embedded in feature packages. Each locale bond provides type-safe translations in 79 languages.

9. Exact Dependency Pinning

All versions in dependencies, devDependencies, and optionalDependencies must be exact — no ^, ~, *, >=, or ranges. The only exception is peerDependencies (which may use ranges for npm compatibility).

Enforced by .npmrc with save-exact=true. When writing code that touches dependency versions, always verify pinning.

10. Package Naming

A package name is a PUBLIC, PERMANENT interface. Once published, renaming it breaks every consumer, so the bar is "exceedingly clear", not "clear to whoever wrote it this afternoon".

  • Backend: @molecule/api-*, Frontend: @molecule/app-*
  • Project dev tooling that both workspaces install as a devDependency and no app or api source imports is named by its tool's own convention and has stack tooling (@molecule/eslint-config, in packages/tooling/). Search, catalogs and the create UI never offer it as a capability; the scaffold declares it.
  • Names must be specific enough to be unambiguous. Ask: "Could this name mean something else?" If yes, add a qualifier (e.g., app-ai-chat not app-chat).

Before you name a new package, answer these three in writing. Each one has been failed in practice; the third is the one that keeps being missed.

  1. Could this name mean something else in a list of 900 packages? A name built from generic nouns — state, data, core, common, manager, service, handler, engine, tools, support — describes nothing on its own and must be qualified until it does. Failed 2026-07-26: @molecule/api-external-state was created for "the state a project owns outside its source tree"; the name equally suggests client state, session state, feature flags, or a remote API's state. It was deleted the same day.
  2. Does the name say what the package IS, not just what it is near? A reader who has never seen it should be able to place it from the name alone.
  3. If it is inseparable from another package, does the name make the relationship obvious? A companion, an extension, or a second interface for an existing category is not "related-ish" — it is part of that thing. Prefer ADDING it to the existing package over minting a sibling with a name that only makes sense once you already know the answer. api-external-state existed solely to make api-project-archive complete; the fix was to fold it in as ProjectExternalStateProvider rather than to find a cleverer name.

The structural trap: a name cannot say whether a package is a core, a bond, a framework binding, or a utility — so do not let the name imply the wrong one. Bonds are api-<category>-<provider>, which means a CORE with the same shape is indistinguishable from a provider for a shorter category. This is real and current in the tree: under @molecule/api-ai-*, anthropic is a provider for api-ai, embeddings is its own core, agents-llm is a provider for api-ai-agents, and email-composer is a utility — four different kinds, one name shape. Same under api-oauth- (github = provider, client = core) and app-ui- (tailwind = provider, react = framework, showcase = core). Nothing but registry.json's type field tells them apart.

When adding to a namespace that already has bonds, either pick a name that cannot be read as a provider of the parent, or state the kind in the name. Do not add another collision to a namespace that already has them.

11. Cross-Stack Boundary

API packages cannot import @molecule/app-*. App packages cannot import @molecule/api-*. ESLint enforces this.

12. JSDoc on All Exports

All exported functions, classes, interfaces, types, and constants require JSDoc with description, @param, and @returns where applicable.

13. Import Ordering

Sorted by: node: builtins → external packages → @molecule/* → relative paths. Enforced by eslint-plugin-simple-import-sort.

14. No Silent Error Swallows

Never discard a caught error silently. Every catch (and .catch()) must do one of:

  1. Re-throw — optionally wrapped with more context (throw new Error('...', { cause: error })).
  2. Log the error via the logger, severity chosen by impact, always including the error:
    • logger.error('what failed and why it matters', { error }) — the operation failed and something is now broken or degraded.
    • logger.warn('...', { error }) — recoverable/degraded, but worth knowing.
    • logger.debug('...', { error }) — genuinely best-effort (cleanup, optional cache, a retry that will retry).
  3. Explicit, documented noop — bind as catch (_error) (the _ prefix marks "intentionally ignored") and add a comment explaining why ignoring is correct/safe at that exact spot.

Always bind the error (catch (error)) — never bindingless catch {}; you can't log what you don't bind. .catch(() => {}) with no log and no justifying comment is forbidden. The log message must give a future debugger a starting point (which operation, which resource) — a vague logger.warn('failed') that drops the actual error is itself a silent swallow. This rule exists because a single swallowed provisioning catch made an entire class of "api server down" failures nearly impossible to trace.

15. State a Project Cannot Regenerate Needs an External-State Bond

@molecule/api-project-archive captures a project and the caller then DESTROYS the original on result.verified — but it captures only from the ProjectExternalStateProvider bonds that are REGISTERED. State whose provider was never written is captured by nobody, verifies clean, and is then permanently deleted. That is silent data loss, not a missing feature.

So every provider bond in a state-owning category — today database (@molecule/api-database) and uploads (@molecule/api-uploads) — needs a matching bond under packages/api/bonds/project-archive-external-state/, or a written exemption saying where that provider's data already survives.

Write it per-provider: capture needs that provider's own tooling (pg_dump cannot dump MySQL). A single bond written against the CORE interface sounds tidier and was tried; it does not work for uploads, because UploadProvider.upload() takes no key and every bond mints a bare uuid at the backend root — so nothing generic can tell which objects belong to one project. Both uploads bonds are exempt for that reason, with the reason written down.

These bonds never DISCOVER what a project owns; configuration declares it. That is the whole design, and it is not a style preference — it is the outcome of two adversarial rounds. Every attempt to ask a server "does this project have a database?" is indistinguishable from a permissions failure (MySQL's information_schema omits rows the account cannot see; so does SHOW TABLES, so the dump is no second witness), and every attempt to ask a filesystem is indistinguishable from a bad path template. Since the caller destroys the project on a successful capture, an inferred absence deletes live data. So: an empty result from the injected resolver is the ONLY way to say "owns nothing", and a resolver returning anything else — undefined, '', a Set — is an error, not an absence.

Enforced by mlcl/scripts/check-external-state-coverage.mjs — npm run verify:external-state, and mlcl's npm test, which its CI runs. A NEW state-owning category is settled by one question, if this resource were deleted, could the project regenerate it from its source tree?, and a "no" means adding it to that script's STATE_OWNING ledger; cache, queue and search are recorded there as "yes", with reasons.


Anti-Patterns

  1. Concrete dependencies in core packages
  2. Returning raw provider types instead of normalized interfaces
  3. Skipping peer dependencies for core interfaces
  4. Hardcoded configuration instead of env vars via @molecule/api-config
  5. Implementation leakage — exposing provider internals in public API
  6. Non-conformant provider exports (loose functions instead of typed provider object)
  7. Named re-exports in barrel files (export { X } from) instead of export * from
  8. CSS class names in ANY package other than ClassMap bond packages
  9. Hardcoded UI text — English strings directly in JSX/templates instead of t('key') calls
  10. Embedding translations in feature packages instead of companion locale bonds
  11. Unpinned dependency versions (^1.0.0 or ~2.3.0 instead of exact 1.0.0)
  12. Inline styles that override ClassMap classes (e.g., style={{ background: 'transparent' }} silently kills cm.surface)
  13. Using ClassMap classes without checking their definitions in the bond package first
  14. Baking consumer-specific stream events or cards into a shared package. App-specific chat/stream events (e.g. molecule.dev's build_degraded upgrade notice) must NOT be added to the core @molecule/app-ai-chat event union or hardcoded in @molecule/app-ide-react's ChatPanel. Use the generic { type: 'custom', name, data } event + the registerCustomEventCard(name, factory) registry, and implement the specifics in the consuming app (e.g. molecule-dev/). The shared package stays generic; only the app knows about its own events. Same test as the Decoupling Principle: "would a different app using this package ever want this exact event/card?" If no, it belongs in the app, not the package.
  15. Silent error swallows — } catch {}, } catch { return null } with no log, .catch(() => {}), or a vague logger.warn('failed') that drops the actual error. Bind the error and log it (severity by impact), re-throw it, or document why the noop is safe with a catch (_error) + comment. See Rule 14.
  16. A provider bond that owns state a project cannot regenerate (a database, an uploads backend) with no matching bond under packages/api/bonds/project-archive-external-state/. The project archive destroys the original after capturing it, so uncovered state is silently, permanently deleted. See Rule 15.

Package Structure

Directory Layout

packages/
├── api/
│   ├── core/           # Abstract interfaces (database, emails, cache, ai, etc.)
│   ├── bonds/          # Provider implementations, grouped by category
│   │   ├── database/   #   e.g. postgresql/, mysql/
│   │   └── ...
│   ├── infrastructure/ # bond (wiring), resource (base resource)
│   ├── resources/      # Typed resources (user, project, device, etc.)
│   ├── middleware/      # Framework middleware wrappers
│   ├── utilities/      # Validation, JWT, password, etc.
│   ├── testing/        # Mock implementations and test helpers
│   ├── ci/             # CI integration packages
│   ├── staging/        # Staging driver implementations
│   └── locales/        # i18n translation packages
├── app/
│   ├── core/           # Abstract interfaces (ui, routing, state, etc.)
│   ├── bonds/          # Provider implementations
│   ├── infrastructure/ # bond (wiring)
│   ├── features/       # IDE, charts, maps, rich-text, video
│   ├── native/         # Device capabilities (camera, biometrics, etc.)
│   ├── frameworks/     # Framework bindings + UI (react, vue, svelte, solid, angular, react-native)
│   └── locales/        # i18n translation packages
└── tooling/            # Project dev tooling both workspaces install (eslint-config)

Key Patterns

Bond System

bond('category', provider) — string-based runtime wiring. Supports singleton (bond('category', provider)) and named providers (bond('category', 'name', provider)) for multi-provider categories like AI. Core defines contract → Provider implements → App wires at startup → Consumer uses anywhere via require('category') or get('category', 'name').

Normalization

All providers for a category return the SAME types. sendMail() returns EmailSendResult regardless of Sendgrid/Mailgun/SES.

Peer Dependencies

Providers declare core interfaces as peerDependencies. This prevents version conflicts and enables interface upgrades without breaking providers.

Three-Layer Frontend

  • Layer 1: Framework-agnostic interfaces (@molecule/app-ui, etc.)
  • Layer 2: Framework bindings (@molecule/app-ui-react, -vue, -svelte, -solid, -angular, etc.)
  • Layer 3: Library providers (@molecule/app-ui-tailwind, etc.)

Swap entire framework by changing Layers 2+3.

One Feature Implementation for React DOM and React Native

Owner directive (2026-11-24, from the start of v2): "use something like react-native-web (or similar/whatever) so that it would be super easy to support swapping renderers/etc without having to duplicate a bunch of work". A React feature package (features/*-react) is the implementation for React DOM and React Native both; no -react-native feature port is written. Vue, Svelte, Solid and Angular keep their ports, which the conformance kit holds to React's output.

React Native cannot render raw DOM tags (div, span, button). Every React feature renders the elements below except those in eslint-rules/intrinsic-jsx-pending.json (15 of 201 on 2026-11-26; the list may only shrink). The design:

  • Renderer-neutral elements (Box, Text, Pressable, TextField, Image, ScrollArea, Svg, Link, GlyphIcon). Their props are typed once in @molecule/app-ui (elements.ts). Each has an as prop naming the web tag. @molecule/app-ui-react/elements renders exactly that tag, so <Box as="ul"> is <ul> and every recorded golden stays the same. @molecule/app-ui-react-native/elements renders native views. A device has no CSS cascade, so the ClassMap's splitForNative applies text classes to the Text that draws them.
  • Features and the UI kit import @molecule/app-ui-react/elements. Its react-native export condition selects the native elements. The matching ./platform condition selects the device overlay host.
  • The kit is single-source: @molecule/app-ui-react's own components render with the elements. They are converted in order of how many features use them; Button and Spinner are done. @molecule/app-ui-react-native shrinks to the native elements plus platform pieces (overlay host, focus trap, click-outside, toasts) and never imports @molecule/app-ui-react. The RN scaffold imports @molecule/app-ui-react. No hand-written react-native stand-in maps native components to DOM tags.
  • Icon fonts: GlyphIcon draws a glyph by ligature on the web and by codepoint on a device, from the icon font's FontDefinition.glyphs and nativeFiles (@molecule/app-fonts-material-symbols/native).
  • A lint rule bans lowercase JSX tags in features/*-react and the kit's components, with a list of the packages not yet converted that may only shrink.
  • Features that are inherently DOM (canvas, maps, HTML5 drag-and-drop, media players, code editors) are registered web-only, so mlcl add refuses them on React Native with the reason. mlcl's pre-commit (scripts/check-react-native-refusals.mjs) refuses a registry in which a feature on the pending list has neither its own webOnlyReason nor a required peer that has one.

Keep DOM-only APIs (layout measurement, raw HTML injection, HTML5 drag-and-drop) out of features that are not inherently DOM.

UIClassMap

getClassMap() resolves styling at render time. Adding a styling library = 1 new ClassMap bond implementation. All framework packages work unchanged.

Locale Bonds

Every package with user-facing text has a companion locale bond (@molecule/{stack}-locales-{name}) providing translations in 79 languages. Feature packages use t(key, values, { defaultValue }) with English inline fallbacks. Locale bonds are pure data — swap one to override all translations for that feature.


Design System

Always reference DESIGN.md when generating or modifying any UI component. Use only the colors, fonts, spacing, and component values defined there — never invent arbitrary values.

Key rules:

  • All spacing follows an 8px grid (4px for tight spaces)
  • Use semantic colors (success/warning/error/info) for status indicators
  • All interactive elements must include data-mol-id attributes for AI agent interaction
  • Every screen must work in both light and dark themes
  • Meet WCAG AA contrast ratios (4.5:1 for body text, 3:1 for large text)

Per-app overrides go in each project's own DESIGN.md, extending the base system.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.