# Teacher Guide — Session 6: Claude Code & CI/CD

**Program:** Applied AI — Advanced Level (certification preparation *Claude Certified Architect*)
**Instructor:** Yann Isola
**Duration:** 2 hours 30 minutes (150 minutes)
**Modules covered:** Chapters 5 and 13 of the reference guide — Claude Code, integrated tools, continuous integration

---

## 1. Session overview

### Educational objectives

At the end of this session, each participant should be able to:

1. **Define Claude Code**: An *agentic* coding assistant that runs in the terminal, capable of reading, modifying, and executing code autonomously within a controlled permissions scope.
2. **Structure an effective `CLAUDE.md` file**: project overview, conventions, common commands, known pitfalls (gotchas) — and explain why this file is *the #1 lever* for output quality.
3. **Configure directory `.claude/`**: `settings.json` (tools authorized via `allowedTools`), custom commands (`.claude/commands/`), hooks.
4. **Master the permissions model**: allow/deny by tool, auto-accept patterns, principle of least privilege applied to a coding agent.
5. **Design a hooks system**: lifecycle events (`PreToolCall`, `PostToolCall`, `Notification`, `Stop`) for custom automation — auditing, guardrails, notifications.
6. **Execute Claude Code in headless mode** (without interface, non-interactive) with `--print` / `-p` to integrate it into a CI/CD (Continuous Integration / Continuous Deployment) pipeline.
7. **Design three CI/CD integration patterns**: automatic PR review (Pull Request, merge request), test generation, documentation update.
8. **Mapping Built-in Tools** (Chapter 13): `Read`, `Write`, `Edit`, `MultiEdit`, `Bash`, `Glob`, `Grep`, `LS`, `TodoRead`, `TodoWrite`, `WebFetch`, `mcp__*` — and associate each tool with its risk level and permission requirement.
9. **Manage costs**: command `/cost`, prompt caching in long sessions, `/compact` to compress the context.

### Prerequisites

- Sessions 1 to 5 of the Advanced level (in particular: agent architecture, tool calling, MCP — Model Context Protocol, model context protocol).
- Comfortable with the command line (terminal, bash shell or equivalent).
- Notions of Git and CI/CD: know what a PR, a pipeline, a runner is.
- Ideally: have already installed Claude Code (`npm install -g @anthropic-ai/claude-code` ⚠ *check the current installation command before the session, it may change*).

### Certification positioning

This session covers a **heavily weighted** area in the *Claude Certified Architect* exam: the configuration of agentic environments and their industrialization. Typical exam questions cover:
- the choice of tools to authorize in a given context (least privilege scenarios);
- the order and semantics of hooks;
- the difference between interactive mode and headless mode;
- the canonical structure of a `CLAUDE.md`.

Emphasize to participants: **the exam tests architectural judgment, not memorization of flags**. Each part of the course ends with a “certification standard question” — use them.

### Materials needed- Video projector + slides (`slides/slides.md`).
- Interactive web page (`webpage/index.html`) — **offline**: `CLAUDE.md` builder, CI/CD pipeline designer, permissions configurator.
- Worksheets (`exercises/exercises.md`).
- Quiz (`quiz/quiz.md`).
- **Highly recommended:** each participant with a terminal and Claude Code installed. Plan a cloned practice Git repository in advance (any small project with tests will do).

### Central message of the session

> “Claude Code is not a chatbot that talks about code: it is an **agent** that acts on your deposit, within a scope that **you** define. The `CLAUDE.md` file is its contextual brain, `settings.json` is its cage, the hooks are your surveillance cameras, and headless mode makes it an employee of your pipeline. »

Repeat this metaphor in four parts (brain / cage / cameras / employee) — it structures the entire session.

### Narrative thread

The entire session is based on **a single common thread project**: `facturation-api`, a fictitious invoicing API in Python with pytest tests. Each concept is illustrated on this same project:
- The `CLAUDE.md` describes `facturation-api`.
- Permissions are calibrated for `facturation-api`.
- CI/CD pipeline reviews PRs of `facturation-api`.

Repetition of the same context anchors concepts and prepares for the certification scenario questions.

---

## 2. Unfolded minute by minute

