# Agent Protocol (AGENTS.md)

Mandatory coordination rules for all agents (Codex/Claude/humans).
Applies before, during, and after any work in this repo.
If context is limited, follow MUST rules and Routing first.

## Project Context (v3.0.0+)

This file is generic. Paths referenced as `${paths.X}` resolve from `baldart.config.yml` in the repo root. MUST rules that target workflow infrastructure (backlog cards, ADRs, project-status doc, PRD sessions, LLM wiki overlay) apply **only when the matching `features.*` flag is `true`** in `baldart.config.yml`:

| MUST topic | Active when |
|---|---|
| Backlog cards (`${paths.backlog_dir}/`), card status, file ownership | `features.has_backlog: true` |
| ADRs (`${paths.adrs_dir}/`), architectural decision records | `features.has_adrs: true` |
| `project-status.md` Active Code Context updates | the file exists at `${paths.references_dir}/project-status.md` |
| PRD workflow, PRD sessions | `features.has_prd_workflow: true` |
| LLM wiki overlay sync | `features.has_wiki_overlay: true` |
| Design-system blocking reads | `features.has_design_system: true` |
| E2E review BLOCKING gate (Phase 2.6 of `/new` invokes `/e2e-review`) | `features.has_e2e_review: true` |

When a MUST rule's feature is `false` or its target file does not exist, the rule is **silent** — do not invent a workflow that isn't there. Project-specific terminology (audience segments, domain entities, brand voice) comes from `identity.audience_segments`, `agents/coding-standards.md`, and skill overlays under `.baldart/overlays/`. See `agents/project-context.md` for the full protocol.

## Pre-Commit Checks

Before committing, run only fast checks (lint + type check). Full build is required only before opening a PR. Fix all errors before staging files.

## File Navigation

When searching for files, use Glob/Grep to find actual file paths before reading. Never guess file paths based on naming conventions.

## Git Workflow

### Branching Strategy (Simplified Git Flow)

This repo uses a simplified Git Flow.

| Branch | Base | Merges To | Purpose |
|--------|------|-----------|---------|
| `main` | — | — | Production. No direct pushes. |
| `develop` | `main` | `main` (release PR) | Integration branch for features. |
| `feat/*` | `develop` | `develop` (PR) | Feature work per backlog card. |
| `hotfix/*` | `main` | `main` + `develop` | Critical production fixes only. |

### Branch Rules

- **Feature work**: Branch from `develop` → `feat/FEAT-XXXX-slug` → PR to `develop`.
- **Cloud agents**: Branch from `develop` → `codex/FEAT-XXXX-slug` or `claude/FEAT-XXXX-slug` → PR to `develop`.
- **Hotfixes**: Branch from `main` → `hotfix/BUG-XXXX-slug` → PR to `main`, then merge/cherry-pick to `develop`.
- **Releases**: PR from `develop` → `main` when a set of features is ready for production.
- **Direct push to `main` is blocked** by a pre-push hook. Use `--no-verify` only for documented emergencies.

### Commit Hygiene

Before committing, ensure only files related to the current task are staged. Run `git status` and `git diff --staged` to verify. Never bundle unrelated changes into a commit.

## Investigation Guidelines

When investigating whether a feature has been implemented, always check git history (`git log --oneline --all --grep`) and actual source code before claiming it exists or doesn't exist.

## Implementation Completeness

When implementing a backlog card or feature plan, verify ALL items from the plan are wired up and functional before marking complete. Cross-check each acceptance criterion against the actual code.

## Testing Conventions

When tests exist, always run the full test suite after implementation to check for regressions. If a test fails, fix the code — not the test — unless the test itself is wrong. When writing new features with tests, write failing tests first, then implement the minimum code to pass them.

## 2) Priority order & conflict policy

Priority order for conflicts:
- Agent rules: `AGENTS.md`.
- Routing: `agents/index.md`.
- Domain references: `${paths.references_dir}/*` (data-model, api/, ui-pages, product-scope, project-status).
- Decisions: `${paths.adrs_dir}/ADR-YYYYMMDD-*.md`.
- Legacy: `archive/project_full_legacy.md`.

Conflict steps (must follow in order):
1. Stop and read both sources.
2. Decide which is newer and update the other.
3. Record the decision in an ADR and the backlog card.

## 3) Repo map (compact)

- `AGENTS.md` (agent rules) + `agents/index.md` (routing).
- `${paths.backlog_dir}/*.yml` (required work cards).
- `/${paths.references_dir}/*` (API, data model, UI routes, status).
- `/${paths.adrs_dir}/` (ADRs).
- `/templates/` (card/spec templates).
- `/src/` or project-specific source directory (application code).

## 4) Non-negotiables (MUST)

### 4.a — Universal MUST (apply to every project)

