Skip to content
Loïc Chossière AI Consultant

Free training

Free Claude Code Training – 2026

This guide starts with a basic use case (on-demand code generation) and transforms it into a controlled, tested, and traceable development environment that can be used on a real production codebase. Each section stands on its own: a concept, a practical implementation, and the associated pitfalls.

  • 28 min read
  • 12 chapters
  • No email address required

1. Getting Started

Claude Code is a command-line tool: it reads project files, suggests changes, runs commands (tests, build, git), and waits for your approval. This section covers the bare essentials you need to get up and running in about 20 minutes.

1.1 Installation and First Launch

Claude Code can be used via the Claude app available on Mac or Windows, via a Visual Studio Code extension, or globally via npm (Node 18+). Once installed, you launch it from the project root; the current folder defines the scope of the project. A desktop app (Windows/macOS) has been available for some time for those who prefer not to use the terminal; it provides the same engine with a graphical user interface. To get started, however, the terminal remains the most straightforward option.

1.2 Basic Work Loop

The basic cycle consists of six steps. The goal is to never accept a change without reviewing it first: you are ultimately responsible for what is committed to the repository.

# 1. Décrire le besoin en langage naturel
> ajoute une validation d'email au formulaire d'inscription

# 2. Claude lit les fichiers concernés et propose un diff
# 3. Relire le diff (ne pas valider à l'aveugle)
# 4. Accepter, refuser, ou demander un ajustement ciblé
> le message d'erreur doit être en français et accessible aux lecteurs d'écran

# 5. Vérifier que le code tourne
> lance les tests unitaires du module d'inscription

# 6. Committer
> crée un commit avec un message conventionnel

1.3 Permission Modes

The permission mode determines what the agent can do without asking you. You can change it on the fly by cycling through Shift+Tab, or at launch with --permission-mode. In the Windows/Mac app, you can select the permission mode below the chat.

Mode Behavior When to use it
default Asks for confirmation before each write/command Discovery, sensitive code
acceptEdits Automatically accepts file edits A structured task where you then review the overall diff
plan Read-only: explore and suggest a plan; do not write anything Outline before writing a single line
bypassPermissions No longer prompts for anything (including shell commands) Disposable environment only (container, worktree)
auto Decides on its own when to ask, based on the risk Daily use once you feel confident
# Démarrer en lecture seule pour cadrer sans rien modifier
claude --permission-mode plan

1.4 Monitoring the Context

Claude operates within a context window of limited size (see 2.2). When it fills up, quality drops and older instructions are discarded. The status line displays the usage in real time; two commands help manage it.

# Voir ce qui occupe le contexte (fichiers lus, conversation, mémoire)
/context

# Compacter la conversation en un résumé pour libérer de la place
/compact

1.5 Undo and Checkpoints

Claude Code maintains a history of internal rollback points. In addition, Git remains the ultimate safety net before any risky operation.

# Ouvrir l'historique des points de restauration (revenir en arrière)
Échap Échap        # double Échap
/rewind            # ou via la commande

# Filet git avant une opération risquée (refacto large, migration)
git stash push -m "checkpoint avant refacto"
git switch -c experimentation   # branche jetable

1.6 Common Mistakes When First Starting to Use It

  • Skipping the complex planning process. Running a broad task without proper scope definition results in a large, inconsistent diff. Use plan mode (Section 5), or the recommended procedure if you need to execute afterward.
  • Approving the diffs without seeing them. The generated code "looks like" good code (section 3). Read it again.
  • Ignoring the context. A session that lasts too long will drift; compact it or restart it.
  • Vague prompts. "Improve this" yields unpredictable results; describe the expected behavior and its scope.
  • Mixing unrelated tasks within the same session: the context becomes contaminated. One session = one intention.
  • Overly broad permissions for convenience, in a non-disposable environment.

2. Execution Model

Understanding how Claude Code works internally allows you to effectively control it. Four concepts are all you need: the agent, the context, the session, and the model.

2.1 Agent vs. Chatbot

The chatbot (the web interface) responds with text. The agent, on the other hand, takes action: it has tools to read and write files, run commands, and perform tests. The practical implication is that an agent can have real-world side effects on your machine and your repository—hence the importance of validations and safeguards.

Conversational Assistant Agent (Claude Code)
Input One question A goal for a project
Action Generates text Read, modify, execute, test
Output A response A change that you approve

2.2 Context Window and Tokens

