Mode d'emploi des mods, en français : les 6 entrées de la barre Mods et chacun de leurs onglets, ma journée, la nuit, ce qu'un mod peut ou ne peut pas faire, à…

Mods for Claude Code: small panes that show what your agents do. They never block or rewrite a tool call; at most they warn.
Needs Claude Code 2.1.287 or later (function-hook mods, panes, Svg element).
The band's Mods bar has 6 entries (Julian, 16 Oct). Each older mod is now shown inside one of them; its own command still works (while it is loaded it answers itself, once removed the hub registers the same name as an alias).
| Entry | Command | Hub mod | Shows inside it |
|---|---|---|---|
| Jauge | /jauge | band | the band above the prompt and its pane |
| Cockpit | /cockpit | cockpit | zoomable méga › projet › conversation › agent with one summary card per topic (Qui consomme, T’attend, À toi, CI, Quota, Problèmes du jour, En cours) and the Usine and Machine tabs; older mods: factory, machine, usage |
| Veille | /veille | veille | tabs Alertes, Fil, À archiver, Export eta; older mods: export-eta |
| À toi | /afaire | a-faire | what only you can do |
| Registres | /registres | registres | tabs Problèmes, Tests réels, Règles, Ménage; older mods: problemes, tests-reels, metrics, menage |
| Référence | /reference | reference | tabs Config, Guide, Scénarios, Santé, CI; older mods: control, guide, scenarios, sante, ci |
filetree (external) stays apart: its own Fichiers tab next to Cockpit.
| Mod | Command | What it shows | |
|---|---|---|---|
band | `/jauge [refresh\ | close]` | Jauge, above the prompt (French labels). Export conv and, when the app links sub-conversations to this one, Export + enfants +N on the Jauge line (26 Oct): one masked Markdown brief for another AI (what the conversation is, where it stands and what is next, live ETA, git, PRs/MRs, every message and tool call), saved under ~/.claude/export-eta/briefs and copied to the clipboard, by export-eta's exporter/brief.mjs; labels in export_brief. Clarity layout (default, 25 Oct): folded to ONE line « ▶ ● 3 agents en cours · ctx ▰▰▱▱▱ 30 % · 5 h · sem » coloured by state; ▶/▼ unfolds sections (En cours · cette conversation as a ├ └ tree with bars, %, tokens, ETA; Jauges; Ailleurs sur ce PC; Mods), state kept in $.store; jauge.layout: "line" keeps the older line. One line always visible: a slim context bar (only the next threshold named) then « ctx 8 % · compact ~16 min · 434 tok/s · 1 compactage(s) · 5 h 24 % · sem 14 % », then « À toi : N » and « attend Julian : N » once each, red when N > 0 (counted by lib/core/veille.mjs in the scanner, the same count Cockpit and Veille show), and a ▸ that unfolds « Cette conversation » (model · effort, agents running/seen, Workflow, PR). The Usage and Veille sections left the band: 5 h / week details are in Cockpit's Quota card, alerts in Veille. Under it, the Mods bar with the 6 entries (launcher.preset: "hubs", default): Jauge, Cockpit, Veille, À toi, Registres, Référence; a hub not loaded is greyed and reads « non chargé : ajouter mods/<x> à CLAUDE_CODE_PLUGIN_DIRS »; launcher.preset: "all" brings back the 15 older buttons. /jauge adds the per-scope table (tok/s, /min, /h, list-price $/h, over 60 s and 10 min), the 5 hottest sessions with their compactions, projects, 30-minute sparklines with compaction markers, each conversation's compactions, and the hand-off helper (RESUME). Optional status-line entry. |
| Mod | Command | What it shows | ||||||
|---|---|---|---|---|---|---|---|---|
cockpit | `/cockpit [mega\ | macro\ | medium\ | micro] [projet ou conversation], /cockpit close` | Cockpit, one side pane ordered by scope (French labels), each section foldable to one summary line: Cette conversation (open and selected at start: model · effort, ctx, state, the lead tree holding it through the app's spawnedFrom link → sub-conversations → Workflows → agents, finished ones folded behind « + N terminé(s) », step, PR/CI, an agent card with its log when an agent is picked), Ce projet (its conversations as a tree, even lanes in another repo, factory's Focus + Pipeline), Tous les projets (two lines per project), Claude global (5-hour, week, Fable week, credits, this session's cost, model share, cache hit, Veille alerts, a /machine button). A small breadcrumb « Méga › Projet › Conversation › Agent » zooms out; a click drills down. The context gauge lives in band, above the prompt. Opens by itself at session start, as a tab next to filetree (the desktop shows one pane at a time). Sections, order, default level and auto-open in cockpit.config.json. It reuses factory, band and veille through byte copies in lib/ (a mod may import only its own folder; scripts/sync-libs.mjs, drift-tested). | |||
factory | `/factory [mission\ | focus\ | arbre\ | pipeline\ | quotas\ | systeme\ | journal], /factory <title or id>` | Side panel of all your agents (v2, French labels), tabs on top and every screen stacked top to bottom at the pane's width (no fixed-size drawing, no zoom). Mission: counters (working, idle, blocked with the reason, waiting on you, done today, cost today), one card per project (lead, sub-conversations, running agents, context %, model and effort), model share vs the V6 targets, and the conversation list with the All / Live / Problems / Waiting filters. Focus: the Ça t'attend rows (green PR/MR not merged, question or action waiting on you, lane idle on a red, conflicting or skipped PR, sub-conversations per lead; one native notification per new row), fleet pulse, live timeline (compactions, context over the 250K hand-off mark, blocked, quiet, merged, handed off) and progress today per project. Arbre (this conversation or one picked from the list): lead with model, effort bars, price per 1M and context, its sub-conversations, Workflows and agents with model, effort, state, tokens and cost, the architect on call (before a plan, error repeats, before done, calls and tokens read), the bill (every turn vs on call), approvals and guards, warnings, the session log and a status line. Pipeline: work in flight per stage (plan, build, review, test/CI, merge) per project. Quotas: Claude 5-hour and weekly bars with the forecast from the usage mod, Codex when available, cost today per model and per project. Système: CPU, RAM, GPU, disks and GitLab runner load from the machine mod. Journal: every session's events, filterable by kind and project. Without the usage or machine mod those boxes say « module non chargé ». Labels, thresholds and which screens show are in factory.config.json → screens and waiting. Screen ideas (counters, Focus, timeline, account pool) from rig-console in korallis/agent-stack (Apache-2.0); no code copied. |
machine | `/machine [refresh\ | ci]` | Machine, a live view of this PC (French labels): CPU total and per core, RAM, free space per fixed drive, GPU (nvidia-smi, else a Windows performance counter, else « non disponible »), top 5 processes by CPU and by memory with claude, node, python and git coloured and totalled, and the local GitLab runner's load (runners online, jobs running / pending) through the ci mod's own scanner and config. From these, « agents en parallèle conseillés maintenant : N » with the rules that fired (CPU, RAM, disk, pending jobs) and the caps (4 CI pipelines minus running jobs, 3 npm ci / tsc). Samples only while its pane is open (every 5 s) or its optional band entry is on (every 15 s, off by default). | |||||
usage | `/conso [aujourdhui\ | semaine\ | classement\ | prevision\ | scenarios\ | plein\ | codex] [refresh]` | Consommation, in French: Classement ranks who burned the most (1 h, 4 h, aujourd'hui, 2 j, 7 j, 30 j; by conversation, project, model, agent type, feature or Claude/Codex; tokens by kind, cost equivalent, share, trend vs the window before, subagents counted under their parent); tokens and list-price cost equivalent today and over the week, per hour (heatmap), project, model, kind (main thread, Agent subagent, Workflow agent, sub-conversation), app surface, effort, skill and MCP server, top 10 sessions. Forecast of the 5-hour and weekly limits from the official % ($.session.usage()) and the measured pace (last 2 h, today, 7 days) with calme / normal / intense projections; which scenario (S1-S5) fits the quota left before the reset; suggests S5 "Plein régime" when much of the week would be left. Optional status-line entry. Codex tab: Codex tokens today and over 7 days, per model, and the plan % Codex writes in its local session files (~/.codex/sessions/**/rollout-*.jsonl, the files the codex-hud plugin reads), next to Claude's on one line; « non disponible » when nothing is written (option codex: config/on/off). Its parser and price table are a shared module (mods/usage/lib). |
| Mod | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
veille | `/veille [fil\ | mode <x>\ | ack <clé\ | all>\ | coordinateur\ | tour]` | Veille, French labels: Fil (/veille fil, the pane's « Fil » tab): every conversation's last message in one place, zero model tokens (files only, nothing sent to a model or added to a prompt). Grouped by project (foldable, « 5 conv · 2 en cours · 1 attend Julian · dernière activité 20:41 »), then lead → sub-conversations (the app's spawnedFrom link, a lane in another repo stays under its lead), by last activity. Folded: title, state (en cours / au repos / attend Julian / bloquée / terminée), model · effort, time, the first two lines of the last message (the end-of-turn wrap_up recap when the turn has one, else the last assistant text; tool calls left out). Unfolded: the full message (Markdown), the ask and its buttons, PR/MR links, « Ouvrir la conversation » and « Copier l'id ». « Nouveau » since your last read ($.store), filters Tout / Attend Julian / Bloquées / Terminées aujourd'hui / Projet, a red « attend Julian : N ». Token-like strings are masked. The watcher writes ~/.claude/veille/fil.json at every fire; the pane reads it and refreshes only on « Rafraîchir ». a zero-token watcher script (Windows task ClaudeVeille, every 5 min, runs with Claude closed) tours conversations, PRs/MRs and CI with the same sources and rules as factory's « Ça t'attend » (its scanner and waiting.mjs imported, not copied), and writes alerts this pane shows: severity, since when, conversation or PR, link, Ack button, last tour (red when two fires were missed), every action with its reason. Modes (config, pane buttons, /veille mode): rien, légère (30 min, notify only), active (5 min, + wake), nuit-active (10 min, the script merges a green up-to-date PR/MR itself: every check success, never skipped, cancelled, manual or 0 jobs; + wake; notifications only for what needs Julian), nuit-test-légère (30 min, notify, small token budget), each with what it may do, a token budget per hour and quiet hours. A conversation blocked on Julian: Windows notification and an e-mail digest (SMTP, your ~/.claude/veille/smtp.json). Waking a conversation (claude -p --resume <id>, off by default) only for what the script cannot do. One line above the prompt with the mode. See veille. |
export-eta | `/export-eta [en-cours\ | lot\ | tout\ | brief [enfants]\ | close] (also /export` when the built-in leaves it free) | « Export eta », zero model tokens: exports conversations to the eta repo as Markdown through a PR. Brief (/export-eta brief [enfants], the band's Export conv / Export + enfants buttons): one masked Markdown file about a conversation and its sub-conversations for another AI, local + clipboard, no PR. En cours (snapshot of every ongoing conversation), Sélection (checkboxes per project, foldable), Lot terminé: each Veille tour counts the conversations finished since the last export; at batch_min (3) or when a lead and all its sub-conversations are finished, « 4 conversations terminées — Exporter vers eta » shows with a button in Veille (Alertes and Fil) and above the prompt (auto: true exports without a click). Each file: header (project, folder, branch, model · effort, start, last activity, state, parent, sub-conversations, PRs), then the messages in order, one line per tool call, tool outputs and file dumps left out, agent results in one line; split into parts past max_kb (300 KB). A confidentiality pass masks tokens, keys, passwords, cookies, connection strings, JWTs, private keys and e-mail addresses (not yours), then re-checks: a file with an unmaskable hit is held back and listed. Layout sources/conversations/<project>/<date>-<title>-<id>.md + INDEX.md per project and global; a re-export rewrites only its own file. Git: fresh worktree of the eta repo, branch, PR, squash merge (green checks, or none and a clean pass), branch deleted, worktree removed. The pane lists the last exports (date, count, PR, masked counts, held-back files). The eta path lives in ~/.claude/export-eta/config.json, never in this repo. |
| Mod | Command | What it shows |
|---|---|---|
a-faire | /afaire [refresh] | « À faire par Julian », in French: every action only you can do, so none gets lost, by collapsible category with a one-line summary each: Configuration (veille's smtp.json missing or incomplete, mods installed but not in CLAUDE_CODE_PLUGIN_DIRS, the ClaudeVeille task missing or not firing), Décisions (open rows and « Your action » lines of your pending-decision files, your open PRs labelled or saying in one sentence that they wait for Julian to approve or decide, questions.md lines marked for you), Connexions / 2FA, Secrets à ranger (tests-reels registry, counts only), Tests manuels (manual-checks.md), Questions des conversations (veille's « attend Julian » alerts, with the conversation link). Each item: why it blocks, the exact steps with a Copier button, since when, its source, a priority (bloque une conversation > bloque une fonction > confort). Fait re-checks what can be measured (fill smtp.json and the item closes by itself; until then it says why not) and marks the rest done; Plus tard hides it one day. Read-only except its own ~/.claude/a-faire. The band shows a red « À toi : N » on its first line and the « À toi » entry in its Mods bar; the veille watcher pushes each new high-priority item once (Windows notification, and its e-mail when smtp.json works). Sources and patterns in afaire.config.json. |
| Mod | Command | What it shows | ||||
|---|---|---|---|---|---|---|
registres | `/registres [problemes\ | tests\ | regles\ | menage\ | close]` | « Registres », one pane with tabs Problèmes, Tests réels, Règles, Ménage, each drawn by a byte copy of its owner's pure view on the owner's files (see its README). /problemes, /tests, /regles, /menage become aliases when their old mod is not loaded. Santé and Veille errors reach the Problèmes tab. |
problemes | `/problemes [refresh\ | P-NNN], /problemes close` | « Problèmes », in French: a persistent register of every error and problem with Claude work, so the same issue is understood once and never re-discovered. A zero-token collector (scanner/problemes_scan.mjs collect, run when the pane opens and the register is older than 30 min, on ↻, and by the Veille watcher each tour) reads only the bytes appended to the transcripts since its last run (sessions, sub-agents, Workflow agents) and the desktop app's session files, and spots AskUserQuestion calls, turns that end on a question, the app's needs_action, permission refusals, folders and rules granted, app and worktree guards, protected rm, BLOCKED: finals, Workflows with agents_error, failing or skipped gh / glab checks, API errors. Configurable rules classify each hit; hits with the same signature (rule + app or key) are one problem whose count and last-seen go up; a fixed problem that comes back is reopened. Seeds import your existing registers once per row (Markdown tables, incidents/findings JSON, from a file or git show). The pane: « N ouverts · M corrigés · cette semaine +K », then collapsible categories with one-line summaries (Blocages manuels, Workflow, Règles, App Desktop / Claude Code, CI, Par application, Mods), each problem expandable to symptom, cause, fix, evidence, timeline and notes; filters by status, period, category and app; « Ajouter une note » appends to the local ledger. Data only in ~/.claude/problemes/. | |||
tests-reels | /tests [refresh], /tests close | « Tests réels », French labels, read-only: Julian's registry of real (non-CI) tests per application (test tenant runs, Cloudflare Access / Workers checks, Power BI Desktop / SSAS / Docker local runs, UI automation, manual checks). Top to bottom, each block folded to one summary line: totals, À ranger (accounts whose secret is not stored, missing ids, secrets seen in clear in the history: kind, session and date only), then one block per app with environments (tenant / cloud / local / docker, URLs, short ids), test accounts masked until « voir » with only where the secret lives (Windows Credential Manager target), procedures with their last run (green / red / never), last runs, manual checks and « Trouvé dans l'historique ». Data lives only in ~/.claude/tests-reels (never in this repo); cli.mjs add / run-log record environments, accounts, procedures and runs and refuse any secret value; scanner/recover.mjs rebuilds what the transcripts, manual-checks.md, handoff/ and reports/ say. See its README. | ||||
metrics | /regles [V5.8] [refresh] | « Les règles marchent ? », in French: whether the rules help, per day over 30 days and per rules version. PRs/MRs merged per day across your repos (gh + glab), tokens and list-price cost per merged PR (M8, sessions attributed to a repo by their folder), share of Opus / Sonnet / Haiku turns, Agent and Workflow agent() calls that name a model (M1), main turns at ≥ 250 K (M2), manual stops, permission refusals (M10), app guard hits, CI gaps (« creux », approximate), BLOCKED / red-twice stops, wake-up calls (M6), compactions. Sparklines with the rules versions from the rules file's git log as │ markers, an « avant / après » table for any version and a summary row per version. Thresholds, targets, labels and detection patterns in metrics.config.json; caches in ~/.claude/metrics-mod, incremental. | ||||
menage | /menage [refresh] | « Ménage », in French: what Claude work left lying on this PC, read-only. For every git repo under your roots: each worktree (branch, merged into main or not, clean or modified, last commit age, disk size), worktree folders git no longer lists, local and remote branches already merged (fast-forward, or squash: same content or same patch-id in main, or a merged PR in the desktop app's session files); plus unloaded copies in ~/.claude/mods, old deploy backups, transcript disk use per project (and projects whose folder is gone), old session temp folders, and desktop sessions that can be archived (idle, every PR merged). Totals of reclaimable space. Each row shows the exact safe command (git worktree remove without --force, git branch -d, …) with a Copy button; the mod never runs it. Modified or unmerged items are red « ne pas supprimer ». Roots, thresholds, command templates and labels in menage.config.json. |
| Mod | Command | What it shows | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
reference | `/reference [config\ | guide\ | scenarios\ | sante\ | ci [diagramme]\ | close]` | « Référence », one pane with tabs Config, Guide, Scénarios, Santé, CI, each drawn by a byte copy of its owner's view on the owner's caches (see its README). Appliquer ce scénario writes the chosen per-role model and effort to ~/.claude/scenarios/applied.json and shows the diff against settings and agent files; it never edits them. /config-claude, /control, /mods-guide, /scenarios, /sante, /ci become aliases when their old mod is not loaded. | |||||
control | `/control [setup\ | usage\ | practices\ | history\ | config] [scan], /config-claude [scan]` | CONFIG (/config-claude, also a tab of /control): everything in Claude Code on this machine, read-only, French labels, top to bottom in the side panel, as a tree category → sub-category → item, each item with its path, modified time, size and full content (Markdown rendered or raw), a search box across names, fields and full text, and a « Changements » list (config files modified in the last 7 days). Ten categories: rules and instructions (global and project CLAUDE.md / CLAUDE.local.md / AGENTS.md, .claude/rules, output styles, memory), agents (user, project, plugin, built-in from the docs), skills / commands / workflows, settings merged by precedence (managed > CLI > local > project > user, docs: value, file that set it, files it overrides; lists merged), documented defaults with their doc URL (« non vérifié » when the docs don't say), hooks and permissions, mods and plugins (loaded or not, version, commands; old copies in ~/.claude/mods flagged), MCP servers (names, command or URL, scope; env and header names only), desktop app preferences (an allow-list of keys; the rest « non lisible depuis un mod »), Claude Control (rules source, deploy.py, last deploy backup, RULES-INVENTORY.md, and a badge when ~/.claude differs from the repo). Secrets are masked before anything is written: any settings key matching `token\ | secret\ | passw\ | key\ | auth\ | credential\ | cookie, every ANTHROPIC_* value, token-looking strings; process env vars by name only. SETUP, USAGE, PRACTICES, HISTORY: read live at each scan, so it never goes stale with a rules version. SETUP: « Règles actives » (the title line and version of ~/.claude/CLAUDE.md, e.g. V5.8), blockers (hook, deny rule, mod deny path), « Mods chargés » (each mod folder: loaded by CLAUDE_CODE_PLUGIN_DIRS, installed not loaded, or a copy of a mod loaded elsewhere), hidden rules, then settings (env names only, a value only for an allow-list), settings hooks, permissions, repo CLAUDE.md, agents, skills, workflows, hook scripts, scheduled tasks, MCP servers, plugins, memory. USAGE: 1/7/30-day model, effort and delegation mix, each metric against the live rule line it measures. PRACTICES: one section per heading of the live CLAUDE.md, each line with the evidence it cites (dates, PRs, audits, PRACTICES ids) and its measured state, plus a « V6 en attente » panel (kept / changed / dropped) when the rules repo has docs/V6-CHANGES.md` on main. HISTORY: the rules' version history. |
guide | /mods-guide [onglet ou section] | Mode d'emploi des mods, in French: tabs (Sommaire, Bases, Événements, Interface, Configuration, Installer et activer, Tester, Écrire un mod pas à pas, Référence API, Nos mods, FAQ), foldable categories, and one card per mod of this repo built live from its plugin.json and hooks module. Same content in MODE-EMPLOI.md. |
| scenarios | /scenarios [S1..] [prompt\|agent\|workflow\|frontmatter\|env] | Scénarios d'agents: presets of roles -> model, effort, unit (session, sub-conversation, Workflow agent(), Agent subagent) and max parallel (S1 Standard V6, S2 Économe, S3 Qualité max, S4 Nuit, S5 Plein régime, plus yours from a JSON file). For each role, the exact settings (Agent call, agent() opts, agent-file frontmatter, env vars) and the documented
hooks/register.tsx 73 lines1// guide mod ("Mode d'emploi des mods"): MODE-EMPLOI.md as a pane with tabs. The first tab, Sommaire, is the whole tree
2// with a link to every tab, category and sub-section; each other tab folds its categories. The "Nos mods" cards are
3// rebuilt at each draw from the neighbouring mods' plugin.json and hooks module. Read-only: no hook on tools or agents.
4// The drawing and the live cards are in draw.tsx (pure), shared with the Référence hub (mods/reference).
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, Register } from 'claude-code'
7
8import { SOMMAIRE, drawGuide, findIn, liveDoc } from './draw'
9import type { Where } from './draw'
10
11const PANE = { id: 'mods-guide', title: "Mode d'emploi des mods" }
12const tabAtom = atom({ plugin: 'guide', key: 'tab' } as const, SOMMAIRE)
13const catAtom = atom({ plugin: 'guide', key: 'cat' } as const, '')
14const subAtom = atom({ plugin: 'guide', key: 'sub' } as const, '')
15
16const text = async ($: EngineInterface, path: string): Promise<string | undefined> => {
17 try {
18 return (await $.fs.read(path, { as: 'text' })) as string
19 } catch {
20 return undefined
21 }
22}
23
24/** The guide with live cards for "Nos mods". */
25const loadDoc = async ($: EngineInterface) => {
26 const root = $.plugin.root.replace(/\\/g, '/')
27 return liveDoc(p => text($, p), `${root}/MODE-EMPLOI.md`, `${root}/mods.json`, root.replace(/\/[^/]+$/, ''), PANE.title)
28}
29
30const go = async ($: EngineInterface, to: Where) => {
31 await update($, tabAtom, () => to.tab)
32 await update($, catAtom, () => to.cat)
33 await update($, subAtom, () => to.sub)
34}
35
36export const register: Register = on => {
37 on('session.start', async ($, e, next) => {
38 await $.command.register({
39 name: 'mods-guide',
40 description: "Mode d'emploi des mods : Démarrer, les 6 entrées (Jauge, Cockpit, Veille, À toi, Registres, Référence), la nuit, possible ou pas, à essayer, écrire un mod, nos mods, FAQ",
41 argumentHint: '[onglet ou section] | close',
42 })
43 return next(e)
44 })
45
46 on('command.run', { command: 'mods-guide' }, async ($, e) => {
47 if ((e.args ?? '').trim().toLowerCase() === 'close') {
48 await $.ui.close({ id: PANE.id })
49 return {}
50 }
51 const { doc, problem } = await loadDoc($)
52 if (problem) return { text: `mods-guide: ${problem}` }
53 const args = (e.args ?? '').trim()
54 const to = args ? findIn(doc, args) : { tab: SOMMAIRE, cat: '', sub: '' }
55 if (!to) return { text: `mods-guide: pas de section « ${args} ». Onglets : ${doc.tabs.map(t => t.title).join(', ')}` }
56 await go($, to)
57 await $.ui.open({ id: PANE.id, title: PANE.title })
58 const where = to.tab === SOMMAIRE ? 'Sommaire' : doc.tabs.find(t => t.id === to.tab)?.title
59 return { text: `mods-guide: ouvert sur ${where}${to.cat ? ` › ${to.cat}` : ''}${to.sub ? ` › ${to.sub}` : ''}` }
60 })
61
62 on('ui.render', { component: 'Pane', requestId: 'mods-guide' }, async ($, e) => {
63 const { doc, problem } = await loadDoc($)
64 return drawGuide($.ui.resolve(e), {
65 doc, problem,
66 tab: await read($, tabAtom),
67 cat: await read($, catAtom),
68 sub: await read($, subAtom),
69 go: to => go($, to),
70 })
71 })
72}
73hooks/draw.tsx 139 lines1// guide mod: the pane's drawing and the live « Nos mods » cards, pure. No `$`: the elements come in as `ui`
2// ($.ui.resolve(e)), files through a `read` callback built on $.fs in the register file, every press as `go`. The
3// guide pane and the Référence hub (mods/reference, a synced copy of this file) draw the same tree. Same output as the
4// drawing that lived in register.tsx before.
5import type { Doc, ModsCatalog } from '../types'
6import { card, modsMarkdown, modulePath } from './cards'
7import { between, locate, parse, slug } from './toc'
8
9export const SOMMAIRE = 'sommaire'
10export type Where = { tab: string; cat: string; sub: string }
11export type Read = (path: string) => Promise<string | undefined>
12
13/** The guide at `guidePath` with live cards for "Nos mods": catalog at `catalogPath`, mods under `modsDir`. */
14export async function liveDoc(read: Read, guidePath: string, catalogPath: string, modsDir: string, title: string): Promise<{ doc: Doc; problem: string }> {
15 const md = await read(guidePath)
16 if (!md) return { doc: { title, intro: '', tabs: [] }, problem: `cannot read ${guidePath}` }
17 let live = md
18 const raw = await read(catalogPath)
19 if (raw) {
20 try {
21 const catalog = JSON.parse(raw) as ModsCatalog
22 const cards = []
23 for (const entry of catalog.mods) {
24 const dir = `${modsDir}/${entry.dir}`
25 const manifest = await read(`${dir}/.claude-plugin/plugin.json`)
26 const rel = modulePath(await read(`${dir}/hooks/hooks.json`))
27 cards.push(card(entry, catalog, manifest, rel ? await read(`${dir}/${rel}`) : undefined))
28 }
29 live = between(md, 'mods', modsMarkdown(cards, catalog))
30 } catch {}
31 }
32 return { doc: parse(live), problem: '' }
33}
34
35/** `/mods-guide [onglet ou section]`: an anchor, or the start of a title. */
36export function findIn(doc: Doc, args: string): Where | undefined {
37 const want = slug(args)
38 if (!want) return undefined
39 const exact = locate(doc, want)
40 if (exact) return exact
41 for (const t of doc.tabs) {
42 if (t.id.startsWith(want)) return { tab: t.id, cat: '', sub: '' }
43 for (const c of t.cats) {
44 if (c.id.startsWith(want)) return { tab: t.id, cat: c.id, sub: '' }
45 for (const s of c.subs) if (s.id.startsWith(want)) return { tab: t.id, cat: c.id, sub: s.id }
46 }
47 }
48 return undefined
49}
50
51export type GuideModel = { doc: Doc; problem: string; tab: string; cat: string; sub: string; go: (to: Where) => void | Promise<void> }
52
53export function drawGuide(ui: any, m: GuideModel): any {
54 const { Box, Text, Button, Markdown } = ui
55 const { doc, problem, cat, sub, go } = m
56 const current = doc.tabs.find(t => t.id === m.tab)
57 const on_ = (yes: boolean) => (yes ? {} : { plain: true as const })
58
59 const tabs = (
60 <Box flexDirection="row" gap={1} flexWrap="wrap">
61 <Button key="tab-sommaire" {...on_(!current)} onPress={() => go({ tab: SOMMAIRE, cat: '', sub: '' })}>
62 Sommaire
63 </Button>
64 {doc.tabs.map(t => (
65 <Button key={`tab-${t.id}`} {...on_(t.id === current?.id)} onPress={() => go({ tab: t.id, cat: '', sub: '' })}>
66 {t.title}
67 </Button>
68 ))}
69 </Box>
70 )
71
72 if (problem) return <Text color="error">{problem}</Text>
73
74 if (!current) {
75 return (
76 <Box flexDirection="column" gap={1}>
77 {tabs}
78 <Text bold>{`Sommaire général · ${doc.title}`}</Text>
79 {doc.intro ? <Markdown text={doc.intro.replace(/^Doc officielle.*$/m, '').trim()} /> : null}
80 <Box flexDirection="column">
81 {doc.tabs.map(t => (
82 <Box flexDirection="column">
83 <Button key={`go-${t.id}`} plain bold onPress={() => go({ tab: t.id, cat: '', sub: '' })}>
84 {t.title}
85 </Button>
86 {t.cats.map(c => (
87 <Box flexDirection="column" paddingLeft={2}>
88 <Button key={`go-${c.id}`} plain onPress={() => go({ tab: t.id, cat: c.id, sub: '' })}>
89 {c.title}
90 </Button>
91 {c.subs.map(s => (
92 <Box paddingLeft={2}>
93 <Button key={`go-${s.id}`} plain dimColor onPress={() => go({ tab: t.id, cat: c.id, sub: s.id })}>
94 {s.title}
95 </Button>
96 </Box>
97 ))}
98 </Box>
99 ))}
100 </Box>
101 ))}
102 </Box>
103 </Box>
104 )
105 }
106
107 return (
108 <Box flexDirection="column" gap={1}>
109 {tabs}
110 <Text bold>{current.title}</Text>
111 {current.intro ? <Markdown text={current.intro} /> : null}
112 {current.cats.map(c => {
113 const open = c.id === cat
114 return (
115 <Box flexDirection="column">
116 <Button key={`cat-${c.id}`} plain bold onPress={() => go({ tab: current.id, cat: open ? '' : c.id, sub: '' })}>
117 {`${open ? '▾' : '▸'} ${c.title}${open ? '' : ` (${c.subs.length})`}`}
118 </Button>
119 {open && (
120 <Box flexDirection="column" paddingLeft={2} gap={1}>
121 {c.body ? <Markdown text={c.body} /> : null}
122 {c.subs.map(s => (
123 <Box flexDirection="column">
124 <Text bold {...(s.id === sub ? { color: 'success' as const } : {})}>{`${s.id === sub ? '→ ' : ''}${s.title}`}</Text>
125 {s.body ? <Markdown text={s.body} /> : null}
126 </Box>
127 ))}
128 </Box>
129 )}
130 </Box>
131 )
132 })}
133 <Button key="back" plain dimColor onPress={() => go({ tab: SOMMAIRE, cat: '', sub: '' })}>
134 ← Sommaire
135 </Button>
136 </Box>
137 )
138}
139hooks/cards.ts 110 lines1// "Nos mods": one card per mod, built from what the mod itself ships (plugin.json, hooks/hooks.json, its hooks
2// module's source) plus the few facts only mods.json knows (state, data read, tests). Pure: no `$`.
3import type { Card, CatalogEntry, ModsCatalog } from '../types'
4
5type Manifest = {
6 name?: string
7 version?: string
8 description?: string
9 userConfig?: Record<string, { title?: string; default?: unknown; options?: unknown[] }>
10}
11
12const uniq = (xs: string[]) => [...new Set(xs)]
13
14/** Events the module hooks: `on('event'` / `on("event"`. */
15export const eventsIn = (src: string) => uniq([...src.matchAll(/\bon\(\s*['"]([\w.*-]+)['"]/g)].map(m => m[1]!))
16
17/** Slash commands the module registers: `$.command.register({ name: 'x'`. */
18export const commandsIn = (src: string) =>
19 uniq([...src.matchAll(/\$\.command\.register\(\s*\{[^}]*?\bname:\s*['"]([\w-]+)['"]/gs)].map(m => `/${m[1]}`))
20
21/** Whether the source can refuse anything: a `deny` answer or a `drop` of a prompt. */
22export const canBlock = (src: string) => /\{\s*deny\s*:|\bdeny:\s*['"`]|\{\s*drop\s*:/.test(src)
23
24/** Whether it draws: a Pane, a band above the prompt, a status line, toasts. */
25export function drawsIn(src: string): string[] {
26 const out: string[] = []
27 if (/component:\s*['"]Pane['"]/.test(src)) out.push('panneau')
28 if (/component:\s*['"]AbovePrompt['"]/.test(src)) out.push('bandeau')
29 if (/\$\.ui\.status\(/.test(src)) out.push('ligne de statut')
30 if (/\$\.ui\.toast\(/.test(src)) out.push('toasts')
31 if (/['"]prompt\.compose['"]/.test(src)) out.push('note dans le prompt système')
32 return out
33}
34
35/** The hooks module path a hooks.json names, relative to the mod folder. */
36export function modulePath(hooksJson: string | undefined): string | undefined {
37 try {
38 const first = (JSON.parse(hooksJson ?? '') as { modules?: string[] }).modules?.[0]
39 return first ? `hooks/${first.replace(/^\.\//, '')}` : undefined
40 } catch {
41 return undefined
42 }
43}
44
45/** One card. `manifest` and `source` are undefined for a mod that is not in this folder (planned, or not installed here). */
46export function card(entry: CatalogEntry, catalog: ModsCatalog, manifest?: string, source?: string): Card {
47 let m: Manifest = {}
48 try {
49 m = manifest ? (JSON.parse(manifest) as Manifest) : {}
50 } catch {}
51 const src = source ?? ''
52 const options = Object.entries(m.userConfig ?? {}).map(([key, f]) => {
53 const choices = Array.isArray(f.options) ? ` (${f.options.join(' | ')})` : ''
54 return `${key}${f.title ? ` « ${f.title} »` : ''}${choices}, défaut ${JSON.stringify(f.default ?? '')}`
55 })
56 const found = Boolean(manifest)
57 const path = entry.path ?? `mods/${entry.dir}`
58 return {
59 dir: entry.dir,
60 path,
61 name: m.name ?? entry.name ?? entry.dir,
62 version: m.version ?? '',
63 description: m.description ?? entry.description ?? '',
64 state: catalog.states[entry.state] ?? entry.state,
65 found,
66 events: eventsIn(src),
67 commands: commandsIn(src),
68 draws: drawsIn(src),
69 blocks: canBlock(src),
70 options,
71 data: entry.data ?? '',
72 note: entry.note ?? '',
73 inside: entry.inside ?? '',
74 tests: entry.tests ?? [],
75 enable: found ? `ajoute <dépôt>/${path} à CLAUDE_CODE_PLUGIN_DIRS, ou lance claude --plugin-dir ${path}` : 'pas encore dans le dépôt',
76 }
77}
78
79/** The same card as Markdown, for MODE-EMPLOI.md. */
80export function cardMarkdown(c: Card): string {
81 const rows = [
82 `#### Fiche ${c.name}`,
83 '',
84 `${c.description || '(pas de description)'}`,
85 '',
86 ...(c.inside ? [`- **Où** : ${c.inside}`] : []),
87 `- **État** : ${c.state}${c.version ? ` · version ${c.version}` : ''}${c.note ? ` · ${c.note}` : ''}`,
88 `- **Fonctionnement** : ${c.found ? `événements ${c.events.map(e => `\`${e}\``).join(', ') || 'aucun'}` : 'pas encore écrit'} · lit : ${c.data || '—'} · ${c.found ? (c.blocks ? '⚠ peut refuser un appel' : 'aucun blocage') : 'sans blocage prévu'}`,
89 `- **Fonctionnalités** : commandes ${c.commands.map(x => `\`${x}\``).join(', ') || 'aucune'} · affiche : ${c.draws.join(', ') || 'rien'} · options userConfig : ${c.options.length ? c.options.join(' ; ') : 'aucune'}`,
90 `- **Activer** : ${c.found ? `\`<dépôt>/${c.path}\` dans \`CLAUDE_CODE_PLUGIN_DIRS\`, ou \`claude --plugin-dir ${c.path}\`` : c.enable}`,
91 `- **Tests** : ${c.tests.length ? c.tests.map(t => `\`${t}\``).join(' · ') : 'aucun pour l’instant'}`,
92 ]
93 return rows.join('\n')
94}
95
96/** The whole "Nos mods" block (a category of Avancé): one sub-section per mod, then the archived / rejected table. */
97export function modsMarkdown(cards: Card[], catalog: ModsCatalog): string {
98 const parts = cards.map(cardMarkdown)
99 parts.push(
100 [
101 '#### Archivés / rejetés',
102 '',
103 '| Mod | Verdict | Pourquoi |',
104 '|---|---|---|',
105 ...catalog.archived.map(a => `| ${a.name} | ${a.verdict} | ${a.why} |`),
106 ].join('\n'),
107 )
108 return parts.join('\n\n')
109}
110hooks/toc.ts 111 lines1// MODE-EMPLOI.md as a tree: `##` = a tab, `###` = a category, `####` = a sub-section.
2// Pure: the pane, the build script (scripts/build.mjs) and node --test all use it.
3import type { Doc, Section, Tab } from '../types'
4
5/** GitHub's heading anchor: lower case, punctuation dropped (letters of any script kept), spaces to dashes. */
6export function slug(title: string): string {
7 return title
8 .trim()
9 .toLowerCase()
10 .replace(/[^\p{L}\p{N}\s_-]/gu, '')
11 .replace(/\s/g, '-')
12}
13
14const TOC = /<!-- toc:start -->[\s\S]*?<!-- toc:end -->/
15
16/** Splits the guide into tabs, categories and sub-sections. The table of contents block is left out of every body. */
17export function parse(md: string): Doc {
18 const text = md.replace(/\r\n/g, '\n').replace(TOC, '')
19 const doc: Doc = { title: '', intro: '', tabs: [] }
20 let tab: Tab | undefined
21 let cat: Section | undefined
22 let sub: Section | undefined
23 const body: string[] = []
24 let fence = false
25 const flush = () => {
26 const t = body.join('\n').trim()
27 body.length = 0
28 if (sub) sub.body = t
29 else if (cat) cat.body = t
30 else if (tab) tab.intro = t
31 else doc.intro = t
32 }
33 for (const line of text.split('\n')) {
34 if (/^\s*```/.test(line)) fence = !fence
35 const m = fence ? null : /^(#{1,4})\s+(.*?)\s*$/.exec(line)
36 if (!m) {
37 body.push(line)
38 continue
39 }
40 const level = m[1]!.length
41 const title = m[2]!
42 flush()
43 if (level === 1) doc.title = title
44 else if (level === 2) {
45 tab = { id: slug(title), title, intro: '', cats: [] }
46 doc.tabs.push(tab)
47 cat = undefined
48 sub = undefined
49 } else if (level === 3 && tab) {
50 cat = { id: slug(title), title, body: '', subs: [] }
51 tab.cats.push(cat)
52 sub = undefined
53 } else if (level === 4 && cat) {
54 sub = { id: slug(title), title, body: '', subs: [] }
55 cat.subs.push(sub)
56 } else body.push(line)
57 }
58 flush()
59 return doc
60}
61
62/** Every anchor of the tree, in order; the build script refuses a duplicate. */
63export function anchors(doc: Doc): string[] {
64 const out: string[] = []
65 for (const t of doc.tabs) {
66 out.push(t.id)
67 for (const c of t.cats) {
68 out.push(c.id)
69 for (const s of c.subs) out.push(s.id)
70 }
71 }
72 return out
73}
74
75/** The table of contents as nested Markdown links to the same anchors. */
76export function tocMarkdown(doc: Doc): string {
77 const lines: string[] = []
78 for (const t of doc.tabs) {
79 lines.push(`- [${t.title}](#${t.id})`)
80 for (const c of t.cats) {
81 lines.push(` - [${c.title}](#${c.id})`)
82 for (const s of c.subs) lines.push(` - [${s.title}](#${s.id})`)
83 }
84 }
85 return lines.join('\n')
86}
87
88/** Puts a fresh table of contents between the markers (the markers must be there). */
89export function withToc(md: string): string {
90 const toc = tocMarkdown(parse(md))
91 return md.replace(TOC, `<!-- toc:start -->\n${toc}\n<!-- toc:end -->`)
92}
93
94/** Replaces what lies between `<!-- name:start -->` and `<!-- name:end -->`. */
95export function between(md: string, name: string, content: string): string {
96 const re = new RegExp(`<!-- ${name}:start -->[\\s\\S]*?<!-- ${name}:end -->`)
97 return md.replace(re, `<!-- ${name}:start -->\n${content}\n<!-- ${name}:end -->`)
98}
99
100/** Where a press on a Sommaire link leads: the tab, the category to unfold and the sub-section to mark. */
101export function locate(doc: Doc, anchor: string): { tab: string; cat: string; sub: string } | undefined {
102 for (const t of doc.tabs) {
103 if (t.id === anchor) return { tab: t.id, cat: '', sub: '' }
104 for (const c of t.cats) {
105 if (c.id === anchor) return { tab: t.id, cat: c.id, sub: '' }
106 for (const s of c.subs) if (s.id === anchor) return { tab: t.id, cat: c.id, sub: s.id }
107 }
108 }
109 return undefined
110}
111types/index.d.ts 61 lines1// Shapes of the guide mod: the parsed MODE-EMPLOI.md, mods.json, a mod card, and its `$.state` values.
2
3export type Section = { id: string; title: string; body: string; subs: Section[] }
4export type Tab = { id: string; title: string; intro: string; cats: Section[] }
5export type Doc = { title: string; intro: string; tabs: Tab[] }
6
7export type CatalogEntry = {
8 /** folder relative to mods/ (an external mod: '../vendor/<name>') */
9 dir: string
10 /** folder relative to the repo, shown in « Activer » (default mods/<dir>) */
11 path?: string
12 name?: string
13 state: string
14 description?: string
15 data?: string
16 note?: string
17 /** where Julian finds it since the 6 hubs: « hub … » for a hub, « dans <hub> … » for an older mod */
18 inside?: string
19 tests?: string[]
20}
21export type ModsCatalog = {
22 states: Record<string, string>
23 mods: CatalogEntry[]
24 archived: { name: string; verdict: string; why: string }[]
25}
26export type Card = {
27 dir: string
28 /** folder relative to the repo */
29 path: string
30 name: string
31 version: string
32 description: string
33 state: string
34 /** the mod's plugin.json was found beside this one */
35 found: boolean
36 events: string[]
37 commands: string[]
38 draws: string[]
39 blocks: boolean
40 options: string[]
41 data: string
42 note: string
43 /** the hub that shows it (mods.json `inside`), '' when not said */
44 inside: string
45 tests: string[]
46 enable: string
47}
48
49declare module 'claude-code' {
50 interface PluginState {
51 guide: {
52 /** tab shown: 'sommaire' or a `##` heading's anchor */
53 tab: string
54 /** category unfolded in that tab ('' = none) */
55 cat: string
56 /** sub-section marked after a Sommaire link ('' = none) */
57 sub: string
58 }
59 }
60}
61