# AI Agent Interaction Guidelines

> Objective: Define the behavioral boundaries for AI assistants and agents within this repository to ensure safe, predictable, and high-quality collaboration.

## 1. Safety & Boundaries

### Scope Constraints

- **No Blind Refactoring**: AI MUST NOT perform large-scale refactoring unless explicitly requested by the user. A user asking to "fix a bug in function X" is not a request to refactor the entire file or module.
- **Scope Limitation**: AI MUST strictly limit its changes to the files required to fulfill the user's explicit request. Do not "fix" unrelated code nearby unless it directly breaks the build or is a critical security issue. Every out-of-scope change MUST be flagged to the user.
- **Restricted Files**: AI agents MUST NOT modify `CHANGELOG.md` directly. This file is managed by automated professional tools and is considered read-only for agents.
- **Destructive Operations**: AI MUST ask for explicit confirmation before:
  - Deleting files or directories
  - Dropping database tables or executing irreversible migrations
  - Resetting or wiping state (caches, volumes, indexes)
  - Modifying production infrastructure configurations
  - Removing API endpoints or removing public interface methods
    Always describe the exact impact ("This will permanently delete the file `/src/legacy/old-auth.ts` and its test file.") before proceeding.
- **Reversibility**: Prefer reversible changes over irreversible ones. When a destructive operation is necessary, provide a rollback procedure alongside the change:

  ```bash
  # Before: backup the database
  pg_dump myapp > backup_$(date +%Y%m%d_%H%M%S).sql

  # Migration (destructive)
  psql myapp < migration_drop_legacy_users.sql

  # Rollback: restore from backup if needed
  psql myapp < backup_YYYYMMDD_HHMMSS.sql
  ```

- **Permission Escalation Prevention**: AI must not attempt to acquire permissions or access beyond what is explicitly granted for the current task. If an operation requires elevated permissions not granted in the session, request them explicitly from the user rather than attempting workarounds.

## 2. Code Generation & Modification

### Quality Standards & Auto-fix

- **Mandatory Auto-fix Routine**: The AI MUST actively act as the first line of defense for the "Triple Guarantee" code quality mechanism. After creating or modifying any file, the AI MUST proactively run the appropriate linting and formatting tools to auto-fix the codebase before handing it back to the user or generating a commit.
  - **Source of Truth:** ALWAYS reference `.pre-commit-config.yaml` and `.github/workflows/lint.yml` for the current tool stack and their exact command arguments.
  - **JS/TS/Vue/React**: Run `eslint --fix <file>` and `prettier --write <file>`
  - **CSS/SCSS/LESS**: Run `stylelint --fix <file>` and `prettier --write <file>`
  - **TOML**: Run `taplo format <file>`
  - **Go**: Run `gofmt -w <file>`
  - **Python**: Run `ruff check --fix <file>` and `ruff format <file>`
  - **Obj-C/C++**: Run `clang-format -i <file>`
  - **Documentation**: Provide clear comments for complex logic, and use tools like `markdownlint-cli2` to ensure Markdown consistency.
  - **SAST/SCA/Heavy Audits**: Local execution of `semgrep`, `trivy`, `lychee`, `golangci-lint`, `ansible-lint`, and `cargo clippy` is **DISABLED** to maintain performance. These are strictly reserved for CI.
  - **Git Flow**: The system enforces Conventional Commits via `commitlint` locally and Semantic Pull Request titles remotely. ALWAYS ensure your commit messages and PR titles follow the `<type>(<scope>): <subject>` format exactly.
  - **No Bypass**: AI agents MUST NEVER use the `--no-verify` flag when committing. If a linting or formatting hook fails, the agent MUST resolve the issue in the code rather than bypassing the quality gate.
  - **Exact Versioning**: AI agents MUST always use exact version numbers (e.g., `1.2.3` instead of `^1.2.3` or `@v4`) in `package.json`, `requirements.txt`, and GitHub Actions to ensure deterministic builds.
  - **Markdown files**: Run `markdownlint-cli2 --fix <file>` and `prettier --write <file>`
  - **YAML/JSON files**: Run `prettier --write <file>` and `yamllint <file>`
  - **Shell scripts**: Run `shfmt -w -s -l <file>` (formatting) and `shellcheck <file>` (logic).
  - **Dockerfile**: Run `hadolint <file>`.
  - **API Contracts**: Run `spectral lint <file>` on OpenAPI/Swagger specs.
  - _Never leave formatting or linting errors for the user, the Git Commit hook, or the CI pipeline to catch. Nip all errors in the bud._

