molecule
AGENTS.md44 starsChanged 59 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 ../scripts/agent-presence.mjs register --repo molecule --work "<what>" then list / claim --exclusive release / verify --pid <pid> — see ../docs/agent-presence.md. 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 need to change?" If…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,736 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.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
17 rules. About 0 are common, 6 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
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
- Distinctive: line 11
Before writing any import, literal value, or function call, apply this test:
- Very specific: line 54
Always export * from './module.js' in barrel files.
- Very specific: line 58
All imports MUST use .js extensions.
- Distinctive: line 72
Every provider MUST export a typed constant:
- Very specific: line 78
Never omit the type annotation.
- Very specific: line 98
Never use localStorage/sessionStorage/AsyncStorage directly.
- Distinctive: line 102
Never hardcode user-visible strings (labels, placeholders, messages, aria-labels).
- Very specific: line 112
All versions in dependencies, devDependencies, and optionalDependencies must be exact — no ^, ~, *, >=, or ranges.
- Distinctive: line 156
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 …
- Very specific: line 166
All exported functions, classes, interfaces, types, and constants require JSDoc with description, @param, and @returns where applicable.
- Very specific: line 174
Never discard a caught error silently.
- Very specific: line 286
All providers for a category return the SAME types.
- Very specific: line 306
Every package with user-facing text has a companion locale bond (@molecule/{stack}-locales-{name}) providing translations in 79 languages.
- Distinctive: line 316
All spacing follows an 8px grid (4px for tight spaces)
- Very specific: line 317
Use semantic colors (success/warning/error/info) for status indicators
- Very specific: line 318
All interactive elements must include data-mol-id attributes for AI agent interaction
- Distinctive: line 319
Every screen must work in both light and dark themes
≈ “Common” is an estimate: at least 1 in 5 of the 16,597 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.
Files
AGENTS.md — molecule.dev
Parallel-agent machine: before a release, any
npm install, or killing a process, register with the shared presence registry:node ../scripts/agent-presence.mjs register --repo molecule --work "<what>"thenlist/claim --exclusive release/verify --pid <pid>— see../docs/agent-presence.md. 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-uiinstead. 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
DataStoremethods.- 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) orbond('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 onlyAlways 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-* - Names must be specific enough to be unambiguous. Ask: "Could this name mean something else?" If yes, add a qualifier (e.g.,
app-ai-chatnotapp-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.
- 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-statewas 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. - 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.
- 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-stateexisted solely to makeapi-project-archivecomplete; the fix was to fold it in asProjectExternalStateProviderrather 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:
- Re-throw — optionally wrapped with more context (
throw new Error('...', { cause: error })). - 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).
- 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
- Concrete dependencies in core packages
- Returning raw provider types instead of normalized interfaces
- Skipping peer dependencies for core interfaces
- Hardcoded configuration instead of env vars via
@molecule/api-config - Implementation leakage — exposing provider internals in public API
- Non-conformant provider exports (loose functions instead of typed
providerobject) - Named re-exports in barrel files (
export { X } from) instead ofexport * from - CSS class names in ANY package other than ClassMap bond packages
- Hardcoded UI text — English strings directly in JSX/templates instead of
t('key')calls - Embedding translations in feature packages instead of companion locale bonds
- Unpinned dependency versions (
^1.0.0or~2.3.0instead of exact1.0.0) - Inline styles that override ClassMap classes (e.g.,
style={{ background: 'transparent' }}silently killscm.surface) - Using ClassMap classes without checking their definitions in the bond package first
- Baking consumer-specific stream events or cards into a shared package. App-specific chat/stream events (e.g. molecule.dev's
build_degradedupgrade notice) must NOT be added to the core@molecule/app-ai-chatevent union or hardcoded in@molecule/app-ide-react's ChatPanel. Use the generic{ type: 'custom', name, data }event + theregisterCustomEventCard(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. - Silent error swallows —
} catch {},} catch { return null }with no log,.catch(() => {}), or a vaguelogger.warn('failed')that drops the actualerror. Bind the error and log it (severity by impact), re-throw it, or document why the noop is safe with acatch (_error)+ comment. See Rule 14. - 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 packagesKey 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.
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-idattributes 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.
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
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.