| Schedule | Duration | Sequence | Support |
|---|---|---|---|
| 0:00 – 0:05 | 5 mins | Home, reminder Session 5, objectives, certification issue | Slides 1–3 |
| 0:05 – 0:25 | 20 mins | **Part A — Claude Code: Anatomy of a Terminal Agent** | Slides 4–8 + live demo |
| 0:25 – 0:45 | 20 mins | **Part B — CLAUDE.md: the contextual brain** | Slides 9–12 + web builder |
| 0:45 – 1:05 | 20 mins | **Exercise 1: Write a CLAUDE.md** | Worksheet + web builder |
| 1:05 – 1:10 | 5 mins | ☕ Short break | — |
| 1:10 – 1:30 | 20 mins | **Part C — Permissions & integrated tools: the cage** | Slides 13–18 + web configurator |
| 1:30 – 1:45 | 15 mins | **Part D — Hooks: surveillance cameras** | Slides 19–22 |
| 1:45 – 2:00 | 15 mins | **Exercise 3 (getting started): Design a hooks system** | Worksheet |
| 2:00 – 2:15 | 15 mins | **Part E — Headless mode & CI/CD: the pipeline employee** | Slides 23–27 + web pipeline designer |
| 2:15 – 2:25 | 10 mins | **Exercise 2 (scoping): CI/CD pipeline with Claude Code** — launching, finishing at home | Worksheet |
| 2:25 – 2:30 | 5 mins | Quick quiz + Exit Tickets + announcement Session 7 | Slides 28–30 |

**Flexibility note:** Exercise 2 (complete CI/CD) is the longest — it is designed to be *framed in session and completed at home*. If you fall behind, compress Part D to 10 minutes (only show `PreToolCall` and `Stop`), but **never** sacrifice Part C (permissions): this is the heart of the security model and the most tricky subject on the exam.

---

## 3. Detailed teaching notes by sequence

### 0:00 – 0:05 | Reception and framing

**What to say:**

> “So far, you have designed agents *in* applications. Today, we turn the tables: the agent is your colleague at the terminal. It reads your code, modifies it, runs your tests. And at the end of the session, it will work on its own in your CI/CD pipeline, at night, while you sleep.The question of the session is not “is it possible?” — it’s “how to stay in control?”. »

Announce the certification issue: this chapter weighs heavily on the exam. Distribute the plan.

---

### 0:05 – 0:25 | Part A — Claude Code: Anatomy of a Terminal Agent

**Key concepts:**

1. **Definition.** Claude Code is a command-line agentic coding wizard. “Agentic” means: it doesn't just respond, it **loops** — reads files, suggests changes, executes commands, observes results, corrects. This is the agentic loop of Session 3, embodied in the terminal.

2. **Starting a project.** The `/init` command inspects the repository and **generates a first `CLAUDE.md`** automatically. Emphasize: this is a *draft* — a good architect always reworks it (transition to Part B).

3. **Natural language interaction.** We do not type rigid commands: “fixes the VAT calculation bug in `invoice.py` and adds a test” is a valid instruction. Claude Code plans, opens the correct files (via `Glob`/`Grep`), edits (via `Edit`/`MultiEdit`), tests (via `Bash`).

4. **Multi-file edits.** Unlike classic autocompletion, Claude Code reasons at the scale of the repository: a function renaming can affect 12 files in a single task.

5. **Built-in Slash commands:**
- `/init` — generates the initial `CLAUDE.md`;
- `/compact` — compresses conversation history to free context (automatic summary);
- `/cost` — displays token consumption and session cost;
- `/review` — launches a code review;
- **custom** commands in `.claude/commands/*.md` — a Markdown file = a command (e.g. `.claude/commands/deploy-check.md` becomes `/deploy-check`).

**Live demo (8 min):** on project `facturation-api`, run `claude`, then `/init`, show the generated `CLAUDE.md`. Then ask in natural language: "list the test files and tell me what is not covered." Show the permission requests that appear — it's the perfect teaser for Part C.

**Educational pitfall:** some participants will think that Claude Code “sees” the entire repository all the time. False: it **crawls** on demand (via `Glob`, `Grep`, `Read`). The context is built incrementally — hence the importance of `CLAUDE.md` which is loaded systematically.

**Certification type question:** “A developer notices that Claude Code ignores the team's naming conventions. What is the first corrective action? » → Document the conventions in `CLAUDE.md` (not: repeat the instruction at each prompt, nor: change model).

---

### 0:25 – 0:45 | Part B — CLAUDE.md: the contextual brain

**Key concepts:**

1. **What it is.** A Markdown file at the root of the project, **automatically loaded at the start of each session**. It is the project equivalent of the system message: standing instructions, versioned with the code, shared by the entire team.

2. **Canonical structure (to be noted):**
- **Project overview** — what, for whom, technical stack. 3 to 5 lines.
- **Conventions** — code style, naming, folder structure, comment language.
- **Common commands** — how to run tests, linter, build, local server.*Accurate and copyable.*
- **Known gotchas** — “module X has a misleading API”, “never touch the folder`migrations/`by hand", "integration tests require Docker".

