SLOPSHOPPER

charts

Dessine les blocs vega-lite, mermaid et dot des réponses en vraies images (PNG dans Ghostty, SVG sur le desktop).

rowscommandtoastpromptprocess
v0.3.0MITupdated 2026-10-21ThomasTartrau/charts
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · charts
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /charts ⎿ charts: charts on | thème dark | largeur max 100 col | hauteur max 22 lignes | ratio cellule 0.5 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<img alt="charts" src="assets/logo/charts-banner.png" width="520">

License: MIT Claude Code Node

Charts and diagrams in Claude Code, drawn as images instead of code blocks.

Install | What it draws | Usage | How it works | Development


What is charts?

I got tired of reading Vega-Lite JSON in my terminal, so I wrote a mod that draws it.

charts is a Claude Code mod. When Claude writes a `vega-lite , `mermaid or `dot block, the mod replaces it with the picture: a PNG in the terminal, an SVG in the desktop app. The stored message still holds the source, so Claude keeps reading the data, not the image.

It also nudges Claude to draw more. Ask for a comparison and you get a bar chart. Ask how a system works and you get a diagram first, then the parts the diagram can't say.

<img alt="Claude answering with a bar chart in the terminal" src="assets/screens/01-bar.png" width="900">

Install

You need:

  • Claude Code 2.1.280 or newer
  • Node 20 or newer on your PATH
  • For images in the terminal, a terminal with the kitty graphics protocol, such as Ghostty or kitty. Other terminals show the chart's text description instead. Under a multiplexer that hides TERM_PROGRAM (herdr, for instance), Claude Code doesn't detect the graphics protocol: set CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, as long as the multiplexer passes kitty graphics through to the terminal.

1. Turn on function hooks

Mods are still early access, so Claude Code only loads them with this variable set. Add it to ~/.claude/settings.json:

{
  "env": { "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" }
}

2. Add the marketplace and install

claude plugin marketplace add https://gitlab.com/ThomasTartrau/charts.git
claude plugin install charts@tartrau-mods

From inside a session, /plugin marketplace add and /plugin install do the same thing.

Claude Code doesn't install the renderer's npm dependencies. The first chart installs them in the plugin's renderer/ folder (pnpm, or npm without it), which takes a few seconds. Start a new session and ask something with numbers in it.

Updating

claude plugin update charts

What it draws

Charts in replies

Any `vega-lite block, with the mod's theme and a size that fits the terminal.

<img alt="A line chart in a Claude reply" src="assets/screens/02-line.png" width="900">

Diagrams

`mermaid flowcharts, sequence, state, class and ER diagrams, and `dot graphs. Mermaid pie and gantt blocks are turned into Vega-Lite charts so they share the same theme.

<img alt="A mermaid flowchart in a Claude reply" src="assets/screens/04-flowchart.png" width="900"> <img alt="A mermaid sequence diagram in a Claude reply" src="assets/screens/03-sequence.png" width="560">

Every image has an "ouvrir en grand" button that opens a full-size PNG in your image viewer.

Usage

Nothing to call. Ask a question where a chart would help and Claude draws one.

The /charts command shows and changes the settings. They are kept across sessions.

CommandEffect
/chartsShow the current settings
/charts on / offTurn the mod on or off
/charts theme dark / lightMatch your terminal's background
/charts width <20-255>Maximum chart width, in terminal columns (default 100)
/charts rows <3-80>Maximum chart height, in terminal rows (default 22)
/charts cell <0.3-0.8>Width/height ratio of a terminal cell (default 0.5)
/charts resetBack to the defaults

How it works

flowchart LR
    A[Claude reply] --> B[charts mod]
    B -->|spec + theme| C[renderer<br/>node process]
    C --> D[(~/.cache/<br/>claude-charts)]
    C -->|PNG| E[Terminal]
    C -->|SVG| F[Desktop app]
  • hooks/ is the mod: TypeScript hooks that Claude Code loads. It finds chart blocks in each reply, draws them and adds a short guide to the system prompt.
  • renderer/ is a small Node script built on Vega-Lite, beautiful-mermaid, Viz.js (Graphviz) and resvg. The mod starts it once per image.
  • Rendered images are cached in ~/.cache/claude-charts, keyed by a hash of the spec. Scrolling back over an old chart doesn't start Node again.
  • Claude Code draws a block of text only once the block is finished, so a chart shows up when the reply ends. While the reply streams, the chart's source doesn't scroll by: one italic line holds its place, with the chart's title, until the image replaces it.

When a block can't be drawn, usually an invalid spec, you get the source back with the error under it.

Development

Load the folder straight from disk, without installing it:

claude --plugin-dir /path/to/charts

A --plugin-dir copy takes priority over an installed copy with the same name.

npm install                          # renderer dependencies
claude plugin validate .             # manifest and hooks module
claude plugin test .                 # mod tests (tests/*.test.ts)
npm test                             # renderer tests

License

MIT