- MUST treat `AGENTS.md` as authoritative for agent rules.
- MUST invoke `codebase-architect` agent (via Task tool) whenever you need to understand codebase structure, existing patterns, or code architecture before planning or implementing changes; do not proceed with planning or implementation without first understanding the existing system through codebase-architect.
- MUST NOT silently fall back when an `Agent` (a.k.a. `Task`) tool call returns empty (`0 tool uses · Done`), times out, or fails with `permissionDecision: deny`. This pattern indicates a Claude Code sub-agent failure (see anthropics/claude-code#56869) or a discovery miss / blocked agent (see #20931 and BALDART's own `agent-discovery-gate` PreToolUse hook), NOT a signal to substitute another agent. STOP, report to the user verbatim: "Agent `<name>` non discoverato o fallito in questa sessione — riavvia Claude Code e verifica con `npx baldart doctor`", and wait for direction. Never auto-route to `feature-dev:*`, `general-purpose`, or any other marketplace/built-in agent as a replacement. **This rule is the ONLY defense against bug #56869 (which BALDART cannot patch from outside Claude Code); deviating from it reintroduces the exact failure mode the rule exists to prevent.**
- MUST NOT work on files/components already claimed by another agent; multiple agents allowed if working on independent areas.
- MUST perform a mandatory clarity analysis before fixing any issue labeled `bug`; confirm that the issue description, proposed correct behavior, and edge cases are unambiguous, document any resolved doubts, and only start fix work once every zone of uncertainty is covered.
- MUST mark missing info as UNKNOWN and ask the user; if blocked, set `BLOCKED` with a blocker.
- MUST mark assumptions as ASSUMED with rationale; add an ADR if permanent (and `features.has_adrs: true`).
- MUST NOT make forbidden assumptions: external provider swap, auth provider swap, DB structure change without data model update, external dependency without documentation, API contract change without API reference update.
- MUST keep docs and code in sync; code change without doc update is invalid; doc update without code is incomplete.
- MUST use commit format `[FEAT-XXX] Brief description` or adapt to your project's convention; keep commits small/traceable.
- MUST NOT commit without updated docs or with failing lint/type checks. Full build is required only before opening a PR, not before every commit.
- MUST pre-sync: `git fetch origin`, clean status, confirm branch; use `git pull --ff-only` unless approved.
- MUST get owner approval before force push/reset, and before deleting an **unmerged** branch; create a safety tag `backup/<YYYYMMDD>-<reason>`. Deleting a feature branch that is **already merged** into `develop` is routine cleanup (it carries no unmerged work) and does NOT require a separate approval — the merge skill deletes it automatically.
- MUST NEVER push directly to `main`; all changes reach `main` via PR (release from `develop` or hotfix merge). Pre-push hook enforces this.
- MUST push working branch and keep `main` merge owner-controlled; the merge skill prunes a feature branch's own remote ref on successful merge into `develop` (routine), but pruning OTHER remote branches happens only when instructed.
- MUST run testing gates before DONE: run tests (if exist), run build, and CI checks on PR; manual validation is REQUIRED for local mode and OPTIONAL for cloud mode.
- MUST pass pre-commit hooks (linting, type checking, markdown lint, build); bypass (`--no-verify`) only for documented emergencies.
- MUST use API versioning for breaking changes: create new version, deprecate old with appropriate headers, minimum sunset period; see project-specific API migration docs.
- MUST use exact terminology from `agents/coding-standards.md` if it exists in your project, plus any terminology declared in `.baldart/overlays/<skill>.md`.

### 4.b — Workflow MUST (only when the matching `features.*` flag is `true`)

- **When `features.has_backlog: true`:**
  - MUST pick one backlog card (TODO/READY), set `IN_PROGRESS`, and assign yourself before work.
  - MUST ask the user which git strategy to use when creating a backlog card and record it in `git_strategy`; if the user requires cloud-agent execution, use a non-main feature branch.
  - MUST keep backlog tasks/notes/status current and log decisions.
  - MUST follow the `git_strategy` specified in the backlog card; if not specified, ask the user before starting work; delete merged branches when instructed.
  - MUST use branch-per-card (`feat/<CARD-ID>-<slug>`, `codex/<CARD-ID>-<slug>`, or `claude/<CARD-ID>-<slug>`), branching from `develop` for features and from `main` for hotfixes only.
  - MUST document every implementation or variation (backlog card/spec/docs update referencing the issue/feature) before merging.

- **When the file `${paths.references_dir}/project-status.md` exists:**
  - MUST update its Active Code Context before work; multiple agents allowed if working on independent areas.
  - MUST follow handoff protocol in Active Code Context; receiver acknowledges and sets `IN_PROGRESS`.
  - MUST keep it under 200 lines; archive detailed work logs to `${paths.references_dir}/work-history.md`.
  - MUST limit Active Code Context to 1 current + 3 recent entries max; use one-line summaries (no file lists).
  - MUST archive work entries older than 7 days to `work-history.md`.

- **When `features.has_adrs: true`:**
  - MUST create complete ADRs (Context, Decision, Rationale, Alternatives, Consequences; no TODO placeholders) for architectural decisions: provider changes, auth changes, DB schema changes, API contract changes, external dependencies, deployment targets, performance/scalability decisions, data model changes affecting multiple features.

- **When the project ships a GitHub issue review convention** (declared in `.baldart/overlays/`):
  - MUST comment on every GitHub issue when resolving it and apply the project's review label (e.g. `vibe review`) per the overlay's labelling rule.
  - MUST create QA issues per test case (labels `qa` + area); when fixed add a fix summary, apply the review label, leave open; open QA issues are the source of truth.
- MUST NOT add detailed file lists or multi-line work descriptions to project-status.md; use work-history.md instead.

## 5) Guidelines (SHOULD)

- SHOULD use Routing to load only relevant modules.
- SHOULD update `${paths.references_dir}/project-status.md` when risks/status change.
- SHOULD review for duplication or drift when updating docs.
- SHOULD set `execution_mode: cloud` in backlog cards handled by cloud agents and claim file ownership using `claimed_paths`.

## 5.1) Execution Modes

- `local`: work on feature branches from `develop`; direct commits to `develop` allowed for trivial changes with owner approval; manual validation remains mandatory before DONE.
- `cloud`: always use feature branch from `develop`, open PR to `develop`, and rely on CI-first validation; local dev server checks are advisory unless explicitly requested.
- `hotfix`: branch from `main` for critical production fixes; merge to both `main` (deploy) and `develop` (sync); requires owner approval.

## 6) Optional conventions (OPTIONAL)

- OPTIONAL: None defined. Add project-specific conventions as needed.

## 6.1) Deprecated Patterns (DO NOT USE)

- Add project-specific deprecated patterns here as they emerge.
- Example: Legacy authentication patterns, outdated API endpoints, deprecated libraries, etc.

## 7) Routing (If you touch X, read Y)

- **Documentation routing**: See `agents/index.md` for which docs to read/update when touching code.
- **Agent invocation routing**: See `.claude/agents/REGISTRY.md` for which agent to invoke via Task tool (single source of truth for all agent capabilities, categories, and decision tree). When adding or updating agents, update REGISTRY.md.

## 8) Workflow gates (tests/build/deploy)

### Pre-commit checks (MUST — fast, ~30s)

Before attempting any `git commit`, MUST run these checks on affected files and fix all errors:

1. Lint check on changed source files — fix all lint errors.
2. Type check (if applicable) — fix all type errors.
3. Markdown lint on changed `.md` files (if .md files changed) — fix all errors.

Only after all checks pass, proceed with `git add` and `git commit`.
Do NOT run a full build before every commit — it kills agent velocity.
Do NOT rely on pre-commit hooks to catch these — run them explicitly first to avoid failed commit retry cycles.

Note: Use linting tools that scope to staged files only when possible; type checking may need to run on the whole project depending on your language/toolchain.

### Pre-PR build check (MUST — before opening any PR)

Before opening a pull request, MUST run:

1. Full build — must pass with no errors.
2. Full test suite — if tests exist, must pass.

This is the only time a full build is required. Do not repeat this for every intermediate commit.

### Manual testing protocol (MVP)

1. Run test suite when tests exist.
2. Run build command (must pass).
3. Run project and manually test changed flows.
4. Record results in backlog card notes.

QA issue methodology (manual):
- One GitHub issue per test case (atomic scope).
- Labels: `qa` + one macro area (customize area labels for your project).
- When fixed: add fix summary comment, apply `vibe review`, leave open.
- If test passes: leave issue open with a short note.
- If test fails: keep open with details and evidence.
- Open QA issues are the source of truth for unresolved bugs.

## 9) Token budget / truncation policy

### File size thresholds

| Doc Type | Max Lines | Action When Exceeded |
|----------|-----------|---------------------|
| Index files (index.md) | 200 | Split by domain |
| Agent modules (agents/*.md) | 300 | Split into sub-modules |
| Reference docs (${paths.references_dir}/*) | 400 | Split by topic |
| API docs (${paths.references_dir}/api/*) | 800 | Split by endpoint group |
| Specs/PRDs (${paths.references_dir}/specs/*, ${paths.prd_dir}/*) | 800 | Split into requirements + implementation |
| project-status.md | 200 | Archive to work-history.md |

### When context is truncated

1. Re-read only the specific section needed (use offset/limit).
2. Use index files (`api/index.md`, `ui/index.md`, `agents/index.md`) to navigate — never load all docs at once.
3. Link over duplicate — one source of truth per fact.
4. Prefer tables over prose for structured data.
5. If a file exceeds its threshold by 50%+, create a backlog card to split it.

### Loading priority

When context budget is limited, load in this order:
1. `AGENTS.md` (rules — always first)
2. `agents/index.md` (routing)
3. Relevant domain module only (not all modules)
4. `${paths.references_dir}/project-status.md` (if status context needed)

## 10) Change protocol (updating this file)

1. Open/update a backlog card for doc changes.
2. Update the relevant module(s) first.
3. Update `${paths.references_dir}/project-status.md` if status or risks change.
4. Add an ADR for architectural decisions.
5. Review for duplication or drift.