A token is a fragment of text (≈ ¾ of a word in English). The context window is the number of tokens the model keeps "in mind" for a query: depending on the model, this ranges from 200,000 to 1,000,000 tokens. As a rough guide, 1 million tokens roughly corresponds to 75,000 lines of code, which is insufficient to process a large existing codebase all at once—hence the need for targeted loading strategies when dealing with large codebases (Sections 4 and 7).

Everything in the context is reloaded with each message: the CLAUDE.md, the files you've opened, the conversation history, and your prompt. The more you add, the slower and more expensive it becomes.

2.3 Session Cycle

A session follows a cycle of events that can be hooked into (hooks, Section 4.7). It is this cycle that makes the agent deterministically customizable.

SessionStart        → chargement du contexte (CLAUDE.md, rules, skills découverts)
UserPromptSubmit    → réception de l'intention ; un skill peut s'activer
   ┌─ boucle ────────────────────────────____────────────────────┐
   │  PreToolUse   → avant chaque appel d'outil (read/edit/bash) │
   │  (l'outil s'exécute) et on peut déclencher des outils       │
   │  sur cet état (par exemple pour remplacer un grep par       │
   │  quelque chose de plus puissant                             │
   │  PostToolUse  → après chaque appel d'outil (pareil que pre) │
   └───────────────────────────────────────────────────_─────────┘
Stop                → fin du tour ; les contrôles de qualité passent
PreCompact          → juste avant un compactage du contexte

2.4 Interactive and Non-Interactive Modes

The same engine can be run in two ways. In interactive mode, you interact with it turn by turn. In non-interactive ("headless") mode, a single pass runs without human intervention in the loop—this is what allows it to be integrated into a script, a cron job, or a CI (Section 11).

# Mode interactif (dialogue)
claude

# Mode non-interactif : une passe, pas d'humain dans la boucle
claude -p "corrige le lint du dossier src/ puis committe"

# Sortie structurée, exploitable par un script ou une CI
claude -p "résume les changements du dernier commit" --output-format stream-json

2.5 Model Selection and Costs

There are several models available, each offering a balance between capacity, cost, and speed. The rule of thumb is to use the smallest model that gets the job done. The larger models are reserved for complex analysis, planning, and final decision-making.

Model Profile In/Out Cost ($ / Mtok) Typical Use
Haiku Fast, economical ≈ 0.25 / 1.25 Scanning, bulk reading, simple synthesis
Sonnet Balanced (default) ≈ 3 / 15 Writing Code on a Daily Basis
Opus The most capable ≈ 15 / 75 Complex problems, planning, judge's evaluation
Fable 5 Latest generation high Most Demanding Tasks (to Be Measured)
# Choisir le modèle au lancement
claude --model opus

# Choisir le modèle sur l'app win/mac
cliquer en bas à droite du chat :)

# Changer de modèle en cours de session
/model sonnet

3. Failure Modes of the Generated Code

Before setting up tooling, you need to understand why code generated without any framing fails in production. These failure modes justify each of the constraints outlined in the following sections.

3.1 Empirical Data

Several analyses published in 2025 point to the same conclusion: a significant portion of the code generated by assistants contains defects that go unnoticed during a quick review. The reported orders of magnitude are as follows: approximately 45 % of the analyzed generated code contains at least one security vulnerability, and an increase of approximately +150 % design flaws compared to hand-written code. The problem isn't the number of bugs, but their invisibility: The code looks correct.

3.2 Documented Incidents

Public incidents involving autonomous agents follow a common pattern: an agent has too broad access and carries out a destructive operation without authorization.

  • Deletion of a production database and its backups during an incorrectly configured migration.
  • Deleting a data volume without confirmation results in irreversible loss of business data.
  • On some platforms, a file move operation may fail silently and destroy the files being moved.

3.3 Four Recurring Failures

Failure Symptom Training section detailing the countermeasure
False-positive test result The test turns green but doesn't actually check anything 8 (mutation, golden)
Duplication The agent recreates a component that already exists elsewhere 7 (semantic context)
Deviation from the spec The result resembles the request; edge cases and business rules are ignored 6 (executable spec)
Inconsistent commit state The agent tries to commit even though some tests are failing, claiming that they passed 9 (safeguards), 10 (judge)

3.4 Three Validation Criteria

The entire process boils down to providing verifiable answers to three distinct questions. Most tools only answer the first one.

  1. Is it working? The code runs, the tests pass, and the app launches.
  2. Does this meet the request? The behavior matches the specification, including boundary cases.
  3. Is this the right need? The specification itself addresses a real business need.