Source 7 files
hooks/register.tsx 199 lines
1// charts : les blocs ```vega-lite (graphiques), ```mermaid et ```dot (schémas) des réponses
2// sont dessinés en vraies images (PNG via le protocole d'image de Ghostty, SVG sur le
3// desktop). Le message stocké garde la source : le modèle voit toujours les données.
4import type { EngineInterface, Register, RenderElement, RenderInput } from 'claude-code'
5
6import { altOf, drawingOf, type Drawn } from './drawings'
7import { chartBlocksOf, segmentsOf } from './fences'
8import { applyCommand, DEFAULT_PREFS, GUIDE, prefsFrom, statusOf, STORE_KEY, USAGE, type Prefs } from './prefs'
9import {
10  chartColumns,
11  chartRows,
12  clearMemo,
13  maxHeightFor,
14  openInViewer,
15  PX_PER_COLUMN,
16  renderChart,
17  type Drawing,
18  type Run,
19} from './render'
20import { displayOf, hasPlaceholder, restoredFrom, START, type StreamState } from './streaming'
21
22const COMMAND = 'charts'
23/** retrait du texte d'une réponse sous la puce, en colonnes */
24const INDENT = 2
25/** hauteur max d'un schéma, en multiple de la hauteur max d'un graphique */
26const DIAGRAM_ROWS_FACTOR = 2
27
28let prefs: Prefs = DEFAULT_PREFS
29/** Le message qui s'écrit : son id, et le bloc de code ouvert dans ce qui en est déjà affiché. */
30let streaming: { messageId: string; state: StreamState } | null = null
31/** Le texte d'origine des blocs affichés avec une ligne de remplacement, par message : un redessin ne relit pas la session. */
32const restored = new Map<string, string>()
33
34/** Rend l'image en grand, fond plein, et l'ouvre dans la visionneuse du système. */
35function openLarge($: EngineInterface, drawing: Drawing) {
36  const run: Run = (argv, init) => $.process.run(argv, init)
37  openInViewer(run, $.plugin.root, drawing, prefs.theme)
38    .then(error => error && $.ui.toast(`charts : ouverture impossible : ${error}`))
39    .catch(err => $.ui.log(`charts : ouverture impossible : ${err}`))
40}
41
42/**
43 * Le texte d'un bloc fini avec ses sources : le moteur le dessine avec le texte affiché
44 * au streaming, où une ligne tient la place de chaque graphique ; la source est relue
45 * dans le message enregistré. Introuvable, le texte reste tel quel.
46 */
47async function sourceOf($: EngineInterface, requestId: string, text: string): Promise<string> {
48  if (!hasPlaceholder(text)) return text
49  const known = restored.get(requestId)
50  if (known !== undefined) return known
51  const messages = await $.session.messages().catch(err => {
52    $.ui.log(`charts : messages de la session illisibles : ${err}`)
53    return []
54  })
55  // sans agentId, toujours la liste (jamais de deny pour la conversation principale)
56  const replies = Array.isArray(messages) ? messages.filter(m => m.role === 'assistant').map(m => m.text) : []
57  const found = restoredFrom(text, replies)
58  if (found === null) return text
59  restored.set(requestId, found)
60  return found
61}
62
63/** Un graphique ou un schéma prêt à dessiner, ou l'erreur à montrer sous sa source. */
64async function chartElement(
65  $: EngineInterface,
66  e: RenderInput<'AssistantMessage'>,
67  drawn: Drawn,
68  source: string,
69  columns: number,
70  maxRows: number,
71  /** l'adresse du bouton « ouvrir en grand » sous l'image */
72  openKey: string,
73): Promise<RenderElement> {
74  const t = $.ui.resolve(e)
75  const fallback = (reason: string) => (
76    <t.Box flexDirection="column">
77      <t.Markdown text={'```\n' + source + '\n```'} />
78      <t.Text color="red" dimColor wrap="wrap">
79        {`charts : ${reason}`}
80      </t.Text>
81    </t.Box>
82  )
83  if ('error' in drawn) return fallback(drawn.error)
84
85  const surface = e.surface
86  const run: Run = (argv, init) => $.process.run(argv, init)
87  const rendered = await renderChart(run, $.plugin.root, drawn, {
88    width: columns * PX_PER_COLUMN,
89    maxHeight: maxHeightFor(maxRows, prefs.cellAspect),
90    theme: prefs.theme,
91    format: surface === 'terminal' ? 'png' : 'svg',
92  })
93  if (!rendered.ok) return fallback(rendered.error)
94
95  const alt = altOf(drawn)
96  const withOpen = (image: RenderElement) => (
97    <t.Box flexDirection="column">
98      {image}
99      <t.Button key={openKey} plain dimColor onPress={() => openLarge($, drawn)}>
100        ouvrir en grand
101      </t.Button>
102    </t.Box>
103  )
104  if ('Image' in t && rendered.file) {
105    // un schéma ou une spec composite peut sortir plus étroit que demandé
106    let width = Math.min(columns, Math.ceil(rendered.width / PX_PER_COLUMN))
107    const natural = chartRows(width, rendered.width, rendered.height, prefs.cellAspect)
108    // plus haute que la place (hauteur fixée par la spec) : réduite en largeur aussi, sinon écrasée
109    if (natural > maxRows) width = Math.max(1, Math.round((width * maxRows) / natural))
110    const rows = Math.min(maxRows, natural)
111    return withOpen(<t.Image source={{ file: rendered.file, format: 'png' }} columns={width} rows={rows} alt={alt} />)
112  }
113  if ('Svg' in t && rendered.svg) {
114    if (rendered.svg.length > 131_072) return fallback('SVG trop lourd pour la surface (plus de 128 Kio)')
115    return withOpen(<t.Svg source={rendered.svg} alt={alt} width={rendered.width} />)
116  }
117  return fallback(`surface ${surface} sans image`)
118}
119
120export const register: Register = on => {
121  on('session.start', async ($, e, next) => {
122    const started = await next(e)
123    prefs = prefsFrom(await $.store.get(STORE_KEY).catch(() => undefined))
124    await $.command
125      .register({
126        name: COMMAND,
127        description: 'Graphiques vega-lite et schémas dot dessinés en images : on|off, theme, width, rows, cell, reset (charts)',
128        argumentHint: '[on|off|theme dark|light|width N|rows N|cell R|reset]',
129        immediate: true,
130      })
131      .catch(err => $.ui.log(`charts : /${COMMAND} non enregistrée : ${err}`))
132    return started
133  })
134
135  on('command.run', { command: COMMAND }, async ($, e) => {
136    const applied = applyCommand(prefs, e.args)
137    if ('error' in applied) return { text: `${applied.error}\n${USAGE}` }
138    if (applied.prefs !== prefs) {
139      prefs = applied.prefs
140      await $.store.set(STORE_KEY, prefs).catch(err => $.ui.log(`charts : écriture du store impossible : ${err}`))
141      clearMemo()
142      $.ui.invalidate('ui.render')
143    }
144    return { text: statusOf(prefs) }
145  })
146
147  // Le modèle apprend à montrer avant d'écrire : graphiques et schémas par défaut.
148  on('prompt.compose', async ($, e, next) => {
149    const composed = await next(e)
150    if (!prefs.enabled || e.surfaces.length === 0) return composed
151    return { sections: [...composed.sections, { id: 'charts:guide', text: GUIDE, scope: 'session' as const }] }
152  })
153
154  // Au streaming : la source d'un graphique ne défile pas, une ligne tient sa place
155  // jusqu'à l'image (le bloc fini, plus bas).
156  on('classic.MessageDisplay', async ($, e, next) => {
157    const shown = await next(e)
158    if (!prefs.enabled) return shown
159    const state = streaming?.messageId === e.message_id ? streaming.state : START
160    const display = displayOf(state, shown.displayContent ?? e.delta)
161    streaming = e.final ? null : { messageId: e.message_id, state: display.state }
162    return { ...shown, displayContent: display.text }
163  })
164
165  // Graphiques et schémas dans les réponses, à la place de leur bloc.
166  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
167    if (!prefs.enabled) return next(e)
168    const text = await sourceOf($, e.requestId, e.props.text)
169    if (text !== e.props.text) e = { ...e, props: { ...e.props, text } }
170    const blocks = chartBlocksOf(e.props.text)
171    if (blocks.length === 0) return next(e)
172
173    const t = $.ui.resolve(e)
174    const chartSize = { columns: chartColumns(e.viewport?.columns, prefs.maxColumns, INDENT), rows: prefs.maxRows }
175    // un schéma prend toute la largeur et deux fois la hauteur d'un graphique : réduit, il devient illisible
176    const diagramSize = { columns: chartColumns(e.viewport?.columns, 255, INDENT), rows: prefs.maxRows * DIAGRAM_ROWS_FACTOR }
177    const segments = segmentsOf(e.props.text, blocks)
178    const [first, ...rest] = segments
179
180    // Le premier segment texte passe par le moteur, qui garde la puce et le style.
181    const lead = first?.kind === 'text' ? first.text : first?.block.kind === 'vega-lite' ? 'Graphique :' : 'Schéma :'
182    const children: RenderElement[] = [await next({ ...e, props: { ...e.props, text: lead } })]
183    const tail = first?.kind === 'text' ? rest : segments
184
185    // un process node par image : rendus en parallèle
186    const bodies = await Promise.all(
187      tail.map((segment, i) => {
188        if (segment.kind === 'text') return <t.Markdown text={segment.text} />
189        const drawn = drawingOf(segment.block)
190        // un camembert ou un gantt mermaid est devenu un graphique : taille de graphique
191        const size = 'kind' in drawn && drawn.kind !== 'vega-lite' ? diagramSize : chartSize
192        return chartElement($, e, drawn, segment.block.source, size.columns, size.rows, `open-${i}`)
193      }),
194    )
195    for (const body of bodies) children.push(<t.Box paddingLeft={INDENT}>{body}</t.Box>)
196    return <t.Box flexDirection="column" gap={1}>{children}</t.Box>
197  })
198}
199
hooks/drawings.ts 33 lines
1// Ce qu'un bloc devient pour le renderer, et le texte alternatif de son image.
2import { parseSpec, type ChartBlock } from './fences'
3import { mermaidChart } from './mermaid-charts'
4import type { Drawing } from './render'
5
6export type Drawn = Drawing | { error: string }
7
8/** Un bloc à dessiner ; un camembert ou un gantt mermaid devient un graphique vega-lite. */
9export function drawingOf(block: ChartBlock): Drawn {
10  if (block.kind === 'vega-lite') {
11    const parsed = parseSpec(block.source)
12    return 'spec' in parsed ? { kind: 'vega-lite', spec: parsed.spec } : parsed
13  }
14  const chart = block.kind === 'mermaid' ? mermaidChart(block.source) : null
15  if (chart) return 'spec' in chart ? { kind: 'vega-lite', spec: chart.spec } : chart
16  return { kind: block.kind, source: block.source }
17}
18
19export function altOf(drawing: Drawing): string {
20  if (drawing.kind !== 'vega-lite') {
21    // mermaid : le type en tête (sequenceDiagram) ; dot : le nom du graphe
22    const name =
23      drawing.kind === 'mermaid'
24        ? drawing.source.trim().split(/\s/)[0]
25        : /^\s*(?:strict\s+)?(?:di)?graph\s+"?([^\s{"]+)/i.exec(drawing.source)?.[1]
26    return name ? `schéma ${name}` : 'schéma'
27  }
28  const pick = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : null)
29  const { title, description } = drawing.spec
30  const titleText = typeof title === 'object' && title !== null ? Reflect.get(title, 'text') : title
31  return pick(description) ?? pick(titleText) ?? 'graphique vega-lite'
32}
33
hooks/fences.ts 99 lines
1// Repérage des blocs ```vega-lite, ```mermaid et ```dot fermés dans un texte markdown, et
2// découpage du texte en segments texte / graphique, dans l'ordre.
3
4export type BlockKind = 'vega-lite' | 'mermaid' | 'dot'
5
6export type ChartBlock = {
7  /** graphique de données (vega-lite) ou schéma (mermaid, Graphviz DOT) */
8  kind: BlockKind
9  /** début du bloc entier, ligne d'ouverture comprise */
10  start: number
11  /** fin du bloc entier, ligne de fermeture comprise */
12  end: number
13  /** le contenu entre les deux lignes de fence : JSON vega-lite ou texte DOT */
14  source: string
15}
16
17export type Segment = { kind: 'text'; text: string } | { kind: 'chart'; block: ChartBlock }
18
19export type ParsedSpec = { spec: Record<string, unknown> } | { error: string }
20
21const LANGS = new Map<string, BlockKind>([
22  ['vega-lite', 'vega-lite'],
23  ['vegalite', 'vega-lite'],
24  ['vl', 'vega-lite'],
25  ['mermaid', 'mermaid'],
26  ['dot', 'dot'],
27  ['graphviz', 'dot'],
28])
29
30// Ouverture : indentation, 3+ backticks ou tildes, info string. La fermeture
31// doit utiliser le même caractère, au moins aussi long, seule sur sa ligne.
32const OPEN = /^([ \t]*)(`{3,}|~{3,})[ \t]*([^\s`]*)[^\n]*$/
33
34/** La ligne ouvre un bloc de code : sa fence, et son type quand c'est un graphique ou un schéma. */
35export function fenceOpening(line: string): { fence: string; kind: BlockKind | undefined } | null {
36  const match = OPEN.exec(line)
37  if (!match) return null
38  return { fence: match[2] ?? '```', kind: LANGS.get((match[3] ?? '').toLowerCase()) }
39}
40
41/** La ligne ferme le bloc ouvert par `fence`. */
42export function closesFence(line: string, fence: string): boolean {
43  const trimmed = line.trim()
44  return trimmed.length >= fence.length && trimmed[0] === fence[0] && [...trimmed].every(c => c === fence[0])
45}
46
47export function chartBlocksOf(text: string): ChartBlock[] {
48  const blocks: ChartBlock[] = []
49  const lines = text.split('\n')
50  let offset = 0
51  let open: { start: number; fence: string; kind: BlockKind | undefined; bodyStart: number } | null = null
52
53  for (const line of lines) {
54    const lineEnd = offset + line.length
55    if (open === null) {
56      const opening = fenceOpening(line)
57      if (opening) open = { start: offset, ...opening, bodyStart: lineEnd + 1 }
58    } else {
59      if (closesFence(line, open.fence)) {
60        if (open.kind) {
61          const source = text.slice(open.bodyStart, Math.max(open.bodyStart, offset - 1)).trim()
62          if (source.length > 0) blocks.push({ kind: open.kind, start: open.start, end: lineEnd, source })
63        }
64        open = null
65      }
66    }
67    offset = lineEnd + 1
68  }
69  // un bloc encore ouvert (réponse en streaming) n'est pas un graphique
70  return blocks
71}
72
73export function segmentsOf(text: string, blocks: readonly ChartBlock[]): Segment[] {
74  const segments: Segment[] = []
75  let cursor = 0
76  for (const block of blocks) {
77    const before = text.slice(cursor, block.start).replace(/\n+$/, '')
78    if (before.trim().length > 0) segments.push({ kind: 'text', text: before })
79    segments.push({ kind: 'chart', block })
80    cursor = block.end
81  }
82  const after = text.slice(cursor).replace(/^\n+/, '')
83  if (after.trim().length > 0) segments.push({ kind: 'text', text: after })
84  return segments
85}
86
87export function parseSpec(source: string): ParsedSpec {
88  let value: unknown
89  try {
90    value = JSON.parse(source)
91  } catch (error) {
92    return { error: `JSON invalide : ${error instanceof Error ? error.message : String(error)}` }
93  }
94  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
95    return { error: 'la spec doit être un objet JSON' }
96  }
97  return { spec: value as Record<string, unknown> }
98}
99
hooks/prefs.ts 81 lines
1// Préférences du mod, gardées dans $.store, et la commande /charts qui les change.
2import type { Theme } from './render'
3
4export type Prefs = {
5  enabled: boolean
6  theme: Theme
7  /** largeur maximale d'un graphique, en colonnes de terminal */
8  maxColumns: number
9  /** hauteur maximale d'un graphique, en lignes de terminal */
10  maxRows: number
11  /** largeur / hauteur d'une cellule du terminal (Ghostty, JetBrains Mono : environ 0,5) */
12  cellAspect: number
13}
14
15export const DEFAULT_PREFS: Prefs = { enabled: true, theme: 'dark', maxColumns: 100, maxRows: 22, cellAspect: 0.5 }
16
17export const STORE_KEY = 'prefs'
18
19export function prefsFrom(stored: unknown): Prefs {
20  if (stored === null || typeof stored !== 'object') return DEFAULT_PREFS
21  const merged = { ...DEFAULT_PREFS, ...(stored as Partial<Prefs>) }
22  const isValid =
23    typeof merged.enabled === 'boolean' &&
24    (merged.theme === 'dark' || merged.theme === 'light') &&
25    Number.isFinite(merged.maxColumns) &&
26    Number.isFinite(merged.maxRows) &&
27    Number.isFinite(merged.cellAspect)
28  return isValid ? merged : DEFAULT_PREFS
29}
30
31export function statusOf(p: Prefs): string {
32  return [
33    `charts ${p.enabled ? 'on' : 'off'}`,
34    `thème ${p.theme}`,
35    `largeur max ${p.maxColumns} col`,
36    `hauteur max ${p.maxRows} lignes`,
37    `ratio cellule ${p.cellAspect}`,
38  ].join(' | ')
39}
40
41export const USAGE = '/charts [on|off] | theme dark|light | width <20-255> | rows <3-80> | cell <0.3-0.8> | reset'
42
43/** Applique les arguments de /charts ; renvoie les nouvelles préférences ou une erreur. */
44export function applyCommand(p: Prefs, args: string): { prefs: Prefs } | { error: string } {
45  const [word = '', value = ''] = args.trim().toLowerCase().split(/\s+/)
46  const n = Number(value.replace(',', '.'))
47  switch (word) {
48    case '':
49    case 'status':
50      return { prefs: p }
51    case 'on':
52      return { prefs: { ...p, enabled: true } }
53    case 'off':
54      return { prefs: { ...p, enabled: false } }
55    case 'reset':
56      return { prefs: DEFAULT_PREFS }
57    case 'theme':
58      return value === 'dark' || value === 'light' ? { prefs: { ...p, theme: value } } : { error: 'thème : dark ou light' }
59    case 'width':
60      return Number.isInteger(n) && n >= 20 && n <= 255 ? { prefs: { ...p, maxColumns: n } } : { error: 'width : entier de 20 à 255' }
61    case 'rows':
62      return Number.isInteger(n) && n >= 3 && n <= 80 ? { prefs: { ...p, maxRows: n } } : { error: 'rows : entier de 3 à 80' }
63    case 'cell':
64      return n >= 0.3 && n <= 0.8 ? { prefs: { ...p, cellAspect: n } } : { error: 'cell : nombre de 0.3 à 0.8' }
65    default:
66      return { error: `argument inconnu : ${word}. ${USAGE}` }
67  }
68}
69
70export const GUIDE = [
71  '# Charts and diagrams by default',
72  'This session draws ```vega-lite (data charts), ```mermaid and ```dot (diagrams) code blocks as real images (terminal and desktop). The person understands a picture faster than prose: show, then tell. Do not wait to be asked for a chart or a diagram.',
73  'Add a diagram, unprompted, whenever you explain how something works or is built: architecture, components and their calls, a pipeline or data flow, a request lifecycle, who talks to whom and in what order, a state machine, data models and their relations, a decision flow. Then explain only what the diagram cannot show.',
74  'Diagrams: write ```mermaid by default, picking the type that fits: flowchart TD or LR (architecture, pipelines, decisions, subgraph for layers or services), sequenceDiagram (calls in time order between actors), stateDiagram-v2 (lifecycles, statuses), classDiagram (types and their links), erDiagram (tables and relations), gantt (a plan or schedule: sections, tasks with dates as YYYY-MM-DD or YYYY-MM-DD HH:mm, durations like 3d, after id, milestone), pie (a share of a whole, at most 8 slices). No mindmap, timeline or journey. Use ```dot only for a large graph that needs automatic layout with clusters.',
75  'Diagram style: short labels (2 to 4 words, <br/> in mermaid or \\n in dot for a second line), edge labels only when they carry information, at most about 20 nodes; split a bigger system into several diagrams. Do not set colors, classDef, style, themes, fonts or init directives: the mod applies its theme. Never use ASCII art for diagrams.',
76  'Add a vega-lite block, unprompted, whenever an answer holds any of: two or more comparable quantities (durations, costs, sizes, counts, scores); a trend or anything over time; a before/after; a distribution; a ranking. For a share of a whole write a mermaid pie, for a schedule a mermaid gantt.',
77  'Lead with the chart, then one or two sentences: the conclusion and the one or two figures that matter. No table that repeats what the chart shows, no ASCII chart.',
78  'Spec: Vega-Lite v6 JSON, data inline in data.values, a short title. Do not set width, height, colors, background or config: the mod applies size and theme. One chart per block, at most 8 series, one y axis; several measures of different units go in separate blocks.',
79  'Use measured figures. When a value is an estimate, say so in the title ("estimation") and never present it as measured.',
80].join('\n')
81
hooks/render.ts 172 lines
1// Appel du moteur de rendu (renderer/render.mjs, un process node) et calcul de
2// la taille en cellules. Le module de hooks n'a ni Node ni DOM : vega tourne
3// dans ce process séparé, qui écrit le PNG que le terminal lit lui-même.
4import type { ProcessRunInit, ProcessRunResult } from 'claude-code'
5
6/** `$.process.run`, passé depuis register.tsx ($ ne traverse pas les imports). */
7export type Run = (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>
8
9export type Theme = 'dark' | 'light'
10export type Format = 'png' | 'svg'
11
12export type Rendered =
13  | { ok: true; file?: string; svg?: string; width: number; height: number }
14  | { ok: false; error: string; isTransient?: boolean }
15
16/** Pixels CSS dessinés par colonne de terminal ; le PNG est rendu en x2. */
17export const PX_PER_COLUMN = 8
18
19const NODES = ['node', '/opt/homebrew/bin/node', '/usr/local/bin/node']
20/** pnpm d'abord (le lockfile du renderer est le sien), npm sinon */
21const INSTALLERS = [
22  ...['pnpm', '/opt/homebrew/bin/pnpm', '/usr/local/bin/pnpm'].map(bin => [bin, 'install', '--prod', '--frozen-lockfile']),
23  ...['npm', '/opt/homebrew/bin/npm', '/usr/local/bin/npm'].map(bin => [bin, 'install', '--omit=dev', '--no-audit', '--no-fund']),
24]
25/** npm et pnpm se lancent par `#!/usr/bin/env node` : node doit être sur le PATH */
26const INSTALL_PATH = '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin'
27const MISSING_DEPENDENCY = /Cannot find (package|module) '[^.'/][^']*'/
28/** une installation par process : les rendus qui la rencontrent l'attendent tous */
29let installing: Promise<string | null> | undefined
30/** macOS, puis Linux */
31const OPENERS = ['/usr/bin/open', 'xdg-open']
32const MEMO_SIZE = 64
33const memo = new Map<string, Promise<Rendered>>()
34
35export function chartColumns(viewportColumns: number | undefined, maxColumns: number, indent: number): number {
36  const available = (viewportColumns ?? 100) - indent - 2
37  return Math.max(20, Math.min(maxColumns, available, 255))
38}
39
40/** Hauteur maximale en pixels CSS pour tenir dans `maxRows` lignes de terminal. */
41export function maxHeightFor(maxRows: number, cellAspect: number): number {
42  return Math.round((maxRows * PX_PER_COLUMN) / cellAspect)
43}
44
45/** Lignes de terminal pour garder le ratio du PNG (cellAspect = largeur / hauteur d'une cellule). */
46export function chartRows(columns: number, width: number, height: number, cellAspect: number): number {
47  const rows = Math.round((columns * cellAspect * height) / width)
48  return Math.max(3, Math.min(rows, 255))
49}
50
51function isRendered(value: unknown): value is Rendered {
52  return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'ok') === 'boolean'
53}
54
55async function runRenderer(run: Run, root: string, input: string): Promise<Rendered> {
56  const script = `${root}/renderer/render.mjs`
57  let lastError = 'node introuvable'
58  for (const node of NODES) {
59    const attempt = await run([node, script], { stdin: input, timeoutMs: 20_000 }).then(
60      ran => ({ ran }),
61      (error: unknown) => ({ failed: error instanceof Error ? error.message : String(error) }),
62    )
63    if ('failed' in attempt) {
64      // Seul un binaire absent fait essayer le suivant. Un rendu abandonné (zoom :
65      // le moteur tue le process) ou trop long n'a rien à voir avec ce binaire.
66      if (!attempt.failed.includes('failed to start')) return { ok: false, error: attempt.failed, isTransient: true }
67      lastError = attempt.failed
68      continue
69    }
70    const { ran } = attempt
71    if (ran.exitCode !== 0 && ran.stdout.trim() === '') {
72      return { ok: false, error: ran.stderr.trim().slice(0, 300) || `exit ${ran.exitCode}` }
73    }
74    try {
75      const parsed: unknown = JSON.parse(ran.stdout)
76      return isRendered(parsed) ? parsed : { ok: false, error: 'réponse du renderer illisible' }
77    } catch {
78      return { ok: false, error: `sortie du renderer illisible : ${ran.stdout.slice(0, 120)}` }
79    }
80  }
81  return { ok: false, error: lastError }
82}
83
84/**
85 * Installe les dépendances du renderer. Claude Code copie le plugin sans
86 * `renderer/node_modules` (ignoré par git) et n'y lance aucune installation.
87 * Rend l'erreur, ou null.
88 */
89async function installDependencies(run: Run, root: string): Promise<string | null> {
90  let lastError = 'ni pnpm ni npm introuvable'
91  for (const argv of INSTALLERS) {
92    const ran = await run(argv, { cwd: `${root}/renderer`, env: { PATH: INSTALL_PATH }, timeoutMs: 300_000 }).catch(
93      (error: unknown) => ({ failed: error instanceof Error ? error.message : String(error) }),
94    )
95    if ('failed' in ran) {
96      if (!ran.failed.includes('failed to start')) return ran.failed
97      lastError = ran.failed
98      continue
99    }
100    return ran.exitCode === 0 ? null : (ran.stderr.trim() || ran.stdout.trim()).slice(-300) || `${argv[0]} : exit ${ran.exitCode}`
101  }
102  return lastError
103}
104
105async function renderWithDependencies(run: Run, root: string, input: string): Promise<Rendered> {
106  const rendered = await runRenderer(run, root, input)
107  if (rendered.ok || !MISSING_DEPENDENCY.test(rendered.error)) return rendered
108  installing ??= installDependencies(run, root)
109  const failed = await installing
110  if (failed) return { ok: false, error: `dépendances du renderer non installées (${root}/renderer) : ${failed}` }
111  return runRenderer(run, root, input)
112}
113
114/** Ce que le renderer dessine : une spec vega-lite, ou la source texte d'un schéma. */
115export type Drawing = { kind: 'vega-lite'; spec: Record<string, unknown> } | { kind: 'mermaid' | 'dot'; source: string }
116
117export function renderChart(
118  run: Run,
119  root: string,
120  drawing: Drawing,
121  options: { width: number; maxHeight: number; theme: Theme; format: Format; scale?: number; opaque?: boolean },
122): Promise<Rendered> {
123  const input = JSON.stringify({ ...drawing, ...options })
124  const cached = memo.get(input)
125  if (cached) {
126    // remis en fin de file : les graphiques encore affichés restent en mémoire
127    memo.delete(input)
128    memo.set(input, cached)
129    // l'échec passager d'un autre rendu (abandonné pendant un zoom) ne vaut pas pour celui-ci : une relance
130    return cached.then(rendered => {
131      if (rendered.ok || !rendered.isTransient) return rendered
132      const fresh = memo.get(input)
133      return fresh && fresh !== cached ? fresh : startRender(run, root, input)
134    })
135  }
136  return startRender(run, root, input)
137}
138
139function startRender(run: Run, root: string, input: string): Promise<Rendered> {
140  const pending = renderWithDependencies(run, root, input)
141  // le cache disque du renderer prend le relais : on ne garde que les plus récents (SVG lourds)
142  if (memo.size >= MEMO_SIZE) memo.delete(memo.keys().next().value!)
143  memo.set(input, pending)
144  // un échec passager n'est pas gardé : le rendu suivant relance node
145  void pending.then(rendered => {
146    if (!rendered.ok && rendered.isTransient && memo.get(input) === pending) memo.delete(input)
147  })
148  return pending
149}
150
151/**
152 * « Ouvrir en grand » : un graphique sur 1400 px, un schéma à sa taille naturelle, en x2
153 * et sur fond plein (la visionneuse n'a pas le fond du terminal), ouvert par le système.
154 * Rend l'erreur à montrer, ou null.
155 */
156export async function openInViewer(run: Run, root: string, drawing: Drawing, theme: Theme): Promise<string | null> {
157  const size = drawing.kind === 'vega-lite' ? { width: 1400, maxHeight: 900 } : { width: 8000, maxHeight: 8000 }
158  const rendered = await renderChart(run, root, drawing, { ...size, theme, format: 'png', scale: 2, opaque: true })
159  if (!rendered.ok) return rendered.error
160  if (!rendered.file) return "le renderer n'a pas écrit de PNG"
161  for (const opener of OPENERS) {
162    // rejeté : ce binaire n'existe pas ici, on essaie le suivant
163    const ran = await run([opener, rendered.file], { timeoutMs: 10_000 }).catch(() => null)
164    if (ran) return ran.exitCode === 0 ? null : ran.stderr.trim() || `${opener} : exit ${ran.exitCode}`
165  }
166  return `ni ${OPENERS.join(' ni ')} ne démarre`
167}
168
169export function clearMemo(): void {
170  memo.clear()
171}
172
hooks/streaming.ts 93 lines
1// Pendant le streaming, le moteur ne dessine un bloc de texte qu'une fois ce bloc
2// terminé : un graphique n'apparaît qu'à la fin de la réponse, et sa source défile
3// en attendant. Le texte qui défile cache donc la source d'un graphique ou d'un
4// schéma et la remplace, à la fence fermante, par une ligne qui dit où il viendra.
5
6import { chartBlocksOf, closesFence, fenceOpening, parseSpec, type BlockKind } from './fences'
7
8export type StreamState = {
9  /** le bloc de code ouvert dans le texte déjà vu ; `kind` absent pour un code ordinaire, laissé visible */
10  open: { fence: string; kind: BlockKind | undefined; body: string[] } | null
11}
12
13export const START: StreamState = { open: null }
14
15/** Le titre d'une spec vega-lite, quand elle en a un lisible. */
16function titleOf(source: string): string | undefined {
17  const parsed = parseSpec(source)
18  if (!('spec' in parsed)) return undefined
19  const title = parsed.spec.title
20  const text = typeof title === 'object' && title !== null && !Array.isArray(title) ? (title as { text?: unknown }).text : title
21  const line = Array.isArray(text) ? text.join(' ') : text
22  return typeof line === 'string' && line.trim() ? line.trim() : undefined
23}
24
25/** La ligne qui tient la place d'un bloc fermé jusqu'à son image. */
26export function placeholderOf(kind: BlockKind, source: string): string {
27  if (kind !== 'vega-lite') return `*Schéma ${kind} : dessiné à la fin de la réponse*`
28  const title = titleOf(source)
29  return title ? `*Graphique "${title}" : dessiné à la fin de la réponse*` : '*Graphique : dessiné à la fin de la réponse*'
30}
31
32/** Le texte à afficher pour un lot de lignes reçues, et l'état pour le lot suivant. */
33export function displayOf(state: StreamState, delta: string): { state: StreamState; text: string } {
34  let open = state.open
35  const shown: string[] = []
36  // le dernier élément est vide quand le lot finit sur un saut de ligne : il ne se rejoint pas
37  const lines = delta.split('\n')
38  const isWhole = delta.endsWith('\n')
39  for (const [i, line] of lines.entries()) {
40    if (isWhole && i === lines.length - 1) break
41    if (open === null) {
42      const opening = fenceOpening(line)
43      if (opening) open = { ...opening, body: [] }
44      if (!opening?.kind) shown.push(line)
45    } else if (closesFence(line, open.fence)) {
46      shown.push(open.kind ? placeholderOf(open.kind, open.body.join('\n')) : line)
47      open = null
48    } else {
49      if (open.kind) open = { ...open, body: [...open.body, line] }
50      else shown.push(line)
51    }
52  }
53  const text = shown.length === 0 ? '' : shown.join('\n') + (isWhole ? '\n' : '')
54  return { state: { open }, text }
55}
56
57// « Graphique : ... » sans titre, « Graphique "Titre" : ... » avec
58const PLACEHOLDER = /^\*(?:Graphique|Schéma)(?: .*)? : dessiné à la fin de la réponse\*$/m
59
60/** Le texte vient du streaming : une ligne y tient la place d'un graphique. */
61export function hasPlaceholder(text: string): boolean {
62  return PLACEHOLDER.test(text)
63}
64
65const squeezed = (text: string) => text.replace(/\s+/g, ' ').trim()
66
67/**
68 * Le moteur garde le texte affiché au streaming pour dessiner le bloc fini : on
69 * remet la source à la place de chaque ligne de remplacement, prise dans le
70 * message enregistré (`stored`, du plus ancien au plus récent) qui a donné ce
71 * texte. null quand aucun ne l'a donné.
72 */
73export function restoredFrom(shown: string, stored: readonly string[]): string | null {
74  for (const original of stored.toReversed()) {
75    // ce message, transformé, contient le texte affiché : c'est le bon, même joint à d'autres blocs
76    if (!squeezed(displayOf(START, original).text).includes(squeezed(shown))) continue
77    const blocks = chartBlocksOf(original).map(block => ({
78      placeholder: placeholderOf(block.kind, block.source),
79      fenced: original.slice(block.start, block.end),
80    }))
81    let next = 0
82    const lines = shown.split('\n').map(line => {
83      if (!PLACEHOLDER.test(line)) return line
84      const at = blocks.findIndex((block, i) => i >= next && block.placeholder === line)
85      if (at < 0) return line
86      next = at + 1
87      return blocks[at]!.fenced
88    })
89    if (next > 0) return lines.join('\n')
90  }
91  return null
92}
93
hooks/mermaid-charts.ts 229 lines
1// Les camemberts (pie) et les diagrammes de Gantt mermaid, que beautiful-mermaid ne
2// dessine pas, traduits en specs vega-lite : même renderer et même thème que les graphiques.
3import type { ParsedSpec } from './fences'
4
5const SCHEMA = 'https://vega.github.io/schema/vega-lite/v6.json'
6/** la palette a 8 couleurs, jamais recyclées : au-delà, les plus petites parts sont regroupées */
7const MAX_SLICES = 8
8const PIE_PX = 220
9const GANTT_ROW_PX = 24
10/** l'axe des dates sous les barres, et la place d'un titre ou d'une légende au-dessus */
11const GANTT_AXIS_PX = 30
12const GANTT_BAND_PX = 30
13
14const SLICE = /^"([^"]+)"\s*:\s*(\d+(?:\.\d+)?)$/
15const DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/
16const DURATION = /^(\d+(?:\.\d+)?)(ms|s|m|h|d|w)$/
17const DAY_MS = 864e5
18const UNIT_MS: Record<string, number> = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: DAY_MS, w: 7 * DAY_MS }
19const TAGS = new Set(['done', 'active', 'crit', 'milestone'])
20// réglages mermaid sans effet ici : les dates sont lues en YYYY-MM-DD [HH:mm], sans jours exclus
21const IGNORED = /^(dateFormat|excludes|includes|todayMarker|tickInterval|weekday|weekend|inclusiveEndDates|topAxis|displayMode|accTitle|accDescr|click)\b/
22
23type Task = { name: string; section: string; start: number; end: number; tags: string[] }
24type Found = { at: number } | { error: string }
25
26/** Un camembert ou un gantt traduit, son erreur, ou null pour les autres types mermaid. */
27export function mermaidChart(source: string): ParsedSpec | null {
28  const lines = source
29    .split('\n')
30    .map(line => line.trim())
31    .filter(line => line !== '' && !line.startsWith('%%'))
32  const [first = '', ...rest] = lines
33  const type = first.split(/\s/)[0]
34  if (type === 'pie') return pieSpec(first.slice(3).trim(), rest)
35  if (type === 'gantt') return ganttSpec(rest)
36  return null
37}
38
39function pieSpec(header: string, lines: readonly string[]): ParsedSpec {
40  let title: string | undefined
41  let showData = false
42  const slices: { name: string; value: number }[] = []
43  // l'en-tête peut porter showData et le titre : `pie showData title Animaux`
44  for (const raw of [header, ...lines]) {
45    let line = raw
46    if (/^showData\b/.test(line)) {
47      showData = true
48      line = line.slice('showData'.length).trim()
49    }
50    if (line === '' || /^acc(Title|Descr)\b/.test(line)) continue
51    const titled = /^title\s+(.+)$/.exec(line)
52    if (titled) {
53      title = titled[1]
54      continue
55    }
56    const slice = SLICE.exec(line)
57    if (!slice) return { error: `pie : ligne illisible : ${line}` }
58    slices.push({ name: slice[1]!, value: Number(slice[2]) })
59  }
60  const total = slices.reduce((sum, s) => sum + s.value, 0)
61  if (total <= 0) return { error: 'pie : aucune part non nulle' }
62
63  const sorted = slices.toSorted((a, b) => b.value - a.value)
64  const kept =
65    sorted.length <= MAX_SLICES
66      ? sorted
67      : [...sorted.slice(0, MAX_SLICES - 1), { name: 'Autres', value: sorted.slice(MAX_SLICES - 1).reduce((sum, s) => sum + s.value, 0) }]
68  const values = kept.map((s, rank) => {
69    const share = (s.value / total) * 100
70    const percent = share > 0 && share < 1 ? '<1 %' : `${Math.round(share)} %`
71    return { rank, value: s.value, label: showData ? `${s.name}  ${s.value} (${percent})` : `${s.name}  ${percent}` }
72  })
73  return {
74    spec: {
75      $schema: SCHEMA,
76      ...(title ? { title } : {}),
77      description: title ?? 'camembert',
78      width: PIE_PX,
79      height: PIE_PX,
80      data: { values },
81      mark: { type: 'arc', padAngle: 0.012 },
82      encoding: {
83        theta: { field: 'value', type: 'quantitative', stack: true },
84        order: { field: 'rank', type: 'quantitative' },
85        color: { field: 'label', type: 'nominal', sort: null, legend: { title: null, orient: 'right', direction: 'vertical', labelLimit: 400 } },
86      },
87    },
88  }
89}
90
91function ganttSpec(lines: readonly string[]): ParsedSpec {
92  let title: string | undefined
93  let axisFormat: string | undefined
94  let section = ''
95  const tasks: Task[] = []
96  const byId = new Map<string, Task>()
97  for (const line of lines) {
98    const directive = /^(title|axisFormat|section)\s+(.+)$/.exec(line)
99    if (directive) {
100      const value = directive[2]!
101      if (directive[1] === 'title') title = value
102      else if (directive[1] === 'axisFormat') axisFormat = value
103      else section = value
104      continue
105    }
106    if (IGNORED.test(line)) continue
107    const colon = line.indexOf(':')
108    if (colon <= 0) return { error: `gantt : ligne illisible : ${line}` }
109    const name = line.slice(0, colon).trim()
110    const read = taskOf(name, line.slice(colon + 1), section, tasks.at(-1), byId)
111    if ('error' in read) return { error: `gantt : "${name}" : ${read.error}` }
112    tasks.push(read.task)
113    if (read.id) byId.set(read.id, read.task)
114  }
115  if (tasks.length === 0) return { error: 'gantt : aucune tâche' }
116
117  const sections = [...new Set(tasks.map(t => t.section))]
118  const values = tasks.map(t => ({
119    task: t.tags.includes('crit') ? `${t.name} (critique)` : t.name,
120    section: t.section || 'tâches',
121    start: new Date(t.start).toISOString(),
122    end: new Date(t.end).toISOString(),
123    isDone: t.tags.includes('done'),
124    isMilestone: t.tags.includes('milestone'),
125  }))
126  // l'heure mermaid est celle écrite : échelle UTC, sinon le fuseau décale les jours
127  // sans axisFormat, vega écrit les dates en anglais (Fri 02, Oct 04) : jour/mois, et l'heure s'il y en a
128  const hasTimes = tasks.some(t => t.start % DAY_MS !== 0 || t.end % DAY_MS !== 0)
129  const format = axisFormat ?? (hasTimes ? '%d/%m %Hh%M' : '%d/%m')
130  const x = { field: 'start', type: 'temporal', scale: { type: 'utc' }, axis: { title: null, format } }
131  const hasSections = sections.length > 1 || sections[0] !== ''
132  return {
133    spec: {
134      $schema: SCHEMA,
135      ...(title ? { title } : {}),
136      description: title ?? 'diagramme de Gantt',
137      // le renderer fait tenir le tout (titre, légende, axe) dans la hauteur : on les ajoute aux lignes
138      height: tasks.length * GANTT_ROW_PX + GANTT_AXIS_PX + (title ? GANTT_BAND_PX : 0) + (hasSections ? GANTT_BAND_PX : 0),
139      data: { values },
140      encoding: {
141        // l'ordre écrit, jalons compris : les deux couches ne le gardent pas seules
142        y: { field: 'task', type: 'nominal', sort: [...new Set(values.map(v => v.task))], axis: { title: null, labelOverlap: false, labelLimit: 240 } },
143        ...(hasSections ? { color: { field: 'section', type: 'nominal', sort: sections.map(s => s || 'tâches'), legend: { title: null } } } : {}),
144      },
145      layer: [
146        {
147          transform: [{ filter: '!datum.isMilestone' }],
148          mark: { type: 'bar', cornerRadius: 3 },
149          encoding: { x, x2: { field: 'end' }, opacity: { condition: { test: 'datum.isDone', value: 0.4 }, value: 1 } },
150        },
151        {
152          transform: [{ filter: 'datum.isMilestone' }],
153          mark: { type: 'point', shape: 'diamond', filled: true, size: 140, opacity: 1 },
154          encoding: { x },
155        },
156      ],
157    },
158  }
159}
160
161/**
162 * `nom : [tags,] [id,] [début,] fin` : la fin est une date, une durée (3d) ou
163 * `until id` ; sans début, la tâche suit la précédente ; un début peut être `after id`.
164 */
165function taskOf(
166  name: string,
167  meta: string,
168  section: string,
169  previous: Task | undefined,
170  byId: ReadonlyMap<string, Task>,
171): { task: Task; id?: string } | { error: string } {
172  const items = meta
173    .split(',')
174    .map(item => item.trim())
175    .filter(item => item !== '')
176  const firstPlain = items.findIndex(item => !TAGS.has(item))
177  const tags = firstPlain === -1 ? items : items.slice(0, firstPlain)
178  const rest = firstPlain === -1 ? [] : items.slice(firstPlain)
179  if (rest.length === 0 || rest.length > 3) return { error: 'il faut une fin ou une durée, et au plus id, début, fin' }
180
181  let id: string | undefined
182  let startText: string | undefined
183  if (rest.length === 3) [id, startText] = rest
184  else if (rest.length === 2) {
185    const head = rest[0]!
186    // une date impossible (2026-02-31) reste un début : son erreur le dira
187    if (head.startsWith('after ') || DATE.test(head)) startText = head
188    else id = head
189  }
190  const start: Found = startText !== undefined ? startOf(startText, byId) : previous ? { at: previous.end } : { error: 'ni date de début ni tâche avant' }
191  if ('error' in start) return start
192  const end = tags.includes('milestone') ? start : endOf(rest.at(-1)!, start.at, byId)
193  if ('error' in end) return end
194  return { task: { name, section, start: start.at, end: end.at, tags }, ...(id ? { id } : {}) }
195}
196
197function startOf(text: string, byId: ReadonlyMap<string, Task>): Found {
198  const after = /^after\s+(.+)$/.exec(text)
199  if (after) {
200    const ends = after[1]!.split(/\s+/).map(id => byId.get(id)?.end)
201    const known = ends.filter((end): end is number => end !== undefined)
202    return known.length === ends.length ? { at: Math.max(...known) } : { error: `tâche inconnue dans "${text}"` }
203  }
204  const at = dateOf(text)
205  return at === null ? { error: `date illisible "${text}" (format YYYY-MM-DD ou YYYY-MM-DD HH:mm)` } : { at }
206}
207
208function endOf(text: string, start: number, byId: ReadonlyMap<string, Task>): Found {
209  const duration = DURATION.exec(text)
210  if (duration) return { at: start + Number(duration[1]) * UNIT_MS[duration[2]!]! }
211  const until = /^until\s+(\S+)$/.exec(text)
212  if (until) {
213    const task = byId.get(until[1]!)
214    return task ? { at: task.start } : { error: `tâche inconnue dans "${text}"` }
215  }
216  const at = dateOf(text)
217  if (at === null) return { error: `fin illisible "${text}" (date YYYY-MM-DD ou durée : 3d, 2w, 4h)` }
218  return at < start ? { error: `la fin "${text}" est avant le début` } : { at }
219}
220
221function dateOf(text: string): number | null {
222  const m = DATE.exec(text)
223  if (!m) return null
224  const day = Number(m[3])
225  const at = Date.UTC(Number(m[1]), Number(m[2]) - 1, day, Number(m[4] ?? 0), Number(m[5] ?? 0), Number(m[6] ?? 0))
226  // 2026-02-31 : Date.UTC déborde sur mars, la date est refusée
227  return new Date(at).getUTCDate() === day ? at : null
228}
229