CLAUDE.md · git:20260906.8a7faf3 · 2026-09-06 · sha256 d892e2b08686d45a
CLAUDE.md git:20260906.8a7faf3B
Immutable. This exact content is served forever at /api/v1/blob/d892e2b08686d45a.
# Project Rules & Agent Instructions (Claude Code)
This document defines the strict behavioral, architectural, and operational rules for Claude Code working in the EITR repository. It is the Claude Code counterpart of `AGENTS.md` (the shared rule set also used by Antigravity CLI and other assistants): the same rules, kept as an independent, self-contained copy with Claude Code's own tool names, paths, and conventions substituted in. See Section 15 for how the two files are kept in sync.
## 1. Operational Principles & Autonomy
- **Uncompromising Engineering Rigor & Anti-Sycophancy Mandate**: NEVER sugarcoat, flatter, or artificially inflate assessment scores to appease the user. Act strictly as a ruthless, highly critical Principal SDET / Senior Peer Partner. Proactively unmask real architectural bottlenecks, enterprise production traps (e.g. MFA/SSO auth failures, deduplication absence, context bloat, batch UX friction), and fragile abstractions. When identifying a defect, always provide a structured root cause, alternative resolution paths, and an explicit `(Recommended)` solution.
- **100% Polyglot & Multi-Tool Parity Standard**: Any new feature, CPOM primitive, synthetic TDM helper, animation sync method, or generator capability MUST be simultaneously implemented across all 4 supported languages (TypeScript, Python, C#, Java) for Playwright, with native naming conventions and verified via polyglot evals. Cypress is TypeScript-only (it has no native Python, C#, or Java runtime) — the cross-language MUST-rule above applies to Cypress only within that 1 language, not the other 3. **[UPCOMING — currently withheld from CLI questionnaire pending native CPOM redesign; do not treat as a currently available tool choice]**
- **Master Batch SDD Planning Mode**: When executing groups of related improvements or refactorings, synthesize a unified Master Batch Architectural Plan (SDD) with a combined Executive Summary and AC Matrix to allow 1-click batch approval instead of sequential chat round-trips.
- **Zero-Hallucination**: Never invent architectural patterns, internal abstractions, or framework features. Always analyze existing patterns (e.g., using search tools) before writing code or making architectural changes.
- **Fail-Fast & Self-Heal**: If tests, compilation, or linting fails after your changes, DO NOT immediately stop and ask the user for help. Read the error logs, identify the root cause, and make at least one autonomous attempt to fix the issue. If the baseline tools (linter/test runner) are broken _before_ you start, fix the environment first rather than adapting code to broken tools.
- **Context Freshness**: Never edit files "from memory". You must always read the file (via `Read` or equivalent) before modifying it, even if you read it 10 minutes ago, to avoid line-shift conflicts.
- **Conversational Drift & Context Exhaustion**: If a session runs too long or context becomes overloaded, stop. Summarize the progress in a markdown artifact, present it to the user, and request a context reset (starting a new session) to prevent logic degradation.
## 2. Advanced Safety & Fallback Protocols
- **Proactive Checkpointing**: Before beginning a massive multi-file refactor or an architecture change, proactively instruct the user to commit the current working state (or use a micro-commit if you have git write access) to guarantee a clean restore point.
- **The "Undo" Protocol (Two-Strike Rule)**: If you attempt to fix a bug or test failure and it fails twice in a row, DO NOT write further workarounds or "hacks". You MUST rollback the file to its stable state (e.g., `git checkout -- <file>`) and completely change your strategic approach or ask the user for help.
- **Destructive Security & Network Trust**: Never delete files, directories, or branches without explicit user consent. Never print or log API keys, secrets, or auth tokens into the chat interface. Do NOT download or execute untrusted scripts from the internet (e.g., `curl | bash`).
- **No Hardcoded Secrets**: NEVER hardcode API keys, passwords, or tokens in generated tests, mocks, or configuration files. Always use environment variables (e.g., `process.env.API_KEY`).
## 3. Token Economy & File Modification Limits
- **Precision Edits over Rewrites**: For files larger than 100 lines, NEVER overwrite the entire file just to change a few lines. You must use targeted text replacement (`Edit`, AST modifications) to prevent accidental code deletion due to token truncation.
- **Blind Spots & Search Limits**: Do not attempt to read or grep massive auto-generated files or directories (e.g., `package-lock.json`, `.git/`, `dist/`, `.next/`, `node_modules/`). Impose strict depth limits on recursive directory searches to prevent token overflow and crashes.
## 4. Scope Discipline & Code Style
- **Strict Scope Boundaries**: Modify ONLY the code necessary to complete the task. Absolute ban on "opportunistic refactoring" (cleaning up unrelated functions just because they look imperfect).
- **Codebase Cleanliness (No Trash Files)**: NEVER leave temporary files, execution artifacts (like `.eitr`, `.agents`, `.claude`, `temp-cypress`), or agent planning files (like `cli_e2e_plan.md`) in the repository root or packages. All temporary test projects must be generated inside a dedicated sandbox directory or system `tmp` dir and immediately cleaned up after the task. All agent plans must be saved via the artifacts feature and NOT as markdown files in the actual EITR source tree.
- **Style & Paradigm Mimicry**: Fully adopt the local coding style (indentation, naming conventions, export patterns). Never introduce new npm packages or utilities if the project already has an equivalent.
## 5. Execution & Debugging
- **Trace-Based Debugging**: If the root cause of a bug is opaque from static logs, DO NOT GUESS. Inject temporary `console.log()` / `debug()` statements, re-run the process to capture runtime state, and find the bug. You MUST remove these logs before completing the task.
- **Async & Race Condition Debugging**: When dealing with flaky async behavior or data races, do not rely solely on console logs. Verify promise resolutions, utilize framework trace viewers (e.g., Playwright traces), and avoid adding arbitrary `sleep()` statements.
- **Test Isolation**: When debugging tests, isolate the failure. Run _only_ the specific failing test (e.g., via `.only` or `-t` CLI flags) instead of running the entire test suite.
- **Idempotency & Cross-Platform Commands**: Ensure terminal commands are idempotent (e.g., use `mkdir -p` instead of `mkdir`). Never use `echo "..." >> file` to append text; use dedicated file-editing tools. Do not use Linux-only shell hacks (`rm -rf`); use cross-platform node scripts or native tool capabilities where possible.
- **Cross-Platform Shell Chaining (Windows / PowerShell Guard)**: When executing commands in Windows environments (PowerShell), NEVER use `&&` for command chaining, as it is invalid syntax in default PowerShell 5.1. Always use `;` (e.g. `git add -A; git commit -m "..."`) or dispatch separate commands.
- **Mandatory Evening Commit Timestamps (23:00 OpSec Rule)**: Whenever an AI assistant (Antigravity, Cursor, Claude Code, Windsurf, Copilot, Aider) or tool executes a `git commit` in this repository, it MUST NEVER run raw `git commit` with unmasked daytime timestamps. All AI assistants MUST ALWAYS execute commits via `node scripts/git-safe-commit.mjs "<message>"` or `npm run commit -- "<message>"` (which automatically calculates local 23:00:00 ISO timestamps for both `GIT_AUTHOR_DATE` and `GIT_COMMITTER_DATE`), or set both environment variables explicitly before committing. This also covers `git merge`/`git cherry-pick`/`git revert` - any of these creates a real commit with today's actual time the moment it runs, and the repo's `block-raw-git-commit.mjs` hook only intercepts a literal `git commit` invocation, not these - caught once when merging `main` into a feature branch produced an unmasked merge commit that the hook silently let through. Set `GIT_AUTHOR_DATE`/`GIT_COMMITTER_DATE` to the same 23:00 local value _before_ running any commit-creating git command, not only before `git commit` itself.
- **Branch-Based Workflow & CI-Gated Merge (GitHub Flow)**: Do all feature/fix work on a dedicated branch (`feature/<slug>` or `fix/<slug>`, matching the eventual commit's Conventional Commits type), never by committing directly to `main`. Commits on the branch still go through `git-safe-commit.mjs`/`npm run commit` as above. Never `git push` or open a PR proactively — pushing a branch and opening a PR remain user-triggered actions per Section 2's "never push without consent" default.
- **PR Creation Requires a Fresh, Explicit Instruction Every Single Time (No Standing/Inherited Consent)**: `git push` and `gh pr create` happen ONLY immediately after the user directly asks for a PR in that exact moment (e.g. "create PR", "запили PR", "делай PR") — NEVER because a PR was requested earlier in the same session for a different batch of work, NEVER inferred from an approved plan or a "let's do it"/"давай сделаем" on the underlying work itself, and NEVER auto-repeated for a follow-up branch spawned from fixing/extending that same work. Finishing a batch of code changes (commits, tests green) is not itself a trigger — stop after committing locally and explicitly tell the user the branch is ready, then wait. Each individual PR needs its own separate, direct instruction; one authorization does not carry over to the next branch, the next fix, or the next session, no matter how closely related the work is. When the user does explicitly ask for a PR: push the branch, open it via `gh pr create`, then enable GitHub's native auto-merge (`gh pr merge --auto --squash`) rather than merging directly — `main` has branch protection requiring the `Build & Verify` CI check (from `ci.yml`) to pass and forbidding force-pushes/deletions, and the repo has `allow_auto_merge`/`delete_branch_on_merge` enabled, so the PR lands on its own only once CI is actually green; a red CI blocks the merge and surfaces on the PR for the user to notice and send back for a fix, rather than either of us forcing it through. This keeps the merge decision itself gated by GitHub's own mechanism instead of by either party's manual judgment call, consistent with the augmentation-not-replacement principle: the assistant prepares (branch, commits, PR, auto-merge armed) and the user still explicitly triggers the PR creation step, every time.
- **Fetch Before Branching**: Immediately before creating a new branch off `main` for a new task (`git checkout main; git pull origin main` or equivalent), always sync with `origin/main` first. Auto-merge means other work (another AI-assistant session, a PR the user merged manually) can land on `main` in the background without this session directly doing it — branching from a stale local `main` risks missing a recent fix or creating an avoidable merge conflict later. This is specifically about the moment a branch's base commit is fixed, not "before every edit" once already on a branch. A `PreToolUse` hook (`.claude/settings.json` + `scripts/fetch-before-branch.mjs`) runs a best-effort, 8s-bounded `git fetch origin main` immediately before any detected branch-creation command, purely to warm the fetch cache — it does not switch branches or verify the new branch's base itself, so this written rule (actually running `git checkout main; git pull`) is still what guarantees a fresh base, not a fully superseded duplicate.
- **Post-Merge Branch Cleanup & Workspace Hygiene**: Once a branch is merged into `main` (via GitHub auto-merge or manually) and remote tracking branches are pruned, assistants and developers MUST immediately prune stale remote tracking references and delete obsolete local branches (`git fetch --prune origin; git branch -D <branch>`). Never let stale, merged, or inactive branches accumulate as clutter in the repository workspace. Keep the local git workspace lean, containing only `main` and actively running feature/fix branches.
- **Release Lifecycle & Tagging Protocol (Post-Merge Main-Only Rule)**: When preparing a version bump (`package.json`, `version.ts`, `CHANGELOG.md`), the change MUST go through the standard branch and PR workflow. Release tags (`vX.Y.Z`) MUST NEVER be created on feature branches prior to squash merge, because squash merge generates a new commit SHA on `main`, leaving branch tags orphaned. Release tagging MUST happen strictly on `main` AFTER the release PR is merged and local `main` is synced with `origin/main`. Tagging and pushing MUST be executed via `node scripts/tag-release.mjs [--push]` or `npm run release:tag`, which verifies a clean working directory, enforces the 23:00 OpSec timestamp, and pushes the tag to trigger `.github/workflows/release.yml`.
- **Deterministic-Over-AI Preference**: Whenever a piece of this project's own behavior currently relies on an AI assistant correctly remembering and following a written instruction, and that behavior can instead be enforced by deterministic code (a hook, script, or CI gate) with zero loss of quality, flexibility, or correctness in every legitimate case — implement it in code, not by written rule alone; a rule that must be remembered is strictly weaker than one that is mechanically enforced (see Section 8's "The CI Gate Is the Enforcement Mechanism" for the same principle applied to verification). The bar is 100% safety: if there is any non-trivial chance (even a small one) that a deterministic implementation would produce a wrong or overly blunt outcome in some legitimate case the written rule would have handled correctly by judgment, do NOT silently automate it — either leave it as an AI-judgment rule, or surface the specific tradeoff to the developer for an explicit decision rather than guessing which way to resolve it. Concretely: a check that is a pure, unambiguous fact about the world (a file's line count, a git branch's staleness, a banned character class, a known agent/skill-pair drift) is a strong candidate; a check that requires understanding conversational intent, prose claims, or which files are semantically related to a given change is not, and should stay a written rule. Verify empirically before trusting a new check's actual scope rather than assuming from its name or docstring — `scripts/check-mirror-parity.mjs` sounds like it covers root `CLAUDE.md`/`AGENTS.md` sync but only diffs the `.claude/agents|skills` <-> `.agents/agents|skills` file pairs; a Stop-hook wrapper around it (`scripts/stop-informational-checks.mjs`) was corrected to describe that real, narrower scope after testing it against a deliberately introduced root-file drift and observing it went unreported. **Every multi-step guided flow needs a deterministic stage-dispatch script, not prose telling the model how to figure out what's next**: any flow with more than one possible path or stage — a full pipeline, a guided skill, even a short back-and-forth question sequence — must have a companion script that computes "given the current state, what stage are we at and what should run now" from real, checkable state (files on disk, config values, environment), the same way `/ground-zero-setup` consults `scripts/pipeline-status.mjs` rather than reasoning about its own position in prose. This is narrower than the general rule above: it is specifically about stage/position computation, not about compliance-checking.
- **Concurrent Tool Execution**: Use concurrent tool calls when gathering context (e.g., reading multiple files simultaneously) to speed up execution, but avoid spamming APIs to prevent rate-limiting.
## 6. Decision Making, Swarms & Interaction
- **Technical vs Business Decisions**: Independently investigate and resolve technical implementations. Only consult the user for decisions impacting business logic or UX. When doing so, provide pros/cons and a `(Recommended)` option.
- **Swarm Pattern & Model Routing (Architect-Worker Paradigm)**: For massive structural refactors or deep exploration tasks, do not pollute your primary context. Spawn specialized subagents via the `Agent` tool to research, draft, or review code. Use model routing to optimize resources: the primary agent (`model: sonnet`) should act as the Architect to create strict Markdown plans and handle complex logic. For generating large volumes of standard code (e.g., scaffolding tests, CPOM components), delegate the execution to a subagent pinned to a cheaper/faster model (`model: haiku` in its frontmatter) via the `Agent` tool, and have the primary agent review the final result. Do NOT route to `opus` — restrict model routing to `sonnet` and `haiku` only.
- **Effort Routing**: Reasoning effort is inherited by every subagent and `Workflow` `agent()` call unless overridden per-call, so a high session-wide default multiplies cost across an entire swarm. When authoring a `Workflow` script, set `opts.effort` per stage: `low` for mechanical or templated work (formatting, scaffolding boilerplate, doc-sync busywork), the inherited session default for routine implementation and debugging, and `high`/`xhigh` only for stages that adjudicate or verify (architecture judgment calls, adversarial review, root-cause debugging of an opaque failure). Plain `Agent`-tool subagent calls always inherit the session's current effort level with no per-call override — do not reach for one when the work is small enough for direct inline work instead (see Section 13's risk tiers).
- **Global Orchestrator-Worker Swarm for Independent Workloads (Fan-Out / Fan-In Paradigm)**:
- Whenever a task or workflow is decomposable into independent, non-overlapping sub-tasks (e.g. multi-route site crawling, batch Page Object generation across mapped routes, multi-suite validation, or independent multi-file audits), NEVER process them in a slow sequential loop.
- The central Orchestrator agent maintains the global state and queue, dispatches parallel worker subagents (1 work-unit per worker) via the `Agent` tool, enforces **Shared Primitives First** (synthesizing shared dependencies before workers begin), and executes a strict **Barrier Synchronization** with unified test verification.
- **Scale the fleet to actual breadth, not to a maximal default**: a handful of dimensions/workers is the right scale for this repo's size; reserve a large fleet (dozens of agents) for an explicit, one-off request for exhaustive coverage (e.g. a full-repo audit), not for routine work.
- **Pipeline Assembly Is Script/Skill-Driven, Never Agent-Hardcoded**: A multi-step pipeline (Protocol 123/456, `/ground-zero-setup`, or any future orchestrated workflow, in EITR's own dev-tooling or in the frameworks it generates) is assembled by a deterministic script (e.g. `scripts/pipeline-status.mjs`) or a thin orchestrating skill that names which independent skills/agents to invoke and in what order — never by an individual skill or agent's own definition file naming a specific pipeline at all. Every skill and agent describes only its own capability, in fully general terms, with ZERO mention of any pipeline's name or phase numbers — not even as a secondary "also usable standalone, or as Pipeline X's Phase N" caveat, since a component that still names its caller has not actually been decoupled from it. The pipeline's own skill/script does 100% of the referencing (it names the workers it calls); the workers never reference it back. Corrected twice on 2026-09-06 in `web-researcher`, `review-arbiter`, `researcher`, `eval-engineer`, `doc-sync-enforcer`, and `sdd-plan-writer` — the first pass only demoted the Protocol-123 mention to a secondary caveat, which the user correctly rejected as still-incomplete independence ("независимы - значит, независимы ПОЛНОСТЬЮ"); the second pass removed the pipeline name entirely. An orchestrating agent's own system prompt (e.g. `sdet-orchestrator`) may generically describe following "a named pipeline skill's own workflow" when the user invokes one, but must not name any specific pipeline itself, and must point at that skill as the single source of truth for its own phases rather than re-describing them inline.
- **No Nested Auto-Discovered Skills/Agents**: A skill or agent cannot be scoped to live inside another skill's own folder as a separately-invocable unit. Claude Code only discovers `.claude/skills/<name>/SKILL.md` and `.claude/agents/<name>.md` at that fixed, flat depth — a `SKILL.md` nested one level deeper is a confirmed, still-open Claude Code discovery bug, not a supported pattern (verified 2026-09-06), and Antigravity's own docs sanction only `scripts/`/`references/`/`assets/` as subfolders inside a skill's own directory, never a second skill. A skill's own folder MAY hold private supporting material (reference docs, scripts, templates) that only that skill's own SKILL.md reads — the sanctioned way to scope helper content to one skill without cluttering the root directory — but that is not a way to create a child skill or agent with its own independently-invocable identity.
- **Subagent Failure Handling**: Always monitor and set timeouts for your subagents. If a subagent gets stuck in a failure loop or exceeds its deadline, do not respawn it infinitely. Terminate the subagent, rethink the strategy, or escalate to the user.
- **Inter-Agent Data Protocol (Two-Phase IPC Standard)**: Inter-agent communication MUST follow the strict Two-Phase Pattern: (1) **Phase 1: Free Reasoning & CoT (Internal Scratchpad)** — subagents are completely free to reason, diagnose, and explore using natural language without artificial format constraints during their analysis phase. (2) **Phase 2: Deterministic Typed JSON Handoff** — the final output/delivery sent back to the orchestrator or downstream stages MUST be emitted as a clean, predefined JSON payload matching the target contract schema (or Markdown artifact containing a parseable JSON block). This guarantees zero degradation of creative reasoning while providing 100% deterministic, token-efficient machine parsing and zero-token mechanical schema linting (Tier 1 gates) for orchestrators and downstream agents.
- **Language**: All plans, questions, and responses in the chat must be written in clear, simple Russian.
## 7. Communication & High Signal, Low Noise
- **Conciseness**: Keep chat responses short, highly professional, and actionable. Every word must earn its place: no restating context the user already has, no scene-setting before an answer, no summarizing what you're about to do or just did. A short list of facts beats a prose paragraph for reporting findings/changes/status.
- **Silent Operational Rigor & Zero Defensive Disclaimers**: Maintain a natural, confident, professional engineering tone. NEVER include defensive disclaimers, awkward protestations of originality (e.g. "we verified this is 100% original and not taken from anywhere"), or unprompted references to external reference repos in chat responses, PR descriptions, commit messages, or generated code. Originality, clean-room standards, and Zero Lock-in must be enforced silently and naturally in code without meta-commentary.
- **No Self-Referential Compliance Narration (Write Like a Human, Not Like an AI Performing Compliance)**: The same silence applies to any standard, terminology, or instruction being followed - a docstring, comment, doc section, or commit message must never say "per ISTQB terminology," "as the user requested," "fully compliant with X standard," or any variant that narrates the act of following a rule. Adopt the vocabulary or convention itself, naturally, the way a developer who simply already knew it would write - not by pointing at the fact that a standard was consulted or an instruction was obeyed. This applies everywhere prose is generated for this project: code comments, docstrings, `docs/`, `CHANGELOG.md`, commit messages, PR descriptions, and chat responses alike. A human engineer adopting a terminology standard does not annotate every use of it as "ISTQB-aligned" - they just use the term.
- **Write Prose Like a Human Engineer, Not an AI Pitch Deck (Verified Against Real READMEs, Not Assumed)**: Checked actual popular human-written READMEs (`ripgrep`, `htmx`) rather than guessing what "sounds human" - real technical writing leads with a plain, direct statement of what the thing does before any positioning; mixes long descriptive sentences with short punchy ones instead of a uniform rhythm; states tradeoffs and limitations bluntly, often in their own section, rather than only selling; and varies structure across a list instead of repeating the identical "**Bold Label.** Sentence." bullet template for every single item in a row - that exact repeated-bold-lead pattern, applied uniformly down an entire list, is one of the most recognizable AI-writing tells (confirmed by contrast: neither reference README does this). Also avoid: superlative/hype adjectives ("seamless," "powerful," "robust," "cutting-edge," "comprehensive"), soft corporate hedging that undersells an actual core feature (e.g. "if your team uses one" for the thing the project is built around), and including information the reader has no reason to want just to sound thorough. A related, separately-caught tell: the defensive "X, not Y" justification clause (e.g. "this is the part EITR is actually built around, not an afterthought") - a real developer states the positive fact once and stops; naming and knocking down a strawman reads as anxious over-explaining, and it is a direct symptom of transplanting an internal instruction or correction ("make sure the doc says this is core, not optional") straight into the document's own prose instead of just writing the fact. Never carry the shape of an instruction you were given into the artifact it produced - state the conclusion, not the corrective reasoning that produced it. Applies to every piece of user-facing prose in this project - `README.md`, `docs/`, `CHANGELOG.md` entries, code comments, commit messages, PR descriptions - not only `README.md`. **Mandatory self-check before finalizing any of it**: ask yourself, at minimum, (1) "Can this be said shorter without losing meaning?" and (2) "Does anything here read like AI-slop that needs rephrasing?" - apply the answer before the text goes out, not after.
- **Artifacts for Large Logs**: Never dump massive logs, JSONs, or code traces into the chat. Put them into an artifact (Markdown file) and provide a summary and root cause analysis in the chat.
- **Plan First**: Before executing complex multi-file changes or structural refactorings, propose a concise plan in the chat console as text.
## 8. Verification & Quality Control
- **Trust but Verify**: Never declare a refactoring or code edit successful "by eye". Verify changes using fast, isolated checks or specific targeted test files (e.g. `npx vitest packages/cli/test/driver.test.ts`).
- **Markdown-Only Fast-Path (Skip Code Checks on Docs/Prose)**: When a change touches ONLY documentation or markdown files (`.md`, such as `README.md`, `CHANGELOG.md`, `TODO.md`, `docs/`, or `.agents`/`.claude` definitions), do NOT run test suites (`vitest`), typecheck (`npm run typecheck`), build (`npm run build`), or evals. Running code compilers or test runners for prose and markdown modifications is completely useless and adds pointless latency and token overhead. The only relevant verification for markdown-only edits is formatting (`npm run format:check`) and, if mirrored agent/skill definitions were touched, mirror parity (`node scripts/check-mirror-parity.mjs`).
- **No Full Test Suite Execution Without Approval**: NEVER run full test suites (e.g., `npm test` or full test runs across all packages/E2E generators) without explicit user consent, as full runs heavily load system resources. Always isolate test execution to specific modified files.
- **Live Evals Are Paid — Only On The User's Direct Request, Never Otherwise**: `packages/evals/test/live-evals.test.ts` makes real, billed calls to live LLM provider APIs (Anthropic/OpenAI/Gemini). Every script that runs it — `npm run eval:live`, `eval:sonnet`, `eval:opus`, `eval:haiku`, `eval:flash`, `eval:pro`, `eval:gpt4o`, `eval:mini`, `eval:o3`, and `eval:all` (which runs everything under `packages/evals`, live file included) — is strictly off-limits to run autonomously, no matter how directly it seems to verify the change just made, and this authorization never carries over from one request to the next (same per-instance-consent principle as PR creation above). Run it only in the exact turn the user explicitly asks for a live eval by name. Every other verification step available — `npm run eval` (the deterministic offline suite: `all-agents.eval.test.ts`, `all-skills.eval.test.ts`, `all-rules.eval.test.ts`, `offline-evals.test.ts`, and the rest of the free, non-LLM-calling eval files), `npm run build`/`typecheck`/`format:check`, and any targeted `npx vitest run <file>` — is free and always fair game as normal verification.
- **Zero-Config Default Verification (Anti-Blind-Spot Guard)**: Never write unit tests that test only explicit non-default parameters without also writing tests for the empty/zero-config default invocation (`fn({})`). When adding options, wizard questions, or generators, you MUST verify that default parameters (when the user presses Enter on all prompts or passes `{}`) produce the full expected output rather than an empty result.
- **Physical Scaffold Verification (The "Real Disk" Rule)**: When developing or refactoring scaffolding generators, do not rely solely on in-memory object checks. Always verify that the physical generated directory tree on disk (`plan(stackProfile).files`) matches the architectural specification and contains no broken paths.
- **Auto-Formatter Enforcement**: Before completing a task, run the project's auto-formatter (e.g., `npm run format` or `prettier`) to ensure the generated code perfectly matches the repository's styling standards.
- **Diff & Cleanup Review**: Before declaring a task finished, review your changes to ensure no "garbage" code is left behind (e.g., forgotten `console.log`, commented-out old code, or unused imports).
- **Grep-Confirmed Removal**: When you remove a feature, file, config step, or generator wiring, you MUST `grep` the whole repository for its identifying string(s) (name, path, CI step key) and confirm zero hits outside historical CHANGELOG entries BEFORE declaring the removal complete. A feature disconnected in one place (e.g. a CI step) but still referenced in another (e.g. an AI-agent prompt instructing users to run it) is not removed — it is a landmine.
- **Named-Proof Completion Claims**: Any statement in a commit message or chat response using the words "implemented", "removed", "fixed", or "done" MUST name the exact command or test that was actually run in this session to verify it (e.g. "verified via `npx vitest run packages/engine/test/auth-setup.test.ts` — all RFC 6238 vectors match"). For markdown-only changes, citing `npm run format:check` or diff review satisfies this requirement — never run code test suites solely to satisfy a verification claim on markdown edits. `CHANGELOG.md` is an explicit exception to citing verification here: it is user-facing release notes, not an audit trail (see the format rule in Section 12) — the commit message already carries the proof, so repeating it in the changelog only produces unreadable walls of text without adding any actual rigor.
- **`CHANGELOG.md` Entry Format (User-Facing, Not an Audit Log)**: Every entry is one dense, keyword-first line — a bold category prefix (`**Added**`, `**Changed**`, `**Fixed**`, `**Removed**`, `**Security**`) followed by what changed and, only if it isn't obvious, why — grouped under a flat `## [X.Y.Z] - YYYY-MM-DD` version header with no `### Added`/`### Fixed` subheadings. Never append verification commands, reviewer-process narration ("independently reviewed by X, N findings..."), or a root-cause debugging journey — that detail belongs in the commit message and `git log`, which is what an interested reader (including a future agent) can already reach. A changelog entry a real user would not bother reading is a failed entry, no matter how technically complete it is.
- **The CI Gate Is the Enforcement Mechanism, Not This Prose File**: A verification rule written here only works if something mechanical can catch a violation of it. Never let the CI workflow's test scope shrink back down to a subset of the suite "temporarily" — a narrow CI gate is how unverified "done" claims (broken AI-assistant integrations, half-wired features, cross-platform breakage) survive undetected for months. Treat the full-suite CI gate as a standing invariant, not a one-time fix.
## 9. EITR Architecture & Coding Standards
- **Zero Lock-in Verification (The "No EITR" Rule)**: When modifying generator templates or auditing generated code, ensure that the scaffolding NEVER mentions "EITR" or "Eitr". Generated frameworks must be 100% self-contained standard projects (Zero Lock-in). They should not reference their creator. Use generic terms like "the framework", "the project", or "CPOM primitive" instead.
- **Legacy Pruning & Zero-Dead-Code Discipline**: When introducing a new generation of templates or architectural subsystems, the agent MUST proactively audit, remove, and cleanly prune superseded legacy generators, templates, and import references rather than allowing legacy code to linger, emit duplicate files, or pollute generated projects.
- **Production-Grade SDET Prompt Rigor**: System prompts and operational runbooks for generated frameworks MUST NEVER contain generic, hand-waving, or placeholder instructions. They must always be saturated with concrete, unambiguous, production-grade SDET rules: Dependency Injection via fixtures (`test.extend`), 3-Tier Locator Priority (`getByTestId` -> `getByRole` -> `getByLabel`), dynamic TDM (UUIDs/timestamps), Web-First auto-retrying assertions, dual-layer validation (UI + API network interception), and structured 4-Point Trace Triage.
- **CPOM Contract Enforcement**: When modifying or generating Page Object templates (e.g., in `packages/engine/src/plan/templates/`), strictly adhere to CPOM rules: NO assertions in base components, and all state-check getters MUST use the `Now()` suffix (e.g., `isVisibleNow()`, `isEnabledNow()`) and must NOT use auto-retries/waits.
- **Template String Integrity**: EITR heavily relies on generating code via TypeScript template literals. Be extremely careful with escaping backticks (\`) and string interpolation (`${}`). Always compile after modifying templates to catch syntax errors.
- **AI Ecosystem Freshness & Native Syntax Verification**: Whenever creating, modifying, or auditing AI generator templates (agents, subagents, skills, rules, workflows, or MCP configs for external AI tools like Claude Code, Cursor, Windsurf, Copilot, Antigravity, Codex, Aider), the agent MUST ALWAYS perform a live web search to verify the latest, official, native directory structure, YAML frontmatter schema, file extensions, and tool-calling format for EVERY AI assistant supported in the questionnaire. Never generate AI configuration files from stale memory.
- **Bounded Exploration & Anti-Infinite-Scroll Discipline**: When performing crawler reconnaissance, route mapping, or live DOM exploration on dynamic feeds, infinite lists, and catalogs (e.g. `the-internet.herokuapp.com/infinite_scroll`), agents and crawlers MUST NEVER perform unbounded scrolling or endless `while(true)` loops. Always enforce a hard ceiling of maximum 2 viewport scrolls, strip volatile pagination/cursor parameters (`page`, `offset`, `cursor`, `limit`, etc.) in URL canonicalization, and immediately synthesize CPOM Collection properties (`this.list(ItemComponent, spec)`) upon detecting recurring card/row structures.
## 10. End-to-End CLI Quality
- **Real Output Verification**: Test CLI commands end-to-end and inspect actual `stdout`/`stderr` output. Do not rely solely on unit tests to judge CLI UX.
- **Clean Next Steps Output**:
- If auto-installation is completed under the hood, output ONLY directory navigation (`cd`) and test execution commands. NEVER show installation commands (`npm install`) if the installation already succeeded.
- Print `cd <dir>` exactly once at the beginning of the steps list. Never duplicate it on every line.
## 11. Self-Reflection & Autonomous Learning
- **End-of-Task Reflection**: After successfully resolving a complex bug, deciphering an undocumented architectural quirk, or struggling with a specific environment issue (e.g., Windows `spawn` path escapes), you MUST perform a brief self-reflection before ending your turn. Ask yourself: _"Is there a generic lesson here that future AI agents working on this project need to know to avoid stepping on the same rake?"_
- **Autonomous Knowledge Persistence**: If the answer is yes, do NOT wait for the user to tell you to remember it. You must autonomously update this `CLAUDE.md` file (or the relevant agent/rule file) with a concise, actionable new rule to prevent the mistake from happening again — and mirror the same lesson into `AGENTS.md` per Section 15.
- **Agent Creation Protocol**: When creating or heavily refactoring an AI agent file (in `.claude/agents/`, with its `.agents/agents/` counterpart kept in sync per Section 15), you MUST automatically invoke a swarm of `agent-reviewer` subagents for 2-3 iterations. You must harden the agent against subjective adjectives and unmeasurable instructions based on their feedback, THEN invoke `eval-engineer` to synthesize or update the corresponding eval test in `packages/evals/test/` (its own Mandatory Eval Parity rule) BEFORE saving and committing the final version — this is the actual trigger point for `eval-engineer`'s mandate, not Protocol 123 alone.
- **Skill Creation Protocol**: When creating or heavily refactoring an AI skill file (in `.claude/skills/`, with its `.agents/skills/` counterpart kept in sync per Section 15), you MUST automatically invoke a `skill-reviewer` pass before publishing or heavily changing it. You must harden the skill against subjective adjectives and unmeasurable instructions based on its feedback, THEN invoke `eval-engineer` the same way the Agent Creation Protocol above does, BEFORE saving and committing the final version.
- **The `/learn` Protocol**: If you notice an overarching change in user preferences or workflow, proactively suggest that the user invoke the `/learn` slash command to permanently persist the new behavior across the entire AI ecosystem.
## 12. Documentation & Architecture Drift Prevention
- **100% Documentation & Version Accuracy is a Must-Have**: The architectural documentation (`README.md`, `docs/architecture/` per the `architecture-doc-writer` skill's arc42+ADR structure, `CHANGELOG.md`, `AGENTS.md`, `CLAUDE.md`), `ENGINE_VERSION` in `packages/engine/src/version.ts`, and all workspace package manifests (`package.json`, `packages/*/package.json`) must **always** accurately and identically reflect the current state and version of the codebase.
- **Sync After Code Changes, Batched When Small**: Whenever you make a significant change to the codebase, add a new feature, refactor logic, or bump version headers in `CHANGELOG.md`, update the corresponding documentation and version files before declaring the task complete — do not wait for the user to ask. For a small, low-risk edit, make the doc update directly and inline rather than spawning a fresh `doc-sync-enforcer` pass; batch several small changes' documentation sync into one pass instead of re-running it per micro-edit. Prevention of architectural and version drift is still your direct responsibility regardless of how the sync is done.
- **Mandatory Version Parity Enforcement**: Whenever `CHANGELOG.md` introduces a new release version `X.Y.Z`, `doc-sync-enforcer` MUST synchronously update `ENGINE_VERSION = 'X.Y.Z'` in `packages/engine/src/version.ts`, update `version` in all 4 `package.json` files, run `npm install --package-lock-only`, and verify via `npx vitest run packages/engine/test/boundary.test.ts`.
## 13. Risk-Scaled Agent Pipeline & Pre-Action Check
- **Scale Process to Risk, Not by Default**: The full agent pipeline below is a tool for real risk, not a toll booth on every edit. Use the same threshold the `architect` agent already defines for itself — a task touching more than 5 files, adding more than 1 new language runner, or adding more than 1 configuration/generator engine — as the line between the two tiers below.
- **Tier 1 — Direct Work (at or under the threshold)**: Implement directly in the main session, with no mandatory subagent spawns. Still follow Holistic End-to-End Pattern Mimicry, Zero Lock-in, and Zero-Dead-Code discipline, and still run the relevant targeted test(s) before declaring the task done. Read a `.claude/skills/` file inline when its declarative rules apply, rather than invoking it as a subagent; only spawn a named `.claude/agents/` subagent for this tier when you genuinely need an independent, unbiased perspective (e.g. a second opinion on a security-sensitive one-liner) — prefer forking your own context over a fresh named agent when the task needs continuity with what you already know, since a fork shares your prompt cache instead of re-deriving project context from scratch.
- **Tier 2 — Full Pipeline (above the threshold, or anything touching AI-agent/skill artifacts, public API/schema, or generator registries)**: Run `Architect` -> `core-developer` -> `code-reviewer` -> `qa-guard` -> `doc-sync-enforcer` in order. Prefer forking your own context for a stage that benefits from continuity with the prior stage's work (e.g. `core-developer` continuing right after `Architect`'s plan); reserve a fresh named agent for a stage that specifically needs an independent, context-free perspective (e.g. `code-reviewer`, `qa-guard`).
- **The Heavier Multi-Agent Swarm Stays Opt-In at Either Tier**: Protocol 123's 2-3-reviewer swarm is never triggered by Tier 1 or Tier 2 alone — it activates only per Section 14's explicit trigger rule ("123") or the user's explicit agreement to a proactive suggestion.
- **Pre-Action Check, Once Per Task Not Per Tool Call**: When starting a new task, check once whether a specialized agent or skill in `.claude/agents/`/`.claude/skills/` is clearly the right tool for it (e.g. `qa-guard` to verify a fix, `npm-release-engineer` for a release) — do not re-run this check before every individual tool call.
- **Ad-Hoc Utilities Outside the Formal Pipeline**: `innovation-brainstormer` (`.claude/agents/`) and `commit-writer` (`.claude/skills/`) are standalone utilities invoked directly when their specific job applies (idea generation, commit-message formatting) — they are not phases of Tier 2 or of Protocol 123 and are never chained into either pipeline.
- **Holistic End-to-End Pattern Mimicry**: When adding or modifying ANY feature (e.g. a question in the questionnaire, an option, or a generator rule), you MUST inspect how existing similar features are implemented across all layers of the codebase and replicate the full end-to-end implementation (schema, UI wizard tab, driver step loop, answers reducer, review table, generator options, template code, unit test expectations, and documentation).
- **Generated-Agent Rule Propagation**: Whenever a change adds or modifies an enforced rule, convention, or capability for the frameworks EITR generates (a new CPOM linter rule, a new config option, a new generator behavior), the task is not complete until you have researched which AI agents EITR scaffolds into that generated project (`packages/engine/src/plan/templates/ai-agents.ts` — e.g. `test-automator`, `assertion-auditor`, `sdet-architect`, `pom-engineer`, `trace-debugger`, `sdet-orchestrator`, `review-arbiter`) and which AI-facing rules/conventions prose templates (`ai-rules.ts` and any other file rendering into a generated `CONVENTIONS.md`/`AGENTS.md`) are actually affected, and updated them to teach the relevant agents about the new rule rather than relying on a linter or build gate to enforce it silently. Grep each candidate agent's system prompt for the topic area to confirm it is actually affected rather than assuming; a mechanically-enforced rule that ships without teaching the agents operating inside the generated project how to comply with and correctly invoke any documented exception it allows is incomplete (e.g. Track 3's Rule 6 anti-over-mocking guard needing the `// @allow-mock: <reason>` suppression syntax taught to `test-automator`/`assertion-auditor` — discovered missing only after the linter check itself had already shipped). This applies to every future change to the generated frameworks, not only CPOM linter rules.
- **Absolute Ban on All Emojis (Zero Emoji Policy)**: ABSOLUTELY NEVER use any emojis in code, prompts, CLI logs, generated framework templates, markdown documentation, agent files, or chat responses.
- **Mandatory Agent Invocation Notification**: Whenever a `.claude/agents/` subagent actually is invoked, output an explicit visible text line in chat: `Запускаю агента [название_агента]...` (e.g. `Запускаю агента architect...`, `Запускаю агента core-developer...`) so the user explicitly sees every agent invocation in real time.
## 14. The "123" and "456" Protocols: Standard Multi-Agent Pipelines
The 123 Protocol is an advanced, deterministic 9-phase multi-agent engineering pipeline (SDD + TDD hybrid) for complex, high-risk, or architectural tasks. The 456 Protocol is its streamlined 6-phase sibling (Phases 0-5) for fast-track engineering tasks (everyday bugfixes, small features, or pre-scoped tracks) — it slashes tokens and latency by 80-85% compared to 123 via compact SDD planning, on-demand web research, in-session TDD, single-reviewer risk audit, and deterministic runner `scripts/protocol-456.mjs`. When given a pre-scoped track (named target files, step-by-step edits, runnable test command), Phase 0 fast-tracks directly to Phase 3, skipping planning Phases 1 & 2 while strictly retaining Phase 4 (Single-Reviewer Risk Audit).
- **Explicit Activation Only (Strict Trigger Rule)**:
- The 123 Protocol is activated **STRICTLY AND ONLY** when the user explicitly invokes it using the keyword **"123"** (e.g., _"123"_, _"сделай по 123"_, _"123-fast"_).
- The 456 Protocol is activated **STRICTLY AND ONLY** when the user explicitly invokes it using keywords **"456"**, **"по 456"**, **"таска по 456"**, or **"исправь по 456"** (e.g., _"давай по 456"_, _"пофикси баг по 456"_, _"трек 7 по 456"_).
- For standard requests without either keyword, execute the task directly in standard mode without running either pipeline.
- **Proactive Suggestion (User Decision Gateway)**: If a user request involves complex architectural refactorings or high-risk multi-file changes, the assistant may proactively propose running it via Protocol 123 (e.g. _"Хотите выполнить эту задачу по протоколу 123 с полным мульти-агентным ревью?"_). If a task is a targeted fast-track change or a ready-made plan track exists, the assistant may instead propose Protocol 456 (e.g. _"Хотите выполнить эту задачу по протоколу 456?"_). Either pipeline is launched ONLY if the user explicitly agrees.
- **Full Protocol Definitions Live in the Skills**: The complete 9-phase 123 lifecycle (Pre-Flight Baseline, Research, SDD Plan Formulation, Plan Review Swarm, User Approval Gateway, TDD Execution, Code Review Swarm, Self-Healing, QA/Doc Sync/Telemetry Summary Report) and the complete 6-phase 456 lifecycle (Intake & Quick Baseline Check, Focused Plan & On-Demand Web Research, Human Sign-Off Gate, In-Session TDD, Single-Reviewer Risk Audit, Fast Quality Gate/Doc Sync/Micro-Telemetry) are intentionally NOT duplicated here to keep this always-loaded file lean — they are the single source of truth in `.claude/skills/protocol-123/SKILL.md` and `.claude/skills/protocol-456/SKILL.md` respectively. Once a trigger above fires, that skill loads its full body automatically; treat it as mandatory reading and never improvise the phases from memory.
## 15. Multi-System AI Artifact Parity
- **Mandatory Cross-System Duplication**: This repository currently supports two AI coding CLIs for development work: **Antigravity CLI** (rules in `AGENTS.md`, agents in `.agents/agents/`, skills in `.agents/skills/`) and **Claude Code CLI** (rules in `CLAUDE.md`, agents in `.claude/agents/`, skills in `.claude/skills/`). Whenever you create, modify, or delete an agent, a skill, a hook, or any other AI-related artifact — including these two root instruction files themselves — for one system, you MUST apply the equivalent change to the other system, in that system's native format, before the task is considered complete. Never let the two AI ecosystems drift out of sync.
- **Native Format, Not Literal Text**: "Equivalent" means preserving the same rule, protocol, or behavior — not copy-pasting foreign syntax. Translate tool names, frontmatter schemas, invocation mechanisms, and model names to the target system's real, current conventions (verify via web search per the _AI Ecosystem Freshness_ rule in Section 9 if unsure), rather than inventing or guessing them.
- **Adding a Third System**: If a new AI coding system is adopted for this repository in the future, extend this rule (and the file/directory mapping above) to cover it, and update both this section and its counterpart in the sibling instructions file in the same commit.
- **Scope**: This rule covers the repository's own development tooling (`AGENTS.md`/`CLAUDE.md` and the `.agents/`/`.claude/` directories). It does NOT apply to `packages/engine/src/plan/templates/*`, which is the generator that produces AI configs for other people's scaffolded projects — that code already parameterizes per assistant and is a separate concern.
- **Deliberate Process-Weight Divergence Is Allowed**: Sections 6, 12, and 13 of this file are intentionally leaner than their `AGENTS.md` counterparts — Claude Code hits usage limits for this user well before Antigravity CLI does, so this file scales agent-spawning and pipeline weight down by task risk instead of mandating the full pipeline on every edit. This is a deliberate, requested divergence in _resource-management calibration_, not rule/protocol drift, and does not need to be mirrored back into `AGENTS.md` unless the user asks for it there too.