4. Configuration and Memory

An agent forgets everything when the session ends. To ensure that it operates consistently from one session to the next, we store the rules and know-how in files. This is the foundation of the entire reliability process.

4.1 Memory Hierarchy

Level Lifetime Contents
Context Volatile (the current turn) Files read, conversation; deleted by /clear or /compact
Session Session Duration History that can be retrieved with --resume
Persistent memory Long-lived Markdown files (CLAUDE.md, skills), .md files documenting the history of problems/issues encountered during the project

4.2 .claude/ Folder Structure and Precedence Rules

All the configuration is stored in a .claude/ folder at the root of the project, complemented by a project CLAUDE.md. You can stack CLAUDE.md by subfolder to tailor the rules.

mon-projet/
├── CLAUDE.md                 # règles projet (chargé à chaque session)
├── .claude/
│   ├── settings.json         # config d'équipe (versionnée)
│   ├── settings.local.json   # config perso (git-ignorée)
│   ├── skills/               # protocoles chargés à la demande
│   │   └── audit-securite/
│   │       └── SKILL.md
│   ├── rules/                # contraintes par chemin de fichier
│   ├── commands/             # commandes /personnalisées
│   ├── agents/               # sous-agents spécialisés
│   └── hooks/                # scripts déclenchés par événement
└── src/
    └── frontend/
        └── CLAUDE.md         # règles spécifiques à ce sous-dossier

Precedence (from the most general to the most specific; the most specific takes precedence): ~/.claude/CLAUDE.md (global, all projects) → CLAUDE.md (project root) → CLAUDE.md subfolders that are traversed. For the settings.json: enterprise → local → project → user.

4.3 CLAUDE.md: the project rules file

CLAUDE.md is not a README (which describes the project to a human): it is a contract which tells the agent how to work. It is injected at the beginning of each session, so it consumes context—keep it concise, prioritize "always/never" rules, and include an index of "where what lives.".

# Projet — Règles permanentes

## Toujours
- Écrire un test en échec avant tout correctif.
- Passer par le design system (aucun composant natif).
- Messages d'erreur en français, conformes WCAG.

## Jamais
- Committer si un test échoue.
- Tracer un email ou un mot de passe dans les logs (RGPD).

## Où vit quoi (index)
- `*.sql`     → charge la rule rls-queries
- `frontend/` → conventions dans frontend/CLAUDE.md
- incident    → gabarit postmortem (skill recording-decisions)

4.4 settings.json and settings.local.json

settings.json contains the team's shared configuration (versioned). settings.local.json contains your personal preferences and permissions (git-ignored). Permissions are specified as "allow" or "deny" for each tool.

{
  "model": "sonnet",
  "permissions": {
    "allow": ["Bash(npm run test:*)", "Bash(git status)", "Edit"],
    "deny": ["Bash(rm -rf*)", "Read(./.env)", "Read(./secrets/**)"]
  }
}

4.5 Skills

A skill is a folder containing a SKILL.md: a step-by-step protocol, loaded only when relevant. The front matter declares when it activates—that's what prevents everything from loading all the time. A skill can include scripts, templates, and data, and can be combined with other skills.

---
name: audit-securite
description: Auditer TLS, secrets, authentification et en-têtes HTTP.
when: l'utilisateur demande un audit de sécurité, ou avant une mise en prod
version: 1.2.0
---

# Audit de sécurité — protocole

1. Scanner les secrets exposés (script ./scan-secrets.sh).
2. Vérifier les en-têtes HTTP de sécurité.
3. Contrôler l'isolation multi-tenant des requêtes.
4. Produire un rapport selon ./gabarit-rapport.md.

4.6 Rules

A rule governs behavior by file path and remains active within its scope. Unlike a skill (a protocol that is executed), a rule is a permanent constraint associated with a file type.

# .claude/rules/rls-queries.md
# Périmètre : **/*.sql, backend/**/repositories/*

Toute requête sur une table multi-tenant DOIT inclure le filtre
d'organisation. Une requête sans clause de scoping est interdite :
elle constitue une fuite de données entre clients.

4.7 Hooks

A hook executes a deterministic script in response to a session cycle event (2.3). It is the key to automation without relying on the model’s "goodwill": formatting after editing, blocking dangerous commands, filtering output to save tokens, and context injection (Section 7).

// .claude/settings.json — formater automatiquement après chaque édition
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/format.sh" }
        ]
      }
    ]
  }
}

