Skip to content

Master Rules

github-actions[bot] edited this page Oct 25, 2026 · 4 revisions

Canonical source: rules/00-master-rules.md — this page is rendered from it on every publish; edit the source.

ClawAI — Master Rules

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.

What This Folder Is

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.

Rule Files

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)

The 8 Absolute Blockers (updated 2026-04-26)

These are NEVER acceptable. They block delivery unconditionally:

  1. TypeScript error — npm run typecheck must exit 0
  2. ESLint error — npm run lint must exit 0
  3. Failing test — npm run test must exit 0
  4. QA script not run — every feature needs qa/test-<feature>.sh passing 0 failures
  5. Docs missing — every new service/feature needs docs in docs/
  6. Coverage going down — CI runs every suite with --coverage and 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
  7. Public method missing logging — every method in *.service.ts / *.manager.ts / *.adapter.ts / *.utility.ts / *.repository.ts MUST emit logger.debug on entry and logger.error in every catch block
  8. 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.

Landing a change

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

The Non-Negotiable Mandate

"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 psql or 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

Quick Reference: Delivery Checklist (21 items, updated 2026-04-26)

  1. .env.example updated
  2. .env updated
  3. scripts/install.sh updated
  4. scripts/install.ps1 updated
  5. ALL 7 Docker compose files updated
  6. i18n locale files (all 8) updated
  7. Architecture docs in docs/ updated
  8. Prisma migrations created
  9. Seed files updated
  10. Test files created/updated (with ≥92 % coverage on the changed unit)
  11. Frontend types synced with backend DTOs
  12. CLAUDE.md updated (root + per-service)
  13. .github/workflows/ci.yml updated
  14. infra/nginx/nginx.conf updated
  15. packages/shared-constants updated
  16. packages/shared-types updated
  17. apps/claw-health-service updated
  18. apps/claw-frontend updated
  19. packages/shared-utilities updated (if the change adds a utility that two or more services need)
  20. Logging audit (every public method in changed files emits debug/error)
  21. CODEX.md and cursor.md updated (mirror any new pattern/rule into all three LLM instruction files)

Reading Order for AI Agents

  1. This file (rules/00-master-rules.md)
  2. Root CLAUDE.md
  3. The specific rule file for the task domain
  4. Service-specific CLAUDE.md for the service being touched
  5. The relevant docs/ file for the feature area

Prompt packs and execution prompts (read BEFORE any code)

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.

Generated artifacts are a hard gate

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

Enforcement

  • Knowledge check — npm run knowledge:coverage fails 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.

Definition of done

  • Every rule file in rules/ appears in this catalog or in rules/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 and sharedPayload; 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 in docs/qa-evidence/<date>-<slug>.md; Verdict DONE only with no NOT_RUN/FAIL lane; tools/qa/evidence.mjs + CI job qa-evidence enforce 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 a Docs: trailer, and docs:impact / docs:refs / counts / duplication checks enforce it in the hooks and CI (ADR-170) |

Clone this wiki locally