Repository navigation
Master Rules
Canonical source:
rules/00-master-rules.md— this page is rendered from it on every publish; edit the source.
Every AI agent (Claude, Codex, Cursor, Copilot, or any other) working on this codebase MUST read and obey every rule in this folder. These rules override default AI behavior. There are no exceptions and no situational bypasses.
rules/ is the single authoritative source of constraints for every contribution to ClawAI — human or AI. Each file covers one responsibility domain. All rules are strict, non-negotiable, and enforced by pre-commit hooks and CI.
| File | Domain |
|---|---|
01-planning-rules.md |
Phase 0–0g: planning gate before every change |
02-backend-rules.md |
NestJS architecture: controllers, services, managers, repos |
03-frontend-rules.md |
Next.js architecture: pages, hooks, components, state |
04-testing-rules.md |
Mandatory testing: TDD, unit, API (20-25×), UI, QA, UAT, coverage |
05-infra-rules.md |
Docker, Nginx, CI, .env, shared packages |
06-docs-rules.md |
Documentation: when, where, what format |
07-commit-rules.md |
Conventional commits, PR rules, branch rules |
08-security-rules.md |
Security: secrets, auth, input validation, OWASP |
09-refactor-rules.md |
Refactor discipline: extraction, dedup, logging, coverage, splits |
26-prompt-pack-intake-protocol.md |
Prompt-pack intake: what MUST happen before code when work arrives as a document |
27-engineering-mindsets.md |
The 26 mindsets: the default operating mode for every agent (moved out of CLAUDE.md) |
28-billing-integrity-and-api-contracts.md |
Billing immutability, refund entitlement, exact FE/BE contract tests |
29-communication-style.md |
Short, plain, concrete replies; stay foreground and keep streaming |
30-agent-self-regulation-and-loop-prevention.md |
Loop/drift prevention: nesting, retry, and verification budgets; discovery classification; deadlock/livelock recovery |
31-anti-gaming-and-semantic-compliance.md |
Anti-gaming: rule 30's budgets enforced by intent, not literal syntax; false progress/completion/blocker guards; executive override protocol |
32-underthinking-and-reasoning-balance.md |
Reasoning floor: the counterweight to rule 30 — architecture/root-cause/evidence/security floors, decision-readiness gate |
01-task-intake-and-planning.md |
No line of code is written before the task is understood and its blast radius is mapped. |
02-monorepo-and-workspace-ownership.md |
ClawAI is an npm-workspaces monorepo: 21 NestJS services, one Next.js frontend, and six shared packages. |
03-microservice-boundaries.md |
Each ClawAI service owns its data and its process. |
04-nextjs-app-router.md |
apps/claw-frontend is a Next.js 16 App Router application (React 19.2). |
05-frontend-components-and-hooks.md |
Components render; hooks hold logic. Splitting them — and keeping each small and single-purpose — is what makes the frontend reviewable and testabl… |
06-frontend-queries-and-cache.md |
All server state flows through TanStack Query; client-only state flows through Zustand. |
07-backend-controllers-and-transport.md |
Controllers are the thinnest layer: they translate transport (HTTP/SSE) into a single service call and translate the result back. |
08-backend-managers-and-use-cases.md |
Managers hold complex orchestration that would bloat a service method: parallel LLM calls, retry chains, external-API sequencing, multi-step assembly. |
09-backend-services.md |
Services are the business-logic layer: they own domain rules, ownership/permission checks, and event publishing. |
10-repositories-and-persistence.md |
Repositories are the only place database queries live. |
11-dtos-and-validation.md |
Every byte that enters a service is validated at the boundary with Zod. |
12-types-enums-constants-and-declaration-ownership.md |
Every declaration has exactly one home. Extracting types, enums, constants, and functions out of logic files keeps those files focused, makes decla… |
13-external-library-wrappers-and-adapters.md |
Third-party code touches ClawAI in exactly one place. |
14-shared-packages.md |
Six packages/shared-* workspaces hold everything used by two or more services. |
15-configuration-and-environment.md |
Configuration is read once, validated with Zod, and exposed through a typed AppConfig — never scraped from process.env at call sites. |
16-authentication-and-authorization.md |
Auth is uniform across every service: one JWT model, one guard stack, one permission catalog, one entitlement layer. |
17-rabbitmq-events-and-jobs.md |
Async cross-service communication runs on one topic exchange with one reliability contract. |
18-error-handling-and-reliability.md |
Errors are typed, logged, and surfaced — never swallowed, never left to spin. |
19-logging-observability-and-redaction.md |
Every request is traceable end-to-end and no log line ever leaks a secret. |
20-i18n-and-user-facing-messages.md |
Every string a user can see is translatable and actually translated into all nine locales. |
21-security-and-secrets.md |
Secrets stay server-side and encrypted; input is validated and bounded; every service ships the same hardening. |
22-testing-and-coverage.md |
Nothing ships untested. Unit tests are the floor; QA scripts, DB verification, and log inspection are the ceiling. Coverage is a proxy for "did you… |
23-git-commits-hooks-and-release-gates.md |
Quality gates run where they are cheap and correct: in the folder you touched. |
24-generated-files-and-knowledge-freshness.md |
The AI-native workflow depends on machine-readable facts staying true. |
33-knowledge-compounding-and-context-velocity.md |
ClawAI is production-grade and worked on by many people and many agents. |
34-gate-economy-and-machine-resources.md |
The gates in this repo are expensive by construction: 17 Prisma clients, 28 workspaces, thousands of tests. |
35-super-administrator-and-privilege-boundaries.md |
Protecting a row is half a privilege boundary; the other half is asking what the caller is allowed to do. |
36-floating-ui-and-toast-clearance.md |
Toasts stack from the same corner everything else floats in; a floating element declares itself and the clearance is measured, never hardcoded. |
37-payg-credit-integrity.md |
PAYG credit spends a customer's money before they see a result: overspend impossible by construction, every dollar attributable, margin inputs private. |
38-adsense-eligibility-and-low-value-content.md |
One authoritative, deny-by-default AdSense eligibility policy: script vs verification vs ad-unit gating, route boundary, chat-share review lockdown. |
39-worktree-branch-completion-pr-and-release-notes.md |
A task done in an agent-created worktree/branch ends with a PR and release notes, not just pushed commits. |
40-chat-surface-layout-and-composer.md |
On a conversation surface the transcript is the only element that grows; the composer is sized by its content in rows, never in pixels. |
41-web-evidence-truthfulness.md |
Never claim a web step that did not run, never stay silent about one that failed; a URL the user wrote is opened, not searched for. |
42-attachment-understanding.md |
A model gets the readable TEXT of an attachment or an honest reason it did not; content is bytes and extractedText is text, and they are never swapped. |
43-account-state-disclosure-and-transactional-email.md |
A refusal names a reason only after the caller has proved the account is theirs; every email to a human is sent in that account's language, and the renderer owns every tag. |
44-live-verification-before-done.md |
Green unit tests are not evidence the feature works; every batch is exercised against the running stack with curl AND a browser, and the observed outputs go in the report. |
45-display-currency-versus-settlement-currency.md |
A price shown and a price charged are different numbers under different policies; display FX fails open to USD and never reaches a gateway, an invoice, a refund or a wallet. |
46-token-quota-enforcement-and-window-integrity.md |
A quota measured after the fact is a receipt, not a limit: count the prompt first, clamp the output to what is left, enforce every window and let the tightest one win. |
47-client-bundle-weight-and-barrel-boundaries.md |
A barrel imported by client components may only re-export leaf modules; server components resolve registry/content data and pass it down as props. |
48-lint-and-test-only-what-changed.md |
Lint the FILES you changed, test the workspace you touched, and do not re-prove what the hooks are about to prove. |
49-qa-team-discipline-and-test-evidence.md |
Every change is walked through the whole QA team on the running stack, across the device matrix, and every claim ships with real, re-runnable evidence. |
50-agentic-research-loop-and-narration.md |
AUTO research: plan gate first, one URL detector, user links are opened, research runs after the POST, milestones are stored, and page-level crawl progress remains live-only. |
51-router-candidates-and-model-window-fit.md |
AUTO router candidates = admin-exposed chat models (health + plan filtered); hosted planner models call ollama.com; one shared context-window table; every prompt source fitted to the model window (ADR-100) |
52-every-schema-ships-a-migration.md |
A Prisma schema change ships a migration in the same commit; a first migration is a full init; enforced by tools/tests/prisma-migrations-present.test.mjs (file-generation had none and prod had no tables) |
53-coding-agent-release-rounds.md |
A coding-agent release is proven by live rounds against claw.local across every tool-capable connector model, not by gates; an assertion reads the workspace, never the run's own report (a run reported four tool calls and left an empty directory) |
54-evidence-and-completion-honesty.md |
A completion claim needs observable evidence; a lane you could not run is reported as not run; never weaken a check to pass it or claim a test passed without its output — restates rules 44/49's discipline as the report-honesty rule |
55-akinator-station-discipline.md |
Ask before assuming, audit claim vs code, declare the knowledge delta by path at plan time, same-batch knowledge, never guess on money/permissions/deletion/security/public contracts — ported from the Akinator method so its discipline applies with no plugin installed |
56-model-reasoning-never-in-the-answer.md |
Reasoning goes to LlmResponse.reasoning (the "Model reasoning" panel), never to content: read thinking/reasoning_content fields, <think> blocks and a BARE </think> (GLM); a buffered response is split once at the parser |
57-memory-and-context-pack-integrity.md |
Memories/pack items are stored whole (length-preserving masking, 250K limit, 4 MB body); type is updatable; chat gets packs from the owner-scoped for-chat route incl. USER-scope packs; large items are fitted by relevance chunks, never head-cut (ADR-127) |
58-auth-route-rate-limits.md |
Every public sign-in / sign-up route has a per-route Redis budget (login 10/15 min per IP+address, 30 per IP; register 5/h per IP, 3/h per address; ...) counted before any lookup, keys hashed, 429 + Retry-After, no lockout, fails open on Redis, nginx auth_routes backstop (ADR-147) |
These are NEVER acceptable. They block delivery unconditionally:
-
TypeScript error —
npm run typecheckmust exit 0 -
ESLint error —
npm run lintmust exit 0 -
Failing test —
npm run testmust exit 0 -
QA script not run — every feature needs
qa/test-<feature>.shpassing 0 failures -
Docs missing — every new service/feature needs docs in
docs/ -
Coverage going down — CI runs every suite with
--coverageand fails below the workspace floor, below the changed-lines target, or when any threshold is lowered; the numbers and the dated path to 92 % are in rules/22 rule 2 -
Public method missing logging — every method in
*.service.ts/*.manager.ts/*.adapter.ts/*.utility.ts/*.repository.tsMUST emitlogger.debugon entry andlogger.errorin everycatchblock -
Cross-service duplicate utility — if a utility lives identically in two or more services, it MUST be moved to
packages/shared-utilities/. Per-service copies are a delivery blocker.
How a change lands, what each hook runs and what CI adds — by change type — is one canonical section: rules/23. In short: commit and push through the hooks, run nothing else by hand, never bypass a hook (ADR-061).
"Done" means all phases complete, all tests green, all docs written, all QA evidence documented.
A feature is NOT done because:
- The code compiles
- The happy path works
- The PR passes CI
A feature IS done when:
- ✅ All TypeScript, ESLint, test, build checks pass
- ✅ QA script run with 0 failures
- ✅ DB writes verified via
psqlor mongo shell - ✅ Docker logs clean (no UnhandledPromiseRejection, no FATAL)
- ✅ Manual UI tested (golden path + empty + error + loading)
- ✅ Docs updated or created
- ✅ All 18 infra checklist items verified
-
.env.exampleupdated -
.envupdated -
scripts/install.shupdated -
scripts/install.ps1updated - ALL 7 Docker compose files updated
- i18n locale files (all 8) updated
- Architecture docs in
docs/updated - Prisma migrations created
- Seed files updated
- Test files created/updated (with ≥92 % coverage on the changed unit)
- Frontend types synced with backend DTOs
-
CLAUDE.mdupdated (root + per-service) -
.github/workflows/ci.ymlupdated -
infra/nginx/nginx.confupdated -
packages/shared-constantsupdated -
packages/shared-typesupdated -
apps/claw-health-serviceupdated -
apps/claw-frontendupdated -
packages/shared-utilitiesupdated (if the change adds a utility that two or more services need) - Logging audit (every public method in changed files emits debug/error)
-
CODEX.mdandcursor.mdupdated (mirror any new pattern/rule into all three LLM instruction files)
- This file (
rules/00-master-rules.md) - Root
CLAUDE.md - The specific rule file for the task domain
- Service-specific
CLAUDE.mdfor the service being touched - The relevant
docs/file for the feature area
When work arrives as a document — prompt pack, execution prompt, plan pack,
implementation brief — the intake protocol in
26-prompt-pack-intake-protocol.md runs first,
in full, regardless of how small or urgent the pack looks. Runbook:
../skills/execute-prompt-pack.md. Summary:
../context/prompt-pack-intake.md.
The two failures it exists to prevent: building what the pack literally says instead of what this repo needs (a second engine where a seam exists), and rebuilding what already shipped — packs are usually handed over mid-flight, so the deliverable is the remainder. Hence the non-negotiable middle steps: audit every deliverable against the code (done / partial / missing — and present is not wired), and review the constraint surface (ESLint, TypeScript, Prettier, coverage, security, i18n × 13, the delivery checklist, and every gate including pre-commit, pre-push and CI) before writing code rather than after.
Where a pack conflicts with repository policy, policy wins — and the deviation is stated explicitly in the plan, never applied silently.
.ai/**, every workspace AGENTS.md, the per-model routers and the inventory
snapshot are generated; the pre-commit hook regenerates and stages them, and CI
fails on a stale one. The rule, the fix for a red CI and the ordering trap live in
one place: rules/24.
-
Knowledge check —
npm run knowledge:coveragefails when a rule in this catalog is unreachable from an index, which is what keeps this file honest. - Review checklist — this file is an index, so its enforcement is that the rules it points at are themselves enforced.
- Every rule file in
rules/appears in this catalog or inrules/README.md. - Each entry's one-line description still matches the rule's Purpose.
|
59-chat-surfaces-are-one-pipeline.md| Every chat surface (Compare, Consensus, Escalation, Repair, Decompose, Best-of-N, Verifier, Pipeline, Cost-Ensemble, Role Pack, judge/critic) shares context + execution gateways, thread resolution, DTO fragments andsharedPayload; chat changes propagate everywhere; unavailable Judge results never render as verified (ADR-155/191) | |60-qa-evidence-is-mandatory-and-machine-checked.md| STRICT: no change is done without walking all 15 QA lanes (unit is only L01; manual API and manual browser are L03/L04) and recording evidence indocs/qa-evidence/<date>-<slug>.md; Verdict DONE only with no NOT_RUN/FAIL lane;tools/qa/evidence.mjs+ CI jobqa-evidenceenforce it (ADR-156) | |63-docs-move-with-code.md| NON-NEGOTIABLE: docs move with code — every doc a change makes stale is fixed in the same commit, every commit carries aDocs:trailer, anddocs:impact/docs:refs/ counts / duplication checks enforce it in the hooks and CI (ADR-170) |
ClawAI Wiki · source-controlled under wiki/ · generated/mirrored from the current repository knowledge layer.
ClawAI Wiki
Product
- Product-Vision
- Flagship-Features
- Business-Overview
- Requirements-Register
- Drift-Log
- Runtime-Managed-Connector-Providers
- Threads
- ADR-Index
Architecture
- System-at-a-Glance
- Architecture-Map
- System-Architecture
- Message-Flow
- End-to-End-Data-Flow
- Routing-Engine
- Event-Bus
- Security-Architecture
Platform
- Backend-Services
- Frontend-Architecture
- Shared-Packages
- Database-Reference
- API-Reference
- Provider-Catalog
- Memory-and-Context-Architecture
- File-Support-Architecture
- Research-and-Web-Crawling
Runtime & Ops
- Docker-Guide
- Nginx-Reference
- CI-CD-Pipeline
- Logging-and-Observability
- Operational-Runbooks
- Troubleshooting
Quality
Engineering OS
- AI-Native-Engineering-OS
- Generated-Manifests
- Rules-Catalog
- Skills-Catalog
- Context-Layer
- Engineering-Memory
- Tooling-and-Automation
- Scripts-and-Operations
- ESLint-and-Architecture-Enforcement
- Extended-Work-Skills
Agents
Reference