Use Case 1: A PreToolUse hook on the input allows you to inject context using a tool like code-review-graph to enhance the analysis before Claude runs, thereby preventing it from issuing unnecessary “grep” commands, for example.

4.8 Commands

/... commands are actions that can be invoked from within the session. Here are a few useful built-in commands, followed by your own commands, which are versioned in .claude/commands/.

Command Role
/plan Thinking Through a Task Without Writing Code (Scoping)
/goal Repeat until a condition is met ("all tests are green")
/loop Run a command at regular intervals
/monitor Monitor a long process until it is complete

A custom command is a simple Markdown file that describes the sequence of steps; it becomes /mon-geste.

# .claude/commands/commit.md
Crée un commit conventionnel pour les changements indexés.
Étapes :
1. Lancer la suite de tests ; abandonner si rouge.
2. Rédiger un message de commit conventionnel.
3. Committer (jamais de --no-verify).

4.9 Plugins and Marketplace

Plugins bundle ready-to-use skills, agents, and hooks that can be installed from a marketplace. They save you from having to rewrite everything yourself.

# Ajouter une marketplace puis installer un ensemble de capacités
/plugin marketplace add anthropics/skills
/plugin install superpowers

# Lister / retirer
/plugin list

5. Step-by-Step Workflow

Requesting an entire feature in a single prompt results in a massive, unreviewable diff that often misses the mark. The solution is to break the work down into steps, each producing a verifiable deliverable.

5.1 From a Single Prompt to a Six-Step Pipeline

We replace "a prompt, I hope" with a chain of six links. The benefit: during the verification step, we can answer the three questions in Section 3.4.

Cadrer → Spécifier → Découper → Exécuter → Vérifier → Tracer
  │         │           │          │           │          │
  besoin   contrat    lots      code+tests   gates+juge  ADR/postmortem

5.2 Command Sequence

In practical terms, each link is represented by a custom command (Section 4.8). Here is a sample chain; the names are your own (and you should define the skills and commands yourself as well)—what matters is the sequence and the artifacts.

Command Link Product
/brainstorming Frame Explicit Intent (Needs Assessment Interview)
/specify Specify Gherkin Specification + NFR
/split Split Deliverables + Dependency Chart
/execute Run Code + tests (in an isolated worktree)
/check Check Verdict from the gates and the judge agent
/trace Trace ADR / postmortem / delivery report

5.3 Artifacts Produced at Each Stage

Each step leaves a written record rather than a verbal exchange that fades away. A good artifact is structured (a format, not prose), controllable (can be reviewed and corrected), verifiable (a gate can evaluate it), and versioned (tracked in Git).

5.4 Feature Cases vs. Bug Fix Cases

The beginning of the pipeline varies depending on the nature of the work; the common trunk then resumes.

  • Feature: We explore the need through interviews (/brainstorming) up to an explicit intention.
  • Bug fix: we require reproducing before fixing. Isolate the issue, write a test that demonstrates the bug (red), fix it until it passes (green), and then assess the impact of the fix on the rest of the system (blast radius).

5.5 Planning

Before writing, we plan in read-only mode (mode plan, section 1.3). The output is a dated, versioned plan, broken down into tasks with their dependencies—a graph that shows what can be executed in parallel.

# plans/2026-06-27-regle-facturation.md

## T1 — schéma de la règle
## T2 — validations          (dépend de T1)
## T3 — tests                (dépend de T1)
## T4 — job CI               (dépend de T2, T3)

6. Executable Specifications

A vague specification leads to endless back-and-forth. An executable specification transforms requirements into tests that the machine can verify on its own.

6.1 The Specification as a Contract

The specification serves as a development-ready ticket: it provides context, explicit acceptance criteria, and non-functional requirements. It is the contract against which the evaluator (Section 10) will assess the work.

6.2 Gherkin Syntax

Gherkin describes behavior in a structured language (Étant donné / Quand / Alors). Each scenario becomes an executable test, centralized with the code.

# specifications/inscription.feature
Fonctionnalité: Validation de l'email à l'inscription

  Scénario: Email valide
    Étant donné un formulaire d'inscription
    Quand je saisis "alice@exemple.fr"
    Alors le formulaire est accepté

  Scénario: Email sans domaine
    Étant donné un formulaire d'inscription
    Quand je saisis "alice@"
    Alors un message d'erreur accessible s'affiche

6.3 Non-Functional Requirements (NFR)

