# AI Workflow

> How AI assistants (Claude Code, Cursor, Copilot) operate inside this repository. This is the operator's guide — what to invoke, when, and what governs it.

For the project's coding rules see [CLAUDE.md](../CLAUDE.md). For the per-agent roster see [AGENTS.md](../AGENTS.md). This document focuses on **workflow**: the lifecycle of an AI-assisted change.

---

## 1. Mental model

Three layers cooperate on every AI-assisted task:

1. **Memory** — `CLAUDE.md`, `AGENTS.md`, `.claude/context/*.md`, and ADRs in `docs/decisions/` are read on every session.
2. **Action** — slash commands (`.claude/commands/`), sub-agents (`.claude/agents/`), skills (`.claude/skills/`), and MCP tools (`.mcp/`) are the active surface.
3. **Guard rails** — hooks (`.claude/hooks/`) + validators (`tools/validators/`) + permission rules in `.claude/settings.json` enforce safety.

```
prompt ─► memory load ─► (command | agent | skill) ─► hooks ─► edit/commit
                                    │
                                    └─► may call: MCP tool, validator, sub-agent
```

---

## 2. Picking the right entry point

| You want to...                       | Use                                             |
| ------------------------------------ | ----------------------------------------------- |
| Build a vertical feature (DB → UI)   | `/create-feature` slash command                 |
| Add one API endpoint                 | `/create-api`                                   |
| Add one frontend page                | `/create-page`                                  |
| Generic CRUD scaffold                | `/create-crud`                                  |
| Draft an ADR                         | `/create-adr`                                   |
| Review a diff before merge           | `/review-code` (multi-agent)                    |
| Plan a risky DB migration            | `/db-migrate` + `migration-agent`               |
| Audit security                       | `/security-audit` + `security-agent`            |
| Audit performance                    | `/perf-audit` + `performance-agent`             |
| Decide architecture / trade-offs     | `architect-agent` (no command — invoke by name) |
| Specialized task with hidden gotchas | a skill from `.claude/skills/` (see §4)         |

Slash commands are the **primary** entry point — they bundle context, steps, and validation. Sub-agents are invoked when a task spans multiple files or needs a specific persona. Skills are loaded on demand for known-hard tasks.

---

## 3. Sub-agents

16 agents live under `.claude/agents/`. Each has a defined scope, allowed files, and a quality checklist. See [AGENTS.md](../AGENTS.md) for triggers and one-line responsibilities.

**Routing rule:** start with the most specific agent the task matches. The agent will hand off (via its own `Handoff` section) when work crosses into another domain.

---

## 4. Skills

Skills are **task playbooks** stored as `.claude/skills/<skill>/SKILL.md`. They encode hard-won, environment-specific knowledge (library quirks, output paths, validation steps) that vanilla prompting forgets.

Available skills (21):

| Skill                       | Use when                                                |
| --------------------------- | ------------------------------------------------------- |
| `feature-vertical-slice`    | Building a full DB → API → UI feature                   |
| `crud-generator`            | Standard list/create/update/delete screen               |
| `auth-flow`                 | Login / refresh / logout changes                        |
| `realtime-feature`          | SignalR or WebSocket channel                            |
| `queue-worker`              | BullMQ or Hangfire background job                       |
| `file-upload`               | S3-compatible upload with signed URLs                   |
| `pdf-generation`            | Server-side PDF (report, invoice)                       |
| `excel-import-export`       | XLSX import/export with validation                      |
| `email-template`            | Transactional email (i18n, responsive)                  |
| `notification-channel`      | Add a delivery channel (LINE, Slack, SMS, ...)          |
| `payment-integration`       | Stripe / Omise / 2c2p with idempotent webhooks          |
| `audit-log-instrumentation` | Wire em-audit into a mutation or sensitive read         |
| `multi-tenant-isolation`    | Add tenant scoping when `auth.multiTenant` is on        |
| `pdpa-data-export`          | DSAR export (right-to-access)                           |
| `pdpa-data-deletion`        | DSAR erasure (anonymize in place)                       |
| `migration-safe-rollback`   | Reversible schema change under live traffic             |
| `performance-budgeting`     | Enforce Lighthouse / bundle / DB budgets before release |
| `accessibility-audit`       | WCAG 2.2 AA check on a component or page                |
| `i18n-key-extraction`       | Extract hardcoded strings into Transloco/next-intl keys |
| `dependency-upgrade`        | Safe single-package or batch upgrade                    |
| `incident-postmortem`       | Blameless postmortem + remediation ADR                  |

If a task matches a skill name, **load the skill first** — it will save iteration time.

---

## 5. Orchestrators (multi-agent pipelines)

For work that always spans the same chain of agents, use an orchestrator from `.claude/orchestrators/`:

| Orchestrator              | Chain                                                       |
| ------------------------- | ----------------------------------------------------------- |
| `feature-orchestrator`    | prd → architect → backend → frontend → qa → reviewer → docs |
| `review-orchestrator`     | reviewer + security + performance + a11y (parallel)         |
| `deployment-orchestrator` | security-audit → perf-audit → release-manager → devops      |
| `release-orchestrator`    | changelog → tag → notes → notifications                     |
| `incident-orchestrator`   | triage → root-cause → fix → postmortem ADR                  |

Orchestrators are invoked like commands but are explicit about handoffs between agents.

---

## 6. MCP integration

MCP server configs live under `.mcp/servers/`. Profiles bundle the right set of servers for a context:

| Profile                    | Use when                               | Posture   |
| -------------------------- | -------------------------------------- | --------- |
| `local-dev.json`           | Day-to-day development on your machine | Broadest  |
| `ci-review.json`           | CI jobs reading the repo               | Read-only |
| `production-readonly.json` | Querying production for diagnostics    | Read-only |
| `designer.json`            | Designer iterating in Figma + Notion   | Minimal   |

**Security rules** (enforced by [policies/security.md](../.mcp/policies/security.md)):

- Never commit real secrets. Use `${ENV_VAR}` references only.
- Production credentials default to **read-only**.
- Destructive MCP operations require explicit human approval.
- `production-readonly.json` is the **default** in CI; `local-dev` is opt-in.

See [.mcp/README.md](../.mcp/README.md) for setup and [policies/permissions.md](../.mcp/policies/permissions.md) for why each server earns its place.

---

## 7. Hooks (Claude Code, not git)

Active hooks under `.claude/hooks/`:

| Hook                       | Event                    | Purpose                                                            |
| -------------------------- | ------------------------ | ------------------------------------------------------------------ |
| `bash-guard.sh`            | `PreToolUse(Bash)`       | Block `rm -rf`, force pushes, writes to `.env`, etc.               |
| `secret-scan.sh`           | `PreToolUse(Edit/Write)` | Detect API keys, tokens, private keys before write completes       |
| `post-edit-validate.sh`    | `PostToolUse`            | Run eslint/prettier/tsc on touched files only                      |
| `architecture-validate.sh` | `PostToolUse`            | dependency-cruiser + custom boundary checks                        |
| `inject-context.sh`        | `UserPromptSubmit`       | Inject relevant `.claude/context/*.md` summaries based on keywords |
| `update-repo-map.sh`       | `Stop`                   | Regenerate `repository-map.generated.json` (gitignored scratch)    |
| `pre-commit-quality.sh`    | git pre-commit           | Format + lint + commit-msg validation (called by Husky)            |

Hooks are **best-effort** — they never block AI on transient failures, only on real policy violations.

---

## 8. Repository intelligence

Two complementary maps live under `tools/validators/`:

- **`repository-map.json`** — canonical snapshot of top-level folders + one-line purpose each. Checked in. Updated via `pnpm generate:repo-map`.
- **`repository-map.generated.json`** — scratch output from the Stop hook. Gitignored. Never tracked.
- **`dependency-map.json`** — app-to-package and package-to-package dependency graph.
- **`module-boundaries.json`** — declared allowed-dependency edges (enforced by `validate:arch`).
- **`feature-ownership.json`** — which team/agent owns which folder.

`pnpm validate` runs `validate:repo-map` + `validate:arch` + `validate:deps` + `validate:format`. Run it before staging.

---

## 9. Governance — what AI is **not** allowed to do

Mirrored in [CLAUDE.md §10](../CLAUDE.md) and as hard denies in [.claude/settings.json](../.claude/settings.json):

- Edit `.env*`, `appsettings.*.json`, `platform/secrets/**`.
- Run `rm -rf`, `git push --force`, `git reset --hard`, `git clean -fd`, `git checkout -- .`, `git restore .`.
- Bypass git hooks (`--no-verify`, `--no-gpg-sign`, ...).
- Commit real secrets or credentials.
- Generate speculative code "while we're here."
- Add backwards-compat shims unless the user explicitly asks.

If a workflow needs to cross one of these lines, **write an ADR first** (`/create-adr`) and get human sign-off.

---

## 10. Typical workflow

A new feature, end to end:

1. **Describe intent** — one paragraph in chat. State the user story and the acceptance check.
2. **Plan** — invoke `architect-agent` or `/create-feature` to break it into a slice.
3. **ADR if non-trivial** — `/create-adr` if a decision will outlive this PR.
4. **Build** — let the skill / command / agent do the slice.
5. **Validate locally** — `pnpm validate && pnpm test`.
6. **Review** — `/review-code` triggers reviewer + security + performance + a11y agents in parallel.
7. **Stage** — Husky `pre-commit` runs format + secret scan + commitlint.
8. **Push** — Husky `pre-push` runs `pnpm validate` again.
9. **CI** — `.gitlab-ci.yml` (+ GitHub Actions parallel preset) re-runs validators in `production-readonly` MCP profile.
10. **Merge** — `/release` for version bump + changelog + tag when the slice ships.

---

## 11. When the AI gets stuck

In order:

1. Re-read [CLAUDE.md](../CLAUDE.md) and any nested `CLAUDE.md` in the touched folder.
2. Check `docs/decisions/` for an ADR that constrains the area.
3. Check `knowledge/anti-patterns/` for what NOT to do here.
4. If a matching skill exists, load it.
5. If the task spans multiple agents, escalate to the right orchestrator.
6. If still blocked — write a short ADR proposing the decision and ask for human review.

Pause and ask the human before any action that crosses a §9 guard rail. Authorization granted once does not carry to the next task.

---

## 12. Links

- [CLAUDE.md](../CLAUDE.md) — repository memory & coding rules
- [AGENTS.md](../AGENTS.md) — sub-agent roster
- [.claude/commands/](../.claude/commands/) — slash commands
- [.claude/skills/](../.claude/skills/) — skill playbooks
- [.claude/orchestrators/](../.claude/orchestrators/) — multi-agent pipelines
- [.mcp/README.md](../.mcp/README.md) — MCP setup
- [docs/decisions/](decisions/) — ADRs
- [knowledge/](../knowledge/) — AI knowledge base