- **Test-Driven Mentality**: When modifying logic or adding features, the AI MUST proactively update or create corresponding tests. Do not output untested code as final without a clear warning:

  ```
  ⚠️ Note: The above implementation does not yet have unit tests.
  Would you like me to generate them? I recommend testing:
  - Happy path: valid input returns expected output
  - Edge cases: empty input, null values, boundary conditions
  - Error cases: invalid format, database failure
  ```

- **Incremental Changes**: Prefer small, incremental, and reviewable changes over massive code dumps. Explain the approach before outputting large code blocks ("I'll make three changes: first X, then Y, then Z — let me start with X...").
- **Mandatory Auto-Commit Logic**: When executing multiple tasks, suggestions, or changes in sequence, the AI agent **MUST** perform an automatic commit after each individual change — never batch them:
  1. **Implement** one change completely.
  2. **Auto-fix** (lint/format) the changed files.
  3. **Commit** it immediately with a precise Conventional Commit message.
  4. **Proceed** to the next item.

  This is a core operational requirement. Every feature implementation or bug fix must result in an immediate, independent, and auditable unit of work. Batching changes or skipping auto-commits is unacceptable.

- **Error Handling**: Generated code MUST include robust error handling adhering to the project's coding style. Never silently swallow errors:

  ```typescript
  // ❌ No error handling — silent failures in production
  async function getUser(id: string) {
    const user = await db.users.findOne({ id });
    return user;
  }

  // ✅ Explicit error handling with context
  async function getUser(id: string): Promise<User> {
    try {
      const user = await db.users.findOne({ id });
      if (!user) throw new NotFoundError(`User '${id}' not found`);
      return user;
    } catch (err) {
      if (err instanceof NotFoundError) throw err;
      throw new DatabaseError(`Failed to fetch user '${id}'`, { cause: err });
    }
  }
  ```

- **No Magic Numbers**: Generated code must not contain unexplained constants or hardcoded values. Use named constants with comments explaining their origin:

  ```typescript
  // ❌ Magic number — what is 86400?
  const tokenTtl = 86400;

  // ✅ Named constant with explanation
  const TOKEN_TTL_SECONDS = 60 * 60 * 24; // 24 hours — aligned with session cookie max-age
  ```

- **Rigorous Verification**: Before referencing a specific API, library function, version number, or configuration option, AI agents MUST verify its existence and exact syntax in the target environment or official documentation.
  - **No Subjective Guessing**: NEVER guess version numbers (e.g., assuming `v1.2.0` exists because `v1.1.0` does).
  - **No Feature Assumption**: NEVER assume a tool supports a flag or feature without verifying the specific version's man page or help output.
  - **Uncertainty Disclosure**: If verification is impossible in the current context, clearly state: "I cannot verify if version X exists—please confirm before proceeding."

## 3. Communication Strategy

### Clarity & Transparency

- **Ask When Uncertain**: If a request is ambiguous, lacks context, or involves undocumented legacy code, ask clarifying questions rather than guessing. Ask at most 3-5 targeted, specific questions at once. Bad: "What do you want?" Good: "Should the new endpoint require authentication? And should it return 404 or an empty array when no results are found?"
- **Acknowledge Mistakes**: If an error occurs or a test fails based on an AI suggestion, acknowledge the mistake clearly and provide a corrected approach. Never deflect blame to the user's setup without evidence.
- **Concise Reporting**: Keep explanations concise. Avoid verbose pleasantries. Lead with the technical point. For long outputs, lead with a summary and offer to expand sections.
- **Uncertainty Expression**: Use explicit qualifiers when confidence is not high. Never present uncertain information with false confidence:
  - "I'm fairly confident that..." — moderate confidence
  - "You should verify, but my understanding is..." — lower confidence
  - "This is based on the documentation for version X — verify for your version" — version uncertainty