NFRs (performance, accessibility, security, internationalization, design system) are defined early on, in a verifiable and blocking manner. Example of a performance requirement expressed in Gherkin and then translated into a measurable metric.

# Exigence de performance — bloquante en CI
Étant donné un changement qui dégrade le FCP au-delà de 1,5 s
  ou le TBT au-delà de 100 ms
Quand le job lighthouse s'exécute
Alors le job échoue, métriques à l'appui
// lighthouserc.js
module.exports = {
  ci: { assert: { assertions: {
    'first-contentful-paint': ['error', { maxNumericValue: 1500 }],
    'total-blocking-time':    ['error', { maxNumericValue: 100 }]
  }}}
};

The same principle applies to other areas: accessibility ("any information conveyed by color must also be conveyed in another way" → axe rule), security (blocking scan for secrets), i18n ("zero hard-coded strings" → failure if a translation is missing), design system (native components prohibited).

6.4 Structured Writing of Prompts

Structuring the prompt using tags and semantic anchors reduces ambiguity and improves compliance. Context, task, constraints, and acceptance criteria are explicitly separated.

<contexte>
Module de facturation, backend Node, base PostgreSQL multi-tenant.
</contexte>
<tache>
Ajouter le calcul de la TVA par pays.
</tache>
<contraintes>
- Aucune requête sans filtre d'organisation.
- Arrondi au centime, demi vers le haut.
</contraintes>
<criteres_acceptation>
- Tests pour la France (20 %), l'Allemagne (19 %) et un cas exonéré (0 %).
</criteres_acceptation>

7. Semantic Context and Static Constraints

Two issues in Section 3 are resolved as the agent writes the code: the duplication (it recreates what already exists because it doesn't "see" it) and structural discrepancies. The solution: give it a true understanding of the relationships within the code, and constrain the code's form using patterns.

7.1 Language Server (LSP) via Serena

A language server gives the agent the same view as an IDE: go to the definition of a symbol, list all its references, and read compiler diagnostics in real time. This eliminates the need to re-read entire files (saving tokens) and allows errors to be detected without restarting the build. It is exposed via an MCP such as Serena. Note that Claude already includes LSPs (Claude plugins), but these do not adequately cover all languages.

// .mcp.json — exposer un serveur de langage à l'agent
{
  "mcpServers": {
    "serena": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/oraios/serena",
               "serena", "start-mcp-server"]
    }
  }
}

The agent then has access to tools such as go_to_definition and find_references: it knows the relationships in the code before creating, which reduces duplication.

7.2 Why native grep is insufficient

Text search (grep) finds strings, not relationships. Searching for CheckItem lists the occurrences, but does not indicate who imports it, who calls it, which functions depend on it, or whether an equivalent component already exists under a different name. The agent, relying solely on `grep`, reconstructs what it cannot find, which leads to duplication.

7.3 Code Review Graph: Semantic Context Engine

A semantic graph-based context engine indexes the code base into a graph of symbols, references, and dependencies. Based on a change or an intent, it answers the question "Which files are actually relevant here?" much more effectively than a keyword search.

7.4 Context Injection via a PreToolUse Hook

The classic problem with MCP tools: they are offered to the agent, which has to decide whether to call them—and in practice, it quickly falls back on `grep` again. The solution: don't expose a tool, but instead set up a hook that intercepts the prompt, queries the graph, and directly injects the correct files into the context before the model reasons. The model no longer has anything to choose: the context is already there, and grep becomes unnecessary (and can be limited elsewhere).

// .claude/settings.json — injecter le contexte du graphe à chaque prompt
{
  "hooks": {
    "UserPromptSubmit": [
      { "hooks": [
        { "type": "command",
          "command": ".claude/hooks/inject-graph-context.sh" }
      ]}
    ]
  }
}
# .claude/hooks/inject-graph-context.sh
# Interroge le graphe sémantique et renvoie les fichiers pertinents,
# qui seront ajoutés au contexte (additionalContext) avant le raisonnement.
PROMPT="$(cat)"
code-review-graph related --query "$PROMPT" --top 8 --format paths

7.5 Constraints by AST pattern (ast-grep)

The AST (syntax tree) represents the code as a structure, not as text. ast-grep allows you to prohibit or enforce structural patterns, which are displayed as diagnostics in the editor and cause build failures during CI.

# Interdire les tests focalisés (.only) — ast-grep
id: no-focused-test
language: typescript
rule:
  any:
    - pattern: it.only($)
    - pattern: describe.only($)
    - pattern: test.only($)
