Detects friction patterns in Claude Code sessions — repeated corrections, CLAUDE.md rules not respected, skills not invoked. Launches parallel Haiku agents on the JSONL files, consolidates with Sonnet. Integrated into /closeweek.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Friction Scan?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/zoomma1-friction-scan)
---
name: friction-scan
description: Detects friction patterns in Claude Code sessions — repeated corrections, CLAUDE.md rules not respected, skills not invoked. Launches parallel Haiku agents on the JSONL files, consolidates with Sonnet. Integrated into /closeweek.
---
# Skill: /friction-scan
Analyzes the raw JSONL files in `~/.claude/projects/` to detect recurring frictions. Produces a prioritized report and updates the state in Postgres.
## Step 0 — Check Postgres
The Postgres `claude_sessions` database runs in the **LXC `docker-host`** (Tailscale node, access via `ssh user@docker-host`), in the Docker container named **`postgres`** (not `claude-postgres`).
```bash
ssh user@docker-host 'docker exec postgres psql -U claude -d claude_sessions -t -A -c "SELECT 1"'
```
If it fails: check that the container is running (`ssh user@docker-host 'docker ps --format "{{.Names}}"'`) and start it on docker-host if needed. **Do not** try a local `docker compose up` or `localhost:5433` (obsolete since the Linux migration). The script `parse_jsonl_friction.py` already points to `host="docker-host" port=5432`.
---
## Step 1 — Parse the JSONL
```bash
uv run ~/.claude/parse_jsonl_friction.py 2>/dev/null
```
- No argument: window since the last scan (Postgres state)
- Returns JSON: `[{session_id, project, cadrage, exchanges: [{user, assistant, has_correction, has_ack}]}]`
- `cadrage` (the session's framing) = first non-hook user message of the session, truncated to 1000 chars, or `null`. Captured **before** the time-window filter — for a session that started before the window, the first message in the window is not the session's framing.
- If 0 sessions → display "No friction detected since the last scan." and stop
**Mandatory upstream filter**: `parse_jsonl_friction.py` must exclude, at parsing time (not downstream), sessions that are automatic recap hooks or `/clear` sessions. **Content-based exclusion criterion** (since 2026-05-24): regex on the content of the first message — match on automatic hook markers (e.g. `Generate a session recap`, `UserPromptSubmit`, macOS/Linux signatures like `-Users-user`/`home-user`). Filtering by folder alone (`C--Users-user` / `home-user`) is not enough — the hook content itself must be detected. Real-session threshold: **minimum 2 messages** — below that, ignore. Without this filter, 98% of the dataset is noise to sort manually.
> **Haiku calibration not proven**: the `cadrage` has been injected into the payload since **2026-07-28**, in response to the 3 false positives of the 2026-05-24 run — the agent was judging fragments out of context. *(Implementation detail, internalized here from the original ticket now archived: `cadrage` = first non-hook user message, ≤ 1000 chars, `null` otherwise, captured **before** the time-window filter — otherwise it would be the first message of the window, not of the session, i.e. exactly the out-of-context fragment the field exists to eliminate. The regex `CADRAGE_SKIP_RE` is **dedicated** and not added to `HOOK_TRIGGER_RE`, which is shared with exchange filtering — without it, 2 of 3 framings were only the `<local-command-caveat>` wrapper. Verified over 60 days: 3/3 usable framings.)* The patch **reduces** false positives without guaranteeing their elimination, and its effect has not yet been observed: the 28/07 scan returned no friction across 2 human sessions, so there was nothing to correct. Until a scan has produced verifiable frictions, manually cross-check the `rule_violation` and `missed_skill` verdicts. If false positives persist despite the framing → architecture problem (Haiku too permissive for the task), not a prompt to tweak.
---
## Step 2 — Haiku agent analysis (parallel, batches of 5)
> ⚠️ **The payload is not the session.** `parse_jsonl_friction.py` only returns the exchanges that matched a regex, without tool calls, and truncates `user`/`assistant` to 500 characters. An agent that ignores this reasons from absences and fabricates frictions that don't exist. **Measured on 2026-08-20**: without the evidence constraint below, 4 verdicts out of 5 reported a friction, 3 of which were based on an extraction artifact — a skill "not invoked", a command "not run", an empty `assistant` field read as "the assistant did nothing". With the constraint, 15 sessions out of 108. **Factor of 5.7 on the same corpus.** The constraint is part of the instrument: removing it changes the figure, not the reality.
For each session in the JSON (batch of 5 simultaneous) → launch a Haiku Agent with this prompt (the ⚠️ block is not decorative, it carries the key reminder):
```
Tu analyses une session Claude Code pour détecter des frictions.
⚠️ CONTRAINTE DE PREUVE — le payload ne contient PAS toute la session : seuls
les échanges ayant déclenché un signal lexical y figurent, les appels d'outils
N'Y SONT PAS, et les champs `user` et `assistant` sont TRONQUÉS À 500
CARACTÈRES. Conséquences strictes :
- Tu ne peux RIEN conclure d'une absence. Jamais « skill non invoqué »,
« commande non lancée », « Claude ne dit jamais X », « X n'apparaît pas ».
- Un `assistant` VIDE = appel d'outil non capturé. JAMAIS une friction.
- Tout verdict portant sur la FIN d'une réponse (canari 🐙, signature, résumé
final) est invalide : la fin est coupée par la troncature.
- `has_correction` / `has_ack` sont des drapeaux de regex lexicale posés par le
script, PAS des jugements. `has_ack` détecte « désolé », « tu as raison » —
il n'a aucun rapport avec l'acknowledge des lessons. Ne fonde jamais une
friction sur leur valeur : lis le texte.
Cadrage — 1er message de {USER_NAME} dans la session :
[cadrage]
Utilise ce cadrage pour distinguer un comportement attendu d'une friction : si
{USER_NAME} y a acté le mode agentic, donné une consigne explicite ou posé le contexte
de la session, ce qui suit n'est pas une violation. Si le cadrage est `null`,
ignore cette instruction.
Voici les échanges avec signaux de friction (user → assistant) :
[échanges de la session]
Projet : [project]
Identifie, uniquement sur preuve positive et citable :
1. Corrections répétées : même erreur commise plusieurs fois
2. Règles CLAUDE.md violées visiblement dans le texte fourni
3. Friction explicite de {USER_NAME} : il reprend, corrige, signale une erreur —
idéalement Claude le reconnaît
Faux positifs à écarter : mots déclencheurs venant de la prose de Claude, d'un
nom de fichier (`non-ignored files`, `stop.json`), ou d'une délégation normale
(`prends la main` = mode agentic codifié dans CLAUDE.md, PAS une friction).
Retourne UNIQUEMENT ce JSON strict, rien d'autre :
{
"session_id": "...",
"project": "...",
"frictions": [
{"type": "correction|rule_violation|missed_skill", "description": "...", "evidence": "...", "severity": "low|medium|high"}
]
}
Retourne [] si aucune friction réelle détectée. Maximum 5 frictions par session.
```
Collect all returned JSON.
**Re-read the verdicts before consolidating.** Even with the constraint, about one verdict in twenty still relies on an absence. Manually discard any verdict whose `evidence` takes the form "X is not present" / "Claude never says X", or that cites a flag rather than a text. Log what was discarded in the report — it is a measurement of the instrument, not noise to throw away.
---
## Step 3 — Sonnet consolidation
Send all Haiku results to a Sonnet Agent:
```
Tu consolides les frictions détectées par des agents Haiku sur [N] sessions Claude Code.
Voici tous les résultats bruts :
[JSON consolidé]
Produis :
1. Top 10 frictions globales (dédupliquées, priorisées par fréquence + sévérité) avec action corrective
2. Détail par projet (max 5 frictions par projet)
Format de sortie : Markdown structuré, prêt à copier dans un fichier vault.
```
---
## Step 3bis — Delta vs previous runs
⚠️ **Without this step, the scan produces nothing.** Measured on 2026-09-09: **13 reports** produced since 17/04, **2 friction-handling tickets** (scans of 24/04 and 01/05), **0 since May** — all the other tickets born from this skill concern the instrument (parser, glob, filter, Haiku framing, Postgres), never what it measures. The cause is not a lack of transport: it is that **a report of N unique incidents calls for no action**. On 09/09, 30 frictions out of 33 had only one occurrence.
What is actionable is **what recurs**. The friction "agentic mode started without validating the contract" was detected in the runs of **10/06**, **20/08** (#1) and **09/09** (#4) without ever being flagged as recurring — each run measured its own window in isolation and forgot the previous one.
**Two sources, because neither is sufficient alone**:
1. **Run N-1, full text** — from Postgres:
```bash
ssh user@docker-host 'docker exec postgres psql -U claude -d claude_sessions -t -A -c "SELECT period_end::date, summary_md FROM friction_scan_runs ORDER BY period_end DESC LIMIT 2"'
```
2. **Long history** — from `99 - Claude Code/Friction scans/INDEX.md`, one line per report.
⚠️ **Mandatory, do not skip**: the database only goes back to **2026-05-28** (4 runs only as of 09/09) whereas the folder contains **13 reports**. A delta based on the database alone is blind to everything before June — including the June occurrence of the recurrence cited above. *Window* angle of [[03 - Knowledge/Claude code/un-inventaire-ne-vaut-que-son-instrument]].
**Produce a `## Récurrences` section at the TOP of the report**, before the top 10:
- Each mechanism already seen in a previous run, **with the dates of all the runs where it appears**
- A mechanism seen **≥ 3 times** → 🔴: detection has clearly failed to correct it. What it lacks is an **executable guardrail** (hook, skill gate), not one more reminder in `CLAUDE.md` — a conclusion already drawn in the 20/08 run and re-verified on 09/09.
- The **new** mechanisms of this run: one line each, without detail (they are in the top 10)
- **If no recurrence: state it explicitly** ("no mechanism from the previous run recurs"). An empty delta is a result, not a section to omit — otherwise nothing distinguishes "nothing recurs" from "I didn't look".
⚠️ **Do not create any ticket from this step.** The kanban is overloaded (active vault lesson) and the skill's absolute rule holds: the scan detects, {USER_NAME} decides. Recurrence goes in the report, not on the board.
---
## Step 4 — Write the report
Create `99 - Claude Code/Friction scans/YYYY-MM-DD.md`:
```markdown
# Friction scan — YYYY-MM-DD
Période : YYYY-MM-DD → YYYY-MM-DD
Sessions analysées : N (X projets)
## Récurrences
🔴 [mécanisme vu ≥ 3 fois] — runs du [dates] → garde-fou exécutable, pas un rappel
- [mécanisme vu 2 fois] — runs du [dates]
- Nouveaux ce run : [liste en une ligne]
*(ou : « aucun mécanisme du run précédent ne se rejoue »)*
## Top 10 frictions globales
1. [friction] → [action corrective]
...
## Détail par projet
### [Projet]
- [friction] → [action]
...
```
Create the `Friction scans/` folder if it does not exist.
---
## Step 5 — Update the Postgres state
**Two counters, not one.** `sessions_count` = the sessions that the parser **returned** (at least one lexical signal), those that go to the fan-out. `sessions_read` = the **denominator**, the sessions of the window actually parsed. Both come from stderr in Step 1: `Sessions avec friction : N` and `Sessions lues : D (sur F fichiers trouvés)`. An `N` without a `D` is not a result — that is what the 28/07 and 04/08 runs produced, credible only because nothing indicated over how many sessions the zero applied.
⚠️ **`sessions_count` does NOT count confirmed frictions.** Established on the 2026-08-20 data: the 28/07 run wrote `8` and the 04/08 run wrote `2`, while **both concluded at 0 real friction** — their `summary_md` says "6 sessions out of 8 are unfiltered noise" and "2 sessions returned, both lexical false positives". The count of confirmed frictions goes in `summary_md`, where these two runs put theirs. Writing the confirmed count there would break the series without anything flagging it.
*(This also settles the "2 human sessions" vs "8 in the database" discrepancy of 28/07: no race between the hook rename and the scan — 8 returned, 6 of which were noise, so 2 human. Both figures are correct, they measure two different things.)*
`instrument_version` marks the population read. Runs are only **comparable at equal version**: the glob fix of 19/08 raised the corpus from 213 to 871 files, so a rise in `sessions_count` after that date is a change of denominator before it is a rise in friction. Current value: `2026-08-19-glob-fix`. Change it as soon as the reading scope of `parse_jsonl_friction.py` moves (glob, recursion, population filters) — not for a change of regex vocabulary.
```sql
UPDATE friction_scan_state SET last_scan = NOW(), updated_at = NOW() WHERE id = 1;
INSERT INTO friction_scan_runs
(period_start, period_end, sessions_count, sessions_read, instrument_version, output_file, summary_md)
VALUES ('[début]', '[fin]', [N avec friction], [D lues], '2026-08-19-glob-fix',
'99 - Claude Code/Friction scans/YYYY-MM-DD.md', '[top 10 en markdown]');
```
Via: `ssh user@docker-host 'docker exec postgres psql -U claude -d claude_sessions -c "..."'` (one `-c` option per statement — a heredoc on stdin doesn't get past the permission guards).
---
## Step 6 — Update the command-tracker
- Open `{VAULT_PATH}\{CLAUDE_CODE_FOLDER}\command-tracker.md`
- `/friction-scan` line → replace the date with today's date in `YYYY-MM-DD` format
---
## Conversational summary
Display after the report:
```
Friction scan terminé — [N] sessions analysées sur [X] jours.
Rapport : 99 - Claude Code/Friction scans/YYYY-MM-DD.md
Top friction : [#1 du top 10]
```
---
## Absolute rules
- Never modify CLAUDE.md or the skills directly — the scan detects, {USER_NAME} decides
- **Step 3bis is never skipped.** It is what makes the report actionable; without it the scan falls back into the 4 months of zero output measured on 09/09. ⚠️ Direct precedent: **Step 3 (Sonnet consolidation) was skipped 3 times out of 3** (24/05, 28/07, 20/08) — a step inserted in the middle of this skill has a documented history of not running. If the delta cannot be computed (database unreachable, INDEX absent), **write it in the report with the reason** instead of omitting the section
- If Postgres is unavailable (LXC `docker-host` unreachable / `postgres` container down): report and stop (no JSON file fallback — the state must be reliable)
- Batches of 5 agents max in parallel — do not overload the shared quota of {USER_NAME}+[partner]