3. **Why it works.** Every instruction in`CLAUDE.md`saves dozens of downstream corrections. Analogy: this is the onboarding document for a new developer — except that this developer rereads it *every session*, in its entirety, without ever forgetting it.

4. **Anti-patterns to denounce:**
- The`CLAUDE.md`of 800 lines: it consumes context in each session and dilutes critical instructions. Target: **less than 150 lines**, dense.
- Generalities (“write clean code”): zero value. Each line must be *project specific*.
- The outdated file: commands that no longer work = the agent loses confidence... no, correction: *you* waste time, because the agent executes broken commands. Treat`CLAUDE.md`like code: review, update, accountability.

5. **Hierarchy.** There can be a`CLAUDE.md`global (user level,`~/.claude/CLAUDE.md`) and`CLAUDE.md`by subfolder for monorepos. The more specific complements the more general.

**Activity (5 min):** project the **CLAUDE.md constructor** of the web page. Fill it live with the room for`facturation-api`. Generate the file, critique it together: what is missing? What is too vague?

**Certification type question:** “Which section of CLAUDE.md has the most impact on reducing order fulfillment errors? » → Exact common orders (agent does not have to guess`npm test`vs.`pnpm test`vs.`make test`).

---

### 0:45 – 1:05 | Exercise 1 — Write a CLAUDE.md

See worksheet. Participants write a`CLAUDE.md`complete for a project described in the statement (or their own project if they have one). The web builder can serve as a scaffold, but require a manual densification pass.

**Correction criteria (announce them):**
- The 4 canonical sections present.
- Copy-paste commands, no pseudo-commands.
- At least 2 real and specific gotchas.
- Less than 100 lines.

**Circulation:** locate the “generic” files (which could describe any project) and challenge: “if I give this file to another pair, will they know that it is not their project? If not, everything has to be rewritten. »

---

### 1:10 – 1:30 | Part C — Permissions & integrated tools: the cage

**This is the most important part of the session.** Slow down.

**Key concepts:**

1. **The catalog of integrated tools (Chapter 13).** Have the table built with the room, by increasing risk level:| Tool | Function | Risk | Typical permission |
|---|---|---|---|
| `Read` | Read a file | Low (possible info leak) | Often self-accepted |
| `LS` | List a directory | Low | Self-accepted |
| `Glob` | Find files by pattern | Low | Self-accepted |
| `Grep` | Search in contents | Low | Self-accepted |
| `TodoRead` / `TodoWrite` | Manage internal task list | Negligible | Self-accepted |
| `WebFetch` | Recover a web page | Medium (exfiltration, unreliable content) | Validation recommended |
| `Write` | Create/overwrite file | High | Validation |
| `Edit` / `MultiEdit` | Edit one/multiple files | High | Validation or targeted reasons |
| `Bash` | Execute a shell command | **Review** | Systematic validation or fine whitelist |
| `mcp__*` | External MCP tools (Model Context Protocol servers) | Variable — server dependent | On a case-by-case basis |

2. **The allow/deny pattern.** In `.claude/settings.json`, the key `allowedTools` defines what is allowed without confirmation. The granularity goes down to **order reason**: `Bash(npm test)` allows exactly `npm test`, `Bash(git diff:*)` allows variants of `git diff`. Anything that is not explicitly allowed triggers an interactive confirmation request — or a **headless refusal** (crucial point for Part E).

3. **Canonical example to project:**```json
{
  "permissions": {
    "allow": [
      "Read", "Glob", "Grep", "LS",
      "Bash(npm test:*)",
      "Bash(git diff:*)",
      "Bash(git log:*)",
      "Edit"
    ],
    "deny": [
      "Bash(rm:*)",
      "Bash(git push:*)",
      "WebFetch"
    ]
  }
}
```⚠ *The exact syntax of the settings file changes with versions of Claude Code — check the official documentation before the session and adapt the slide if necessary. The **logic** (explicit allow, priority deny, patterns by prefix) is stable and is what is tested in certification.*

4. **Architect principle:** `deny` always wins over `allow`. We think in three circles: *free reading* (exploring costs nothing), *monitored writing* (validated or targeted modifications), *locked execution* (the shell is a total attack surface - unconstrained `Bash` is equivalent to giving SSH access).

5. **What Claude Code can NOT do:** exit the working directory without permission, execute anything without going through its declared tools, hide an action (any tool call is visible and logable via hooks). But remember attack vector #1: **prompt injection** via the content read (a malicious code comment, a trapped `WebFetch` page can contain instructions). Permissions are the defense: even manipulated, the agent cannot execute what is refused.