message: "Test focalisé interdit : il masque les autres tests."
severity: error

Other typical uses: preventing the removal of a column during a migration (DROP COLUMN), require a feature flag for every new page, prohibit opening a transaction without a security context, and enforce architectural boundaries.

In addition, static checks catch what the agent misses: duplicate detection (an equivalent component already exists), removal of dead code, and rejection of non-internationalized strings (hard-coded text). For precise, targeted searches, ripgrep (rg) remains the most accurate tool to use over the generic `grep`.

8. Testing Strategy

A false positive test result (Section 3.3) is the most dangerous failure: a green test that does not actually verify anything creates a false sense of security, which is worse than having no test at all. This section specifically addresses this risk.

8.1 TDD: Test-First Development

First, you write a test that fails (red), proving that the expected behavior isn't there yet, and then you code until it passes (green). For a bug, the red test reproduces the defect; for a feature, it defines the acceptance criteria.

1. RED    — écrire un test qui échoue (le comportement n'existe pas)
2. GREEN  — écrire le minimum de code pour le faire passer
3. REFACTOR — nettoyer sans casser le test

8.2 Reference Datasets (Golden Datasets)

For complex outputs (reports, transformations, renderings), we freeze a validated reference output. Any future deviation causes the test to fail: this serves as a non-regression test against the exact result, and the reference is protected against any unintended changes.

8.3 Detecting Flaky Tests

A test that passes once doesn't prove anything if it depends on time or a non-deterministic order. We rerun the tests numerous times (overnight) to detect those that alternate between green and red, and we automatically open a ticket once a threshold is exceeded.

# Relancer la suite N fois et repérer les alternances (exemple)
for i in $(seq 1 50); do npm test -- --reporter=dot || echo "ÉCHEC run $i"; done

8.4 Mutation Tests

The mutation test directly addresses the "false green" issue: modifications are intentionally introduced into the code (mutants); if a test remains green despite the mutation, it means it provides no protection. These tests are generally run at night (as they are costly).

# Tests de mutation (nightly) — exemple Stryker (JS/TS)
npx stryker run
# Mutant survivant = test qui ne détecte pas le changement -> à renforcer

8.5 The Page Object Pattern and Choosing the Test Level

For E2E (agent-driven browser testing), we separate the page description (selectors) from the test logic using the Page Object pattern—otherwise, the suite becomes unmaintainable. The test suite is a software application in its own right, subject to the same engineering requirements as the application.

9. Permissions, Environments, and Safeguards

The incidents described in Section 3.2 all stem from excessive permissions. We therefore explicitly define what the agent may do, where, and to what extent.

9.1 Matrix of Rights by Environment

The guiding principle: full access during development (disposable), conditional access during pre-production, and read-only access during production.

Action Dev Staging Prod
Write & Iterate ✓ free ✓ via PR ✗
Run commands ✓ under gate ✗
Deploy ✓ auto human validation ✗ never
Accessing data ✓ disposable ✗ ✗
Read signals & logs ✓ ✓ ✓

9.2 Tool Permissions and Allowlists

Permissions are specified per tool in settings.json (4.4). We restrict each agent to only what is strictly necessary (allowlist) and explicitly reject anything dangerous.

{
  "permissions": {
    "allow": ["Bash(npm run test:*)", "Bash(git*)", "Edit", "Read"],
    "deny":  ["Bash(rm -rf*)", "Bash(git push --force*)",
              "Read(./.env)", "Read(./secrets/**)"]
  }
}

9.3 Secure Access to Production Data via a Custom MCP

This is a technique for providing secure access to production: an MCP server is placed in the middle. The agent calls the tool without holding any credentials; the MCP holds the server-side access credentials, queries the source (logs, metrics), and returns only filtered data.

Agent  →  MCP  →  API logs/metrics  →  Prod
(0 credential)   (détient les accès, filtre la donnée)

↩ ne remontent que les données filtrées ; les secrets restent côté serveur.

9.4 Git Worktrees and Agent Isolation

To run multiple tasks in parallel without the agents getting in each other's way, we give each one a Git worktree: a dedicated working directory, with one branch per task. We can even ask Claude to manage them on its own, of course!

# Un worktree isolé par ticket
git worktree add ../projet-ticket-265 -b ticket-265
# ... l'agent travaille dans sa "chambre" ...
git worktree remove ../projet-ticket-265   # nettoyage après merge

9.5 Execution Limits

We cap resources to prevent things from getting out of hand: the number of concurrent MRs (beyond that, conflicts skyrocket), the number of worktrees (disk space, compilation), and secret scans before every push.

# .claude/hooks/limite-worktrees.sh — refuser au-delà de 6 worktrees
COUNT=$(git worktree list | wc -l)
if [ "$COUNT" -ge 7 ]; then
  echo "Limite de worktrees atteinte (6)." >&2
  exit 2   # bloque l'action et réengage l'agent
fi

9.6 Multi-stage CI pipeline

The CI extends local gates: everything is blocking (except for night jobs). A typical breakdown into successive stages, from the local environment to runtime.

Step Inspections
Pre-commit (local) format, lint, quick tests
Security (CI) secrets, prohibited patterns, vulnerabilities in dependencies, image scanning
Migration no breaking changes, backward compatibility
Front performance, accessibility, bundle size, visual regression, i18n
Build & Deploy image, deployment, smoke test
Nightly Flaky detection, mutation testing

9.7 Cost Optimization

Three simple strategies reduce token usage without sacrificing quality: routing read/scan tasks to Haiku, compacting the context at the right times, and marking stable portions of the prompt for caching.

# Lecture massive / synthèse : modèle économique
/model haiku
# Compacter dès qu'une sous-tâche est finie
/compact

10. Automated Review and Traceability

Once the code has been written and tested, it is first reviewed by the machine and then, as a last resort, by a human, and we track the decisions made so we don't repeat the same mistakes.

10.1 Independent Adjudicator

The implementation and the specification are submitted, and a judge makes the final decision. This judge is independent: It only looks at the Gherkin (what was requested) and the modified code, and returns a binary verdict. It verifies that the functional test matches the spec, that it runs, and that it covers the criteria.

Entrée : spec Gherkin + diff du code
Sortie : VALIDATED  (conforme à chaque critère)
         FAILED     (+ critères manquants ou non couverts)

10.2 Automated code review and final human review

A second agent, based on a more capable model, reviews the content just as a human proofreader would. Locally, an enhanced review command (/ultrareview) does the initial processing before the CI. But the final decision is still made by a human.

10.3 ADR: Architecture Decisions (in .md files)

An ADR (Architecture Decision Record) documents decisions in an .md file: the context, the choice made, and its implications. It serves as the agent’s lasting record of key decisions, to be reviewed and re-evaluated regularly.

# ADR 0042 — Isolation multi-tenant par Row-Level Security
Date : 2026-06-27
Statut : accepté

## Contexte
Plusieurs organisations partagent la même base ; une requête sans
filtre a déjà provoqué une fuite inter-tenant.

## Décision
Activer la RLS au niveau base ; tout accès passe par un contexte
d'organisation explicite.

## Conséquences
+ Fuite inter-tenant structurellement impossible.
− Toute requête doit fournir le contexte ; surcoût léger.

10.4 Postmortems (also .md files) and recurrence thresholds

Postmortems document an incident: root cause, corrective action, follow-up actions, and accepted debt. We don’t wait indefinitely for them; we trigger them based on thresholds, to turn a recurring problem into a process improvement.

Recurrence Action
1 to 2 fixes nothing in particular
≥ 3 corrections on the same topic postmortem triggered
≥ 5 fixes Mandatory root cause analysis
3+ postmortems on the same topic meta-postmortem: we evaluate the method, not the bug

10.5 Delivery Reports (MR)

The delivery report (Merge Request) summarizes what has been done, the scope that has been maintained, and the test plan that has been checked off. In a standardized format, it is then used to link a deployment to an investigation (section 11).

## Résumé
Unifie le widget Checks via le composant partagé CheckItem.

## Périmètre préservé
Le groupement existant est conservé ; seul le rendu des items change.

## Plan de test
- [x] tests unitaires
- [x] E2E (parcours principal)
- [ ] revue visuelle (humaine)

11. Non-Interactive Execution and Orchestration

Once the safeguards are in place, we can increase autonomy: trigger the agent without typing anything, then incorporate it into a deterministic workflow that controls it.

11.1 Headless Mode and Event-Driven Triggering

The mode claude -p (2.4) executes a pass without human intervention. When you link it to an event, you no longer have to press Enter—the event does it for you.

# Déclenché par un événement plutôt qu'au clavier
claude -p "corrige le ticket #412 puis ouvre une MR" --output-format stream-json

# Déclencheurs typiques :
#   - hook PostToolUse -> écrit une métrique
#   - cron toutes les 5 min -> dépile le backlog
#   - webhook CI -> relance une investigation

11.2 Deterministic workflow controlling the agent

Two ways to link an agent and a workflow. Putting the workflow in the agent (the entire protocol within skills) makes the order fragile: the agent compacts, loses its memory, and drifts. The opposite is more robust: it is the workflow that calls the agent, one step at a time. The deterministic code controls the sequence; the agent performs only one step.

11.3 Daemon: Autonomous Cycle and Safeguards

A daemon continuously processes the backlog and runs a short cycle for each ticket. Safeguards limit the system’s autonomy; merging remains a human action.

// Cycle autonome (run.ts), piloté par le daemon
preflight   → tout doit être vert au départ
plan        → fixer le périmètre
execute     → un pas d'implémentation
review      → juge LLM ; si rouge, on reprend, jamais de merge auto

// Garde-fous : max 2 agents simultanés ; 3 échecs sur une tâche = pause ;
// le merge est déclenché par l'humain, pas par le daemon.

11.4 Parallel Backlog Reduction

An orchestration command (e.g.,. /autopilot) takes tickets that are ready for development, delegates several of them in parallel (one worktree per ticket, section 9.4), and then lets you review the MRs. Delegation is explicit and capped; it’s not a situation where "one agent calls everyone.".

11.5 Improvement Cycle

The agent is part of the system it maintains: it, too, is monitored (every tool call, every failure). Regular analysis distinguishes useful work from friction = toil (meaningless repetitive actions, even when scripted) + retries (running a step again in the hope that it will succeed). What happens often enough becomes a script or a rule.

Continuously measured signal Objective
Time to Detect a Bug in Production decrease
Regression Rate by Delivery decrease
Percentage of automatically suggested corrections increase
Friction (toil + retries) per week decrease

11.6 Migrating an Existing (Legacy) Code Base

Building on a foundation that’s already been "vibe-coded" for months, we proceed as we do with any legacy project, in stages—we never rush through an unsecured area.

  1. Understanding: Identify key areas and actual business needs.
  2. Secure: Run characterization tests (green first).
  3. Cut out: Isolate a seam; no big bang.
  4. Lock: gates (lint, tests, review); red means blocked.
  5. Speed up: Increase autonomy in the area that is now secure.

12. Reference

12.1 Command Table

Command Effect
/plan Setting Up a Task Without Writing Code
/goal Iterate until a condition is met
/loop Run periodically
/monitor Monitoring a Long-Running Process
/context Check the context's occupancy
/compact Summarize the conversation
/rewind Return to a checkpoint
/model Change the model
/plugin Manage Plugins

12.2 Keyboard Shortcuts

Shortcut Effect
Shift+Tab Cycle through permission modes
Échap Pause the current action
Échap Échap Open History / Go Back
@ Reference a File
/ Execute a command
# Add a note to memory (CLAUDE.md)

12.3 Troubleshooting

Symptom Probable cause Action
Answers That Drift Away Saturated context /compact or restart the session
A skill doesn't trigger when: / description too vague Specify the activation condition
The agent keeps re-reading a file over and over Outdated document in memory Update the source file and the CLAUDE.md
Too many permission requests Overly strict mode Adjust the allow/deny settings or switch to auto
High cost Large model, complex context Route to Haiku, /compact, cache

12.4 Daily Checklist and Confidence Calibration

  • Start in mode plan to ensure alignment; do not code until the plan has been approved.
  • Review every change; never accept anything blindly.
  • A red test before any fixes; no commits with a "false green" status.
  • Monitor the context; compact at subtask transitions.
  • Reserve mandatory human review for sensitive areas (multi-tenant SQL, data).
  • Track decisions (ADR) and incidents (postmortem) in real time.

Confidence Calibration: The riskier the environment (data, multi-tenant, production), the more human and systematic the verification must be. The more disposable it is (development worktree), the more we can delegate. Trust is managed on a per-area basis, not globally.

12.5 Summary of the Standard Configuration

Layer Role Examples
Installed MCPs Capacities connected once Serena (LSP), managed browser, logs/metrics access
Skills On-Demand Protocols brainstorming, debugging, testing, audit-*
Rules Constraints per file, always active commits, minimal code, secure logs, rls-queries
Hooks Deterministic automations format, scan secrets, context injection
The engine Deterministic Shortcuts (in Code) daemon, ticket dispatch, worktrees, metrics