# Small Team Guide (Level 2)

*Setup time: 1-2 days. Requires team alignment.*

This guide covers how to establish shared harness engineering practices across a team of 3-20 engineers. The goal is to ensure that every team member's AI agents produce consistent, high-quality code that respects your shared standards.

---

## Prerequisites

- Every team member has completed [Level 1 (Individual)](individual-developer.md) setup
- You have a shared codebase with CI/CD in place
- Someone on the team is willing to champion the harness effort

## Step 1: Team Alignment on Harness Practices

Before changing any configuration, align on these questions:

1. **Which AI coding tools does the team use?** You need to support all of them.
2. **What are your biggest pain points with agent-generated code?** These drive your first rules.
3. **Who will maintain the harness?** Initially, one person. Eventually, everyone.
4. **How will you handle disagreements about rules?** Treat harness rules like code -- propose via PR, discuss, merge.

### The alignment meeting (30 minutes)

Run a short meeting with this agenda:

1. (5 min) Explain what a harness is and why it matters
2. (10 min) Each person shares their top 3 agent mistakes from the past month
3. (10 min) Group the mistakes into categories (conventions, architecture, testing, etc.)
4. (5 min) Agree on the first 10 rules and who will write the initial shared config

The shared mistake list is your starting backlog for harness improvements.

## Step 2: Shared AGENTS.md and Team Conventions

### Choose your base file

Use `AGENTS.md` as the universal base. It is recognized by most tools and serves as the single source of truth. Add tool-specific files that import or reference it.

### Structure for teams

```markdown
# AGENTS.md

## Project Overview
[Brief description -- same as Level 1 but reflecting the full project scope]

## Team Conventions
[This section is new -- it captures team-wide agreements]

## Architecture
[Shared architectural understanding]

## Commands
[Build, test, lint, deploy commands]

## Rules
[The "never do this" list, sourced from the team's shared mistake log]

## Workflow
[How agents should approach tasks in this codebase]
```

### Team conventions section

This is the critical addition over Level 1. Document the agreements that humans know implicitly but agents don't:

```markdown
## Team Conventions

### Code organization
- One public type per file. No exceptions.
- Shared utilities go in `src/Project.Shared/`. Don't create new utility projects.
- Feature code goes in `src/Project.Application/{Feature}/` and `src/Project.Web/Pages/{Feature}/`. Each feature has handlers, validators, and tests.

### Naming
- Public types: PascalCase (`InvoiceListPage`, `CreateInvoiceCommand`).
- Private fields: `_camelCase`.
- Async methods: end in `Async` (`GetInvoiceAsync`).
- Test classes: `{TypeUnderTest}Tests`.
- API routes: kebab-case (`/api/invoice-items`, not `/api/invoiceItems`).

### State and data flow
- HTTP requests handled by minimal API endpoints in `Project.Web` that send a MediatR command/query.
- Cross-cutting concerns (validation, logging, retries) live in MediatR pipeline behaviors.
- Persistence: Entity Framework Core 8 against Azure SQL Database. No raw SQL except in EF migrations.
- Background work: hosted services or Azure Functions, never `Task.Run` fire-and-forget.
- Do NOT use AutoMapper. We removed it -- write explicit projection methods instead.

### Error handling
- API responses use the `ProblemDetails` shape (`{ type, title, status, detail }`).
- Throw subclasses of `DomainException`. Never throw raw `Exception` or `InvalidOperationException` from application code.
- Every minimal API endpoint has a global exception filter that maps `DomainException` to the right HTTP status.

### Pull requests
- PRs should be under 400 lines of diff when possible.
- Every PR needs at least one test (xUnit + FluentAssertions).
- PR title format: `type(scope): description` (e.g., `feat(invoices): add bulk export`)
```

### Composing customization surfaces

With Copilot, the universal `AGENTS.md` lives alongside Copilot-specific surfaces. Layer them:

```
project-root/
  AGENTS.md                                # Universal agent config
  .github/
    copilot-instructions.md                # Repo-wide Copilot context
    instructions/typescript.instructions.md
    instructions/tests.instructions.md
    prompts/code-review.prompt.md
    agents/planner.md
  .vscode/mcp.json                         # MCP server wiring
```

## Step 3: CI/CD Integration for Constraint Enforcement

The harness is only as strong as its enforcement. Rules that aren't enforced are suggestions.

### Principle: If the agent can break it, CI should catch it

Every rule in your `AGENTS.md` should have a corresponding automated check. The mapping:

| Rule | Enforcement |
|------|-------------|
| "Throw `DomainException` subclasses, not raw `Exception`" | Roslyn analyzer (`PRJ012`) |
| "One public type per file" | Roslyn analyzer / `dotnet format` style rule |
| "All minimal API endpoints have a validator" | Architecture test using `NetArchTest` |
| "PRs under 400 lines" | GitHub Action that checks diff size |
| "No AutoMapper" | `dotnet list package` check in CI |

### Implementing CI checks

**GitHub Actions example -- structural checks:**

```yaml
name: Harness Checks
on: [pull_request]

jobs:
  harness:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with: { dotnet-version: 8.0.x }

      - name: Verify formatting
        run: dotnet format --verify-no-changes --severity error

      - name: Build (warnings as errors)
        run: dotnet build -warnaserror

      - name: Architecture tests
        run: dotnet test tests/Project.ArchitectureTests --no-build

      - name: Banned package check
        run: |
          # No AutoMapper
          if dotnet list src package --include-transitive | grep -i "AutoMapper"; then
            echo "ERROR: AutoMapper is banned. Use explicit projection methods."
            exit 1
          fi

      - name: PR size guard
        run: |
          DIFF_SIZE=$(git diff --stat origin/main...HEAD | tail -1 | awk '{print $4}')
          if [ "${DIFF_SIZE:-0}" -gt 800 ]; then
            echo "WARNING: PR has $DIFF_SIZE changed lines. Consider splitting."
          fi
```

      - name: Check PR size
        run: |
          DIFF_SIZE=$(git diff --stat origin/main...HEAD | tail -1 | awk '{print $4}')
          if [ "$DIFF_SIZE" -gt 800 ]; then
            echo "WARNING: PR has $DIFF_SIZE changed lines. Consider splitting."
          fi
```

### Escalating enforcement

Start with warnings, graduate to blockers:

1. **Week 1-2:** CI prints warnings but doesn't block
2. **Week 3-4:** CI blocks on critical rules (security, architecture violations)
3. **Month 2+:** CI blocks on all rules. No exceptions without team discussion.

## Step 4: Prompt Templates and Shared Context

### Prompt templates

Create reusable prompt templates for common tasks. Store them in a team-accessible location (repo, wiki, or shared directory).

**`templates/new-feature.md`:**

```markdown
## Task: Implement [FEATURE NAME]

### Requirements
[Paste requirements here]

### Acceptance criteria
[List specific criteria]

### Technical approach
- This feature belongs in `features/{name}/`
- Use the existing patterns from `features/invoices/` as reference
- Required files: component, hook, test, types

### Verification
After implementation, confirm:
1. All tests pass: `npm test`
2. No lint errors: `npm run lint`
3. No type errors: `npm run typecheck`
4. Feature works in browser: `npm run dev`, navigate to [route]
```

**`templates/bug-fix.md`:**

```markdown
## Task: Fix [BUG DESCRIPTION]

### Bug report
[Paste bug report or link]

### Steps to reproduce
[List steps]

### Expected behavior
[What should happen]

### Approach
1. First, write a failing test that reproduces the bug
2. Then fix the bug
3. Verify the test passes
4. Check for similar patterns elsewhere in the codebase

### Verification
1. The new test passes: `npm test -- --testPathPattern={test-file}`
2. All existing tests still pass: `npm test`
3. No regressions in related features
```

### Shared context documents

Maintain documents that agents can reference for deeper context:

- `docs/architecture-decisions.md` -- ADRs that explain *why* things are the way they are
- `docs/api-conventions.md` -- detailed API design standards
- `docs/database-schema.md` -- current schema with annotations
- `docs/third-party-integrations.md` -- how you interact with external services

These documents serve double duty: useful for human onboarding and for agent context.

## Step 5: Code Review with AI Agents (The Ralph Wiggum Loop)

The "Ralph Wiggum Loop" is a multi-agent review pattern:

```
Agent A generates code
    --> Agent B reviews it
        --> Agent A fixes issues
            --> Human does final review
```

### Why it works

Agent B catches different mistakes than Agent A because it approaches the code from a review perspective rather than a generation perspective. The human reviewer then handles the judgment calls that neither agent can make.

### Implementing the loop

**Option 1: Sequential agents (same tool)**

After the coding agent finishes, start a new session:

```
Review the changes in this PR. Check for:
1. Violations of our AGENTS.md rules
2. Missing test coverage
3. Potential performance issues
4. Security concerns
5. Readability and maintainability