**Activity (5 min):** web page permissions configurator. Scenario: “Claude Code must do code review in CI, read-only + comments”. The room chooses the tools, the page generates the `settings.json`. Expected response: Read/Glob/Grep/LS only, everything else in deny.

**Certification type question:** “A CI pipeline uses Claude headless code to generate tests. What minimum set of tools should be allowed? » → Read, Glob, Grep, LS (exploration), Write or Edit (create test files), `Bash(pytest:*)` or equivalent (check that the tests pass). Nothing else. Every superfluous tool is a wasted point.

---

### 1:30 – 1:45 | Part D — Hooks: surveillance cameras

**Key concepts:**

1. **Definition.** A hook is a **your own** script that Claude Code automatically executes at specific points in the lifecycle. Unlike the prompt (which the model can misinterpret), a hook is **deterministic**: it always executes, exactly as written.

2. **The four events:**
- `PreToolCall` — *before* each tool call. Can **block** the call (guardrail). Ex.: refuse any `Bash` containing `DROP TABLE`.
- `PostToolCall` — *after* each tool call. Do not block, but observe and react. Ex.: launch the code formatter after each `Edit`.
- `Notification` — when Claude Code needs human attention (permission request, question). Ex.: send a Slack message.
- `Stop` — when the agent completes its response/task. E.g.: play a sound, trigger the rest of the pipeline, archive the session log.

3. **Architect use case (the three families):**
- **Guardrails** (PreToolCall): *inviolable* security policies, complementary to permissions — permissions say *which* tools, hooks say *what uses* of these tools.
- **Quality automation** (PostToolCall): automatic lint/format, checking that modified files compile.
- **Observability** (all): complete audit log of each agent action — a frequent requirement in a regulated environment. Link to participant context: In a bank, this log is what the auditor will ask for.

4.**Blocking semantics:** a `PreToolCall` hook that exits with a failure code (and/or message) **prevents the call** and returns the explanation to the model, which can adjust its strategy. It's a dialogue, not just a wall.

**To say:**

> “Remember the division of labor: `CLAUDE.md` = what the agent *should* do (persuasion). Permissions = what it *can* do (capacity). Hooks = what happens *when he acts* (control and reaction). A certified architect knows how to choose the right level: you don't put in the prompt what should be a hook, and you don't put in a hook what should be a permission. »

**Certification type question:** “The security team requires that no command containing `curl` to an external domain is ever executed, even if the user approves it. Prompt, permission or hook? » → Hook `PreToolCall` (inspection of command content + unconditional blocking). A `deny Bash(curl:*)` permission is also defensible — excellent opportunity to debate: the permission blocks *all* curl, the hook allows fine-grained logic (internal curl OK, external no).

---

### 1:45 – 2:00 | Exercise 3 (getting started) — Design a hook system

See worksheet. Work on paper/publisher: design the hooks for a regulated environment. No need to execute — the exercise evaluates the **design**: choice of event, filtering logic, action.

**Circulation:** the classic mistake is to put everything in `PreToolCall`. Push to justify: “why this control *before* rather than *after*? What does it cost in latency? »

---

### 2:00 – 2:15 | Part E — Headless & CI/CD mode: the pipeline employee

**Key concepts:**

1. **Headless mode.** `claude -p "instruction"` (or `--print`) executes the task **without interactive interface**: Claude Code receives the instruction, acts, prints the result, ends. Exit code usable by the pipeline.

2. **Critical consequence:** in headless mode, **no one clicks on "authorize"**. All permissions must be pre-granted in `settings.json` (or via command line permission flags). An unauthorized tool = action refused = potentially incomplete task. Hence the golden rule: *calibrate headless permissions to what is strictly necessary for the task, and nothing more* — it is an agent without human supervision.

3. **The three integration patterns to know for certification:**

**a) Automatic PR review.** Trigger: opening/updating a PR. The job checks out the code, launches `claude -p "Révise ce diff : bugs, sécurité, conventions du CLAUDE.md. Formate en Markdown."` with **read-only** permissions + `Bash(git diff:*)`. The output is posted as a PR comment via the forge API (GitHub/GitLab). *Architect's point: the AI review complements the human review, it does not replace it — configure it as non-blocking at first.*

**b) Test generation.** Trigger: coverage drop or manual request. Permissions: read + `Write` (limited to the `tests/` folder if possible via hook!) + `Bash(pytest:*)`. The job commits the tests to a branch and opens a PR — **never direct push to main**. *Here is a perfect permission + hook marriage: `Write` authorized, hook `PreToolCall` which checks that the path starts with `tests/`.*