## 4. Context Handling & Token Management

### Knowledge & Research

- **Read Before Writing**: AI MUST read relevant project documentation, architecture files, and existing code patterns before generating new implementations. Generating code that contradicts the project's established patterns is unacceptable. Always check:
  1. Existing similar implementations in the codebase (avoid duplication)
  2. Project conventions (naming, file structure, error handling patterns)
  3. Relevant architecture documents or ADRs
  4. Any related tests that document expected behavior
- **CLI-First Research Strategy**: AI agents MUST prioritize command-line tools (e.g., `grep`, `find`, `curl`, `gh api`) over browser-based research. Browser tools are considered high-latency fallbacks; use them only for complex visual documentation or when CLI-accessible resources are exhausted.
- **Artifact Usage**: Utilize designated memory or "brain" directories (if configured) to store and retrieve long-running task context, architectural decisions, checklists, and completed vs pending work. Reference prior decisions rather than re-inventing them.
- **Check Existing Code**: Before creating a new utility function or module, search the codebase for an existing equivalent. Avoid duplication — reference the existing implementation and extend it if needed.

### Token Limits & The Lazy-Loading Router (MANDATORY)

To prevent Context Window Overflow and hallucination caused by massive rule sets, ALL AI agents MUST strictly adhere to the **Lazy-Loading Router Architecture** when consulting the project's Single Source of Truth (`.agent/rules`):

1. **Anti-Global-Load Guard**: AI agents MUST NEVER attempt to load, read, or list all files in the `.agent/rules/` directory simultaneously.
2. **Core Fundamentals**: AI agents inherently understand or must load the general rule set (`01` through `12`).
3. **The Router (`00-index.md`)**: For any technology-specific logic (e.g., Go, React, Ansible, Docker), the agent MUST consult `00-index.md` to find the exact rule file name for that stack.
4. **On-Demand Loading**: The agent MUST ONLY load the specialized rule file(s) definitively required for the current granular task. For example, if fixing a Python script, do not load Go or Ruby rules.
5. **Context Window Management**: In long conversations, periodically summarize what has been accomplished and what remains. If the context is too large to process accurately, proactively request a focused sub-task definition or clear your localized memory of irrelevant files to free up token space.

## 5. Quality & Review

### Standards Before Output

- **Self-Review Checklist**: Before presenting generated code, review it mentally for:
  - ✅ Correctness: does it solve the stated problem?
  - ✅ Security: any injection vulnerabilities, exposed secrets, privilege escalation?
  - ✅ Edge cases: null/undefined, empty collections, boundary values, concurrent access?
  - ✅ Error handling: are all failure modes handled explicitly?
  - ✅ Style consistency: does it match the existing codebase patterns and conventions?
  - ✅ Test coverage: are tests added/updated for the changed logic?
- **Cite Sources**: When recommending a specific library, pattern, or algorithm, briefly justify why it is the best choice for this context — performance, community support, license, maintainability — rather than presenting it as the only option.
- **Versioning Awareness**: When referencing APIs, libraries, or framework features, be explicit about the version they apply to. Avoid recommending deprecated APIs. If the project uses an older version, provide version-appropriate guidance and note the upgrade path.
- **Output Validation**: For generated configurations, scripts, or infrastructure code, include a validation command alongside the output so the user can verify correctness independently:

  ```bash
  terraform validate && terraform plan   # IaC validation
  kubectl --dry-run=client apply -f manifest.yaml  # Kubernetes dry-run
  docker build --no-cache -t test-image .          # Docker build validation
  tsc --noEmit                                 # TypeScript type check
  ```

- **Language-Aware & Contextual Automation**: When creating or modifying health checks, setup scripts, or CI pipelines, AI agents MUST implement **Language-Aware Detection** and **Selective Display**.
  - Scripts SHOULD auto-detect active languages and tools.
  - Irrelevant checks SHOULD be skipped or groups hidden to avoid noise.
  - See [08-dev-env.md](08-dev-env.md) and [10-ui-ux.md](10-ui-ux.md) for UX standards.

## 6. Advanced Agentic Workflows & Isolation

### Artifact & State Management

- **Persistent State Isolation**: When AI agents need to maintain persistence, long-running task context, or detailed checklists (e.g., `task.md`), they MUST create and use the **`.agent/brain/`** directory at the project root.
- **Git Pollution Prevention**: To prevent these AI memory files from polluting the project's version control history, the `.agent/brain/` directory is strictly ignored in `.gitignore`. AI agents MUST verify this isolation before writing state.
- **Temporary Scratchpads**: For completely ephemeral work (one-off debug scripts, intermediate text processing), use the OS temporary directory (`/tmp/` or `%TEMP%`) to ensure zero trace is left after a restart.

### Tool Calling Priorities

When operating in an agentic mode equipped with system tools, AI MUST prioritize tools according to stability and safety:

1. **The Hierarchy of Execution (Native API > Shell > Browser)**:
   - **Tier 1 (Native APIs)**: ALWAYS use native, purpose-built file manipulation APIs (e.g., `replace_file_content`, `view_file` equivalents exposed by the host IDE) as the absolute first choice.
     - **File Modification Best Practice**: Prefer `strReplace` over `fsWrite` for existing files:

       ```typescript
       // ❌ WRONG: Rewriting entire file (risks overwriting others' changes)
       fsWrite('.devcontainer/devcontainer.json', completeFileContent)
       // Risks: May overwrite concurrent changes, lose previous fixes, introduce regressions

       // ✅ CORRECT: Precise surgical replacement
       strReplace({
         path: '.devcontainer/devcontainer.json',
         oldStr: '"workspaceFolder": "/workspaces/template",',
         newStr: ''  // Remove this line
       })
       // Benefits: Minimal change scope, preserves other modifications, easier to review
       ```

     - **When to use `fsWrite`**: Only for creating new files or when the entire file structure needs to change
     - **When to use `strReplace`**: For all modifications to existing files (99% of cases)
     - **Why this matters**: `fsWrite` can accidentally overwrite fixes made in other branches or by other developers, leading to regression of previously resolved issues

   - **Tier 2 (Shell/CLI)**: If native APIs are insufficient, fall back to CLI tools (`grep`, `curl`, `jq`).
   - **Tier 3 (Browser)**: The Browser tool is the absolute last resort. Use it ONLY for rendering visual documentation, passing CAPTCHAs, or interacting with heavy client-side SPAs where CLI scraping fails.
2. **Strict Prohibition on Dangerous Shell Text Processing**: NEVER use `cat <<EOF > file`, `sed -i`, or `echo > file` in a shell command to modify source code. These workflows are highly prone to escaping errors and context corruption.
3. **Targeted Search**: Use structured search tools (`grep_search`, `ast_search`) before falling back to full-disk `find` or unconstrained `grep -r`, to prevent IO exhaustion.
4. **Absolute Paths**: Always construct and utilize **absolute paths** when interfacing with the filesystem to eliminate relative-path context confusion inside autonomous loops.

### Self-Correction & Autonomous Rollback

- **Mandatory Self-Correction Loop**: After making changes to source code or configuration, the AI MUST silently and autonomously run the appropriate linter, compiler, or test suite to verify the change.
- **Silent Retry**: If the validation command fails, the AI MUST NOT immediately stop and report the error to the user as a failure. Instead, it MUST attempt to read the error logs, self-correct the code, and re-run the validation at least once. Only escalate to the user if the self-correction loop fails repeatedly or fundamentally changes the design constraints.