Be specific. For each issue, cite the file and line number.
```

**Option 2: Switch custom agents for review**

Generate code with the default Copilot agent, then switch to the `reviewer` custom agent for the critique pass. The `reviewer` agent is read-only by design — it cannot edit files, only comment. This gives you a genuinely different perspective on the same diff.

**Option 3: CI-integrated review**

Configure GitHub PR reviewers (CodeRabbit, GitHub's own AI review, or in-house bots) to comment against your harness rules. Pair this with the `/code-review` prompt for a manual pre-push pass.

### What the human reviewer focuses on

With agents handling syntax, convention, and obvious bugs, the human reviewer can focus on:

- Does this approach make sense architecturally?
- Will this be maintainable in 6 months?
- Are there edge cases the agent didn't consider?
- Does this match the product intent?

## Step 6: Documentation as Infrastructure

In harness engineering, documentation is not a nice-to-have. It is infrastructure that directly affects agent output quality.

### The documentation stack

| Document | Purpose | Update frequency |
|----------|---------|-----------------|
| `AGENTS.md` | Agent instructions | Weekly (as mistakes are observed) |
| `docs/architecture.md` | System structure | When architecture changes |
| Inline code comments | Local context | With every code change |
| ADRs | Decision rationale | When decisions are made |
| API docs (OpenAPI) | Endpoint contracts | When API changes |
| `CHANGELOG.md` | Recent changes | Every release |

### Writing documentation for machines

Human documentation and machine documentation have different needs:

- **Be explicit.** "Use the repository pattern" means nothing to an agent that doesn't know your repository pattern. Show the code.
- **Be concrete.** "Follow best practices" is useless. "All database queries go through the `Repository` class in `lib/db/`" is useful.
- **Include examples.** A short code example is worth more than a paragraph of explanation.
- **Keep it current.** Stale documentation is worse than no documentation because the agent will follow it confidently.

### Documentation linting

Add checks that documentation stays current:

```yaml
# In CI
- name: Check docs freshness
  run: |
    # Flag docs not updated in 90 days
    find docs/ -name "*.md" -mtime +90 -exec echo "STALE: {}" \;
```

## Step 7: Onboarding New Team Members to the Harness

### The onboarding checklist

When a new engineer joins the team:

1. **Read `AGENTS.md`** -- This is their first stop for understanding team conventions
2. **Set up their AI coding tool** with the team's configuration
3. **Run the verification suite** -- ensure their local environment catches violations
4. **Do a "ride-along" task** -- pair with them on their first agent-delegated task
5. **Review their first 3 agent-generated PRs together** -- teach them what to look for
6. **Add them to the harness maintenance rotation** -- everyone contributes

### Ongoing harness maintenance

**Weekly (rotating):**
- Review the shared mistake log and add new rules
- Check for stale documentation
- Update config files if conventions have changed

**Monthly (team):**
- Review harness effectiveness: are the same mistakes still happening?
- Remove rules that are no longer relevant
- Discuss new patterns that should be added

**Quarterly (team lead):**
- Assess whether the team is ready for Level 3 practices
- Review tool choices -- are better options available?
- Measure agent delegation ratio and trends

## Common Pitfalls for Teams

| Pitfall | How to avoid it |
|---|---|
| One person writes all the rules | Rotate responsibility. Everyone contributes to the harness. |
| Rules added without enforcement | Every rule in AGENTS.md gets a corresponding CI check within 2 weeks. |
| Harness becomes a dumping ground | Keep it organized. Remove obsolete rules. Quality over quantity. |
| Team doesn't agree on conventions | Use PRs for harness changes. Disagree in review, not in production. |
| New members bypass the harness | Make onboarding explicit. Don't assume people will read AGENTS.md. |
| Over-engineering the harness too early | Solve real problems. Don't add rules for hypothetical mistakes. |

## Success Criteria

Your Level 2 harness is working when:

- [ ] The team has a shared `AGENTS.md` that everyone has contributed to
- [ ] CI enforces at least 10 harness rules automatically
- [ ] Agent-generated PRs pass CI on the first try more than 70% of the time
- [ ] New team members can be productive with agents within their first week
- [ ] The mistake log shrinks over time -- agents make fewer novel mistakes
- [ ] Code reviews focus on architecture and intent, not style and convention

## What's Next

When your team harness is mature, consider scaling to [Level 3 (Enterprise)](enterprise.md) for organization-wide harness infrastructure.
