# Agent Rules

Shared rules for all projects in this environment. Technology appendices at end extend these rules only for matching stacks.

## 1. Coding Standards

- Clarity over cleverness; prefer obvious multi-line code to dense tricks.
- Use explicit access modifiers, return types, and argument types where language supports them.
- Scope variables narrowly; never pollute global/shared namespaces.
- Sanitize inputs and encode output for its context: HTML, JS, URL, attribute, SQL, etc.
- Never leave debug dumps, temporary exits, aborts, or throwaway logging in committed code.
- SQL: no `SELECT *`; parameterize queries with explicit type binding; inspect plans for complex/expensive SQL.
- Dates/localization: use app config/localization, not hardcoded masks.
- Style defaults: concise focused methods; named booleans for complex conditions; filenames `lowercase`; variables/methods `camelCase`; constants `UPPER_SNAKE_CASE`.
- For non-trivial changes, ask whether a cleaner solution exists. Avoid hacks/workarounds; find root cause.
- Minimal impact: touch only what is needed; no unrelated refactors or new patterns without clear reason.
- Encoding default: UTF-8 without BOM unless appendix says otherwise.
- Tests must be cross-platform: do not implicitly assume Windows, Linux, or macOS paths, separators, shells, environment variables, permissions, or link behavior. Derive platform-sensitive values from the same runtime helper/configuration under test; isolate unavoidable OS-specific assertions behind explicit platform guards.

## 2. Tool Priority

Prefer MCP/native tools over shell when equivalent exists. Use shell for builds, tests, dev servers, installs, Git operations not exposed by MCP, or subprocess-only tasks.

MCP routing:
- `projectfs-mcp-server`: for supported read-only filesystem operations, prefer it over direct shell commands: use `read_file` or `read_many` for file content, `list_dir` for directory exploration, `grep_files` for literal text search, and `stat` for metadata. Use shell commands such as `cat`, `type`, `Get-Content`, `find`, `dir`, `ls`, `grep`, `rg`, or equivalents only when ProjectFS does not support the required capability (for example regex searches, pipelines, builds, tests, writes, or process operations), and state the missing capability before the fallback. ProjectFS does not support filesystem writes. Use a write-capable mechanism only when the requested write operation is already authorized. A fallback to shell or another tool does not grant authorization and must preserve all existing safety, approval, confirmation requirements, scope, and security constraints, including for deletions, overwrites, moves, bulk changes, and destructive operations. Do not use ProjectFS for operations outside read-only filesystem exploration.
- `docs-mcp-server`: search/read internal docs before new logic. If search empty: `list_tags` -> `list_documents(include_tags=true)` -> retry with bilingual/domain synonyms.
- `memory-mcp-server`: operational memory retrieval/persistence for reusable context; keep project isolation explicit and verify against primary sources before decisions.
- `git-mcp-server`: per working tree/stage preferisci `git_query(action="status")`, `git_diff(action="working")` (anche `stat=true`, `name_only=true`, `file_path="..."`, `cached=true`) e `git_diff(action="check")` (anche `cached=true`), oltre a history, blame, repo info e conflitti. Shell (`git status --short`, `git diff`/`--stat`/`--name-only`/`-- <file>`, equivalenti `--cached`, `git diff --check`) solo se la capability MCP non e' disponibile nel runtime attivo: dichiara il fallback.
- `linter-mcp-server`: get lint config when unclear; lint all modified files before final delivery.
- `sql-mcp-server`: inspect schema before SQL; SELECT-only data checks; explain plans for complex queries.
- `playwright-mcp-server`: navigate UI, inspect DOM, screenshots, console/network, deterministic interactions.
- `office-mcp-server`: Word/Excel/PDF read/write/extract; prefer over raw binary reads.
- `mantis-mcp-server`: read/search issues, handle attachments, add private technical notes when findings must persist.
- `cf-mcp-server`: CF bridge/logs for CFML inspection; see `COLDFUSION.md` when relevant.

Skills:
- Pick one primary skill matching the objective; add sidecar skills only for direct evidence/validation.
- Read chosen `SKILL.md`; load referenced files only as needed.
- Specialist skill for single-domain work; `mcp-technical-analyst` for multi-source reconstruction; `mcp-master-orchestrator` for multi-phase coordination.
- Skill file is authoritative if it conflicts with this summary.
- For memory-heavy tasks, prefer `mcp-memory-operator` for consolidation/handoff and keep analyst/orchestrator as primary for multi-source intake.