**c) Documentation update.** Trigger: merge on main. Claude Code compares code and doc, updates outdated sections, opens a doc PR.Permissions: read + `Edit` on `docs/`.

4. **Cost management in CI:**
- Each run consumes tokens: follow `/cost` interactively, and in CI, cap (lap limit, job timeout).
- **prompt caching** (caching of prompt prefixes) greatly reduces the cost of long sessions: the `CLAUDE.md` and the stable context are cached, only new content is billed at full price. ⚠ *Cache prices and reduction rates are changing — give the order of magnitude (“the cached token costs a fraction of the normal token”) and refer to the current price list.*
- `/compact` in long interactive session: summarizes the history to avoid context congestion (and the degradation of quality that goes with it).

5. **Anti-pattern to nail to the wall:** `--dangerously-skip-permissions` (or any “allow all” equivalent) in a pipeline connected to production secrets. If you have to use it, it's in a disposable container, no outgoing network, no secrets. An architect who puts “allow everything” in a CI runner with AWS credentials has failed his certification *and* his security audit.

**Activity (5 min):** web page pipeline designer. Build the PR flow live → review Claude → tests → deployment, configuring each step (permissions, blocking/non-blocking).

**Certification type question:** “In headless mode, Claude Code stops without finishing because a tool is refused. Most likely cause? » → Permission missing in `settings.json`: in headless there is no interactive confirmation possible.

---

### 2:15 – 2:25 | Exercise 2 (scoping) — CI/CD pipeline

Start exercise 2: reading the statement together, choosing the pattern in pairs, writing the workflow skeleton. The finishing (complete YAML workflow + settings.json + hook) is done at home. Announce that the productions will be reread at the start of Session 7.

---

### 2:25 – 2:30 | Closing

- **Quick quiz**: 3 oral questions taken from the quiz (Q2, Q5, Q9 recommended).
- **Exit ticket**: each participant writes *one* session architecture decision that they would apply tomorrow in their organization.
- **Announcement Session 7** and reminder: Exercise 2 to be completed, it will be reread.

---

## 4. Attendee Frequently Asked Questions (and Answers)

**“Claude Can Code destroy my repository? »**
With default permissions: no — write and execute actions require confirmation, and Git protects you (everything is reversible before push). With “allow all” and without Git: yes, like any script you give the keys to. The architect's response: it's not a question of confidence in the model, it's a question of permission scope.

**“Why not put everything in CLAUDE.md rather than in hooks? »**
Because `CLAUDE.md` is *persuasion*: the model follows the instructions with a very high probability, but not a guarantee. A hook is *code*: it executes 100%. Security policies go into hooks/permissions; preferences and conventions go to `CLAUDE.md`.

**“Is headless mode the same binary? »**
Yes — same tool, flag `-p`/`--print`. What changes: no interactivity, therefore no confirmations, therefore mandatory pre-configuration.

**“What are AI PR reviews worth?” »**
Excellent for: obvious bugs, convention inconsistencies, oversights (error handling, edge cases), documentation errors.Limited for: business relevance, choice of background architecture. Hence the recommendation: non-blocking, in addition to humans.

**“What about MCP tools (`mcp__*`)? »**
Each connected MCP server exposes its tools under the prefix `mcp__nomserveur__nomoutil`. They fit into the same allow/deny model. Architect's rule: audit each MCP server as a security dependency (who wrote it? what does it really do?) before authorizing it — that was the focus of Session 5.

---

## 5. Scale and summary answers

- **Exercise 1 (CLAUDE.md)**: /10 — 4 sections (4 pts), exact commands (2 pts), 2+ specific gotchas (2 pts), conciseness < 100 lines (2 pts).
- **Exercise 2 (CI/CD)**: /15 — correctly chosen and justified pattern (3 pts), functionally plausible workflow (4 pts), `settings.json` with least privilege (4 pts), failure/cost management (2 pts), no crippling security fault (2 pts). **Critical fault = “allows everything” with secrets: caps the score at 7.**
- **Exercise 3 (hooks)**: /10 — good event for each need (4 pts), realistic filtering logic (3 pts), prompt justification vs permission vs hook (3 pts).
- **Quiz**: /10, corrected in the appendix to the quiz. Indicative certification preparation threshold: **8/10**.

---

## 6. To go further (to be mentioned at the end)

- Official documentation Claude Code (reference of settings, hooks and flags — to consult *up to date*, the tool evolves quickly ⚠).
- Course reference guide, chapters 5 and 13.
- Bonus exercise: plug a `Notification` hook into the team's messaging channel and measure the average reaction time to permission requests.