Minimal skill map:
- Browser/UI: `mcp-browser-automation`
- Review: `mcp-code-reviewer`
- CFML: `mcp-coldfusion-developer`
- SQL/data: `mcp-database-expert`
- Docs: `mcp-docs-navigator`
- Git/Mantis traceability: `mcp-git-mantis-workflow`
- Ticket writing: `mcp-mantis-ticket-writer`
- Office files: `mcp-office-expert`
- Memory operations: `mcp-memory-operator`
- Multi-source analysis: `mcp-technical-analyst`
- Multi-phase orchestration: `mcp-master-orchestrator`
- Sophia/Yii: `mcp-sophia-yii-developer`

## 2.1 Memory Context Discipline

Use operational memory as a context layer, not as an authoritative source.

Rules:
- Verify memory-derived claims against primary sources (docs/code/tickets/commits) before implementation decisions.
- Keep project isolation explicit: provide project context (project_path or equivalent project identifier) for project-scoped memory operations.
- Prefer memory search/read before writing new entries; avoid duplicates and low-value noise.
- Persist only reusable outcomes: decisions, validated workarounds, root causes, constraints, handoff checkpoints.
- Never persist secrets, credentials, raw sensitive payloads, or verbose dumps.
- Favor stable contracts over tool-version details: if memory capabilities evolve, continue to apply these rules.
- Write trigger: persist memory only when it is likely to prevent repeated analysis or reduce regression risk in future tasks.
- Update policy: when the same fact changes, create an explicit superseding memory record rather than silently rewriting historical context.
- Conflict policy: when memory conflicts with primary sources, primary evidence wins; keep the memory item marked for reconfirmation.

## 3. Work Loop

Before starting:
- Review relevant Knowledge Items before independent research.
- Search docs first; use docs fallback before saying no docs found.
- For non-trivial work, make a checkable plan. If execution derails, stop and re-plan.
- Ask only when intent is genuinely ambiguous or assumption would be risky.
- For merge/rebase: verify repo root, branch, upstream, worktree cleanliness, source/target branches, and backup/original branch if available.

During work:
- Verify before editing: read nearby code, conventions, blame/history when useful.
- Stay within scope; do not surprise user with unrelated mutations.
- For bug reports, investigate logs/errors/tests and resolve root cause independently.
- Audit/review/regression passes stay read-only unless remediation is requested.
- If `RULES.md` exists in the target directory, read it before touching files there. It extends these rules within that directory; follow the more restrictive rule on conflicts.

After changes:
- Prove outcome with tests, lint, logs, diff, smoke checks, or equivalent evidence.
- Never call work done without validation or clearly stating what could not run.
- For rebases, compare against target branch and original source branch when possible.
- Record durable analysis/decisions as structured outputs when useful; avoid duplicating full content inline.
- If memory and primary evidence diverge, report the divergence explicitly and proceed based on primary evidence.
- After user correction, capture root cause and update the relevant rule/Knowledge Item when appropriate.

## 4. Version Control

- Do not commit unless explicitly requested.
- Commit messages should follow standard conventions; prefix tracked issues when relevant, e.g. `#1234 Fix role attribute deletion`.
- Before multi-step workflows, check `{.agents,.agent,_agents,_agent}/workflows/` and follow existing workflow docs.
- For conflicts, avoid blind `ours/theirs` on semantic files; inspect code/history and stop when business meaning is unclear.

## 5. Token/File Discipline

- Avoid reading huge files or raw Base64 into the chat. Warn and ask before full read if token saturation is likely.
- Prefer server-side save/download/export and return paths, not large inline blobs.
- For non-text artifacts, use dedicated MCP/tooling before raw reads.
- Prefer concise, evidence-first answers. No throat-clearing.
- Do not restate large code blocks, diffs, logs, JSON, SQL, or file contents unless requested.
- For findings, use: issue -> evidence -> fix -> validation.
- For tool results, summarize only relevant facts and cite path/line/range when possible.
- Prefer paths, saved artifacts, structured outputs, and checklists over inline blobs.
- For multi-step work, keep plans short and update only when state changes.
- Avoid repeating unchanged context already present in the conversation.
- When spawning sub-agents, require compact outputs: files, findings, risks, validation only.

## 6. Technology Appendices

If present beside this file, read and follow the matching appendix:
- Repo rules: `RULES.md` if exists
- CFML: `COLDFUSION.md`
- Yii/SOPHIA: `Yii.md`
- For output minimization and token-bloat control, follow `TOKEN_DISCIPLINE.md`.
