mintfig 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. mintfig/__init__.py +162 -0
  2. mintfig/_explain/__init__.py +1 -0
  3. mintfig/_explain/change.py +392 -0
  4. mintfig/_explain/compare.py +1308 -0
  5. mintfig/_explain/compare_grouped.py +472 -0
  6. mintfig/_explain/core.py +2005 -0
  7. mintfig/_explain/distribution.py +1268 -0
  8. mintfig/_explain/flow.py +508 -0
  9. mintfig/_explain/layout.py +2012 -0
  10. mintfig/_explain/matrix.py +623 -0
  11. mintfig/_explain/relate.py +1318 -0
  12. mintfig/_explain/timeline.py +595 -0
  13. mintfig/_explain/trend.py +2557 -0
  14. mintfig/_explain/waterfall.py +459 -0
  15. mintfig/_table.py +691 -0
  16. mintfig/_tabular.py +738 -0
  17. mintfig/annotations.py +1165 -0
  18. mintfig/assets/AGENTS_SNIPPET.md +11 -0
  19. mintfig/assets/SKILL.md +143 -0
  20. mintfig/assets/__init__.py +1 -0
  21. mintfig/assets/references/publication.md +79 -0
  22. mintfig/assets/references/scientific_and_recipes.md +213 -0
  23. mintfig/audit.py +179 -0
  24. mintfig/brief.py +518 -0
  25. mintfig/bundle.py +333 -0
  26. mintfig/cli.py +1300 -0
  27. mintfig/edit.py +347 -0
  28. mintfig/epistemic.py +1083 -0
  29. mintfig/explainer.py +194 -0
  30. mintfig/export.py +247 -0
  31. mintfig/inspect_data.py +583 -0
  32. mintfig/interactive.py +1028 -0
  33. mintfig/palettes.py +233 -0
  34. mintfig/plate.py +784 -0
  35. mintfig/preflight.py +2398 -0
  36. mintfig/proof.py +627 -0
  37. mintfig/runner.py +403 -0
  38. mintfig/skill.py +167 -0
  39. mintfig/specs.py +291 -0
  40. mintfig/style.py +151 -0
  41. mintfig/terminal.py +785 -0
  42. mintfig/themes.py +660 -0
  43. mintfig-0.2.0.dist-info/METADATA +239 -0
  44. mintfig-0.2.0.dist-info/RECORD +47 -0
  45. mintfig-0.2.0.dist-info/WHEEL +4 -0
  46. mintfig-0.2.0.dist-info/entry_points.txt +2 -0
  47. mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/cli.py ADDED
@@ -0,0 +1,1300 @@
1
+ """Command-line interface for mintfig runner, preflight, specs, and skills."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .preflight import preflight_pdf
15
+ from .runner import run_script
16
+ from .skill import VALID_TARGETS, get_agents_snippet, get_skill_markdown, install_skill
17
+ from .specs import JOURNALS, JournalSpec, get_spec
18
+
19
+
20
+ def _format_widths(spec: JournalSpec) -> str:
21
+ """Format unique preset column widths cleanly for CLI display."""
22
+ by_width: dict[float, list[str]] = {}
23
+ for name, w in spec.widths_mm.items():
24
+ by_width.setdefault(w, []).append(name)
25
+ parts = [f"{'/'.join(names)}={w:.0f}" for w, names in sorted(by_width.items())]
26
+ return ", ".join(parts) + " mm"
27
+
28
+
29
+ def _verified_label(spec: JournalSpec) -> str:
30
+ """Return the spec's last-verified date, or ``"unverified"`` when unset."""
31
+ return getattr(spec, "last_verified", "") or "unverified"
32
+
33
+
34
+ def _spec_to_dict(spec: JournalSpec) -> dict[str, Any]:
35
+ """Serialize a JournalSpec including v0.2 provenance fields."""
36
+ return {
37
+ "name": spec.name,
38
+ "display_name": spec.display_name,
39
+ "spec_version": getattr(spec, "spec_version", ""),
40
+ "last_verified": getattr(spec, "last_verified", ""),
41
+ "source_url": getattr(spec, "source_url", ""),
42
+ "widths_mm": dict(spec.widths_mm),
43
+ "max_height_mm": spec.max_height_mm,
44
+ "max_page_height_mm": spec.max_page_height_mm,
45
+ "font_family": list(spec.font_family),
46
+ "font_min_pt": spec.font_min_pt,
47
+ "font_max_pt": spec.font_max_pt,
48
+ "body_pt": spec.body_pt,
49
+ "tick_pt": spec.tick_pt,
50
+ "legend_pt": spec.legend_pt,
51
+ "panel_label_pt": spec.panel_label_pt,
52
+ "panel_label_case": spec.panel_label_case,
53
+ "axes_linewidth_pt": spec.axes_linewidth_pt,
54
+ "data_linewidth_pt": spec.data_linewidth_pt,
55
+ "min_linewidth_pt": spec.min_linewidth_pt,
56
+ "dpi_photo": spec.dpi_photo,
57
+ "dpi_combo": spec.dpi_combo,
58
+ "dpi_line": spec.dpi_line,
59
+ "default_palette": spec.default_palette,
60
+ }
61
+
62
+
63
+ def _format_single_spec(spec: JournalSpec) -> str:
64
+ """Format a detailed single-journal specification table."""
65
+ spec_version = getattr(spec, "spec_version", "")
66
+ last_verified = getattr(spec, "last_verified", "")
67
+ verified_str = f"verified {last_verified}" if last_verified else "unverified"
68
+ source_url = getattr(spec, "source_url", "")
69
+ lines = [
70
+ f"{spec.display_name} ({spec.name})",
71
+ "─" * 64,
72
+ f" Spec version : {spec_version} ({verified_str})",
73
+ f" Source URL : {source_url}",
74
+ f" Column widths : {_format_widths(spec)}",
75
+ f" Max height : {spec.max_height_mm:.0f} mm (page max {spec.max_page_height_mm:.0f} mm)",
76
+ f" Font family : {', '.join(spec.font_family)}",
77
+ f" Font size bounds : {spec.font_min_pt:.1f}–{spec.font_max_pt:.1f} pt",
78
+ f" Body / Tick / Leg : {spec.body_pt:.1f} / {spec.tick_pt:.1f} / {spec.legend_pt:.1f} pt",
79
+ f" Panel labels : {spec.panel_label_pt:.1f} pt {spec.panel_label_weight} ({spec.panel_label_case})",
80
+ f" Line widths : axes {spec.axes_linewidth_pt:.2f} pt, data {spec.data_linewidth_pt:.2f} pt, min {spec.min_linewidth_pt:.2f} pt",
81
+ f" DPI (photo/combo) : {spec.dpi_photo} / {spec.dpi_combo} / {spec.dpi_line} (line)",
82
+ f" Default palette : {spec.default_palette}",
83
+ ]
84
+ return "\n".join(lines)
85
+
86
+
87
+ def _format_all_specs() -> str:
88
+ """Format a compact overview table of all supported journal specs."""
89
+ headers = ("Journal", "Widths (mm)", "Max H", "Font (pt)", "Panel", "Version", "Verified")
90
+ rows: list[tuple[str, str, str, str, str, str, str]] = []
91
+ for key, spec in JOURNALS.items():
92
+ unique_w = "/".join(f"{w:.0f}" for w in sorted(set(spec.widths_mm.values())))
93
+ max_h = f"{spec.max_height_mm:.0f} ({spec.max_page_height_mm:.0f})"
94
+ font_rng = f"{spec.font_min_pt:.0f}–{spec.font_max_pt:.0f}"
95
+ panel = f"{spec.panel_label_pt:.1f}pt {spec.panel_label_case}"
96
+ version = getattr(spec, "spec_version", "")
97
+ verified = _verified_label(spec)
98
+ rows.append(
99
+ (f"{key} ({spec.display_name})", unique_w, max_h, font_rng, panel, version, verified)
100
+ )
101
+
102
+ widths = [max(len(headers[i]), *(len(row[i]) for row in rows)) for i in range(len(headers))]
103
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
104
+ sep = "─" * (sum(widths) + 2 * (len(widths) - 1))
105
+
106
+ lines = [fmt.format(*headers), sep]
107
+ for row in rows:
108
+ lines.append(fmt.format(*row))
109
+ lines.append("")
110
+ for key, spec in JOURNALS.items():
111
+ source_url = getattr(spec, "source_url", "")
112
+ if source_url:
113
+ lines.append(f" {key}: {source_url}")
114
+ return "\n".join(lines)
115
+
116
+
117
+ def _parse_width_arg(raw: str | None) -> str | float | None:
118
+ """Convert numeric CLI --width values to float while preserving preset names."""
119
+ if raw is None:
120
+ return None
121
+ try:
122
+ return float(raw)
123
+ except ValueError:
124
+ return raw
125
+
126
+
127
+ def _parse_targets_arg(raw_targets: Sequence[str] | None) -> list[str]:
128
+ """Parse comma-separated or repeated --target values."""
129
+ if not raw_targets:
130
+ return ["claude", "antigravity", "agents-md"]
131
+ parsed: list[str] = []
132
+ for item in raw_targets:
133
+ for part in item.split(","):
134
+ cleaned = part.strip()
135
+ if cleaned:
136
+ parsed.append(cleaned)
137
+ return parsed or ["claude", "antigravity", "agents-md"]
138
+
139
+
140
+ def _parse_list_arg(raw_values: Sequence[str] | None) -> list[str] | None:
141
+ """Parse comma-separated or repeated CLI string list flags."""
142
+ if not raw_values:
143
+ return None
144
+ out: list[str] = []
145
+ for item in raw_values:
146
+ for part in item.split(","):
147
+ cleaned = part.strip()
148
+ if cleaned:
149
+ out.append(cleaned)
150
+ return out or None
151
+
152
+
153
+ def _parse_reference_arg(raw: str | None) -> float | tuple[float, str] | None:
154
+ """Parse ``--reference 100`` or ``--reference 100:SLA budget``."""
155
+ if raw is None:
156
+ return None
157
+ if ":" in raw:
158
+ val_s, label_s = raw.split(":", 1)
159
+ return (float(val_s.strip()), label_s.strip())
160
+ return float(raw.strip())
161
+
162
+
163
+ def _parse_waterfall_start(raw: str | None) -> float | tuple[str, float] | None:
164
+ """Parse ``--waterfall-start 69.0`` or ``--waterfall-start Base:69.0``."""
165
+ if raw is None:
166
+ return None
167
+ if ":" in raw:
168
+ label_s, val_s = raw.split(":", 1)
169
+ return (label_s.strip() or "Start", float(val_s.strip()))
170
+ return float(raw.strip())
171
+
172
+
173
+ def _parse_sort_arg(raw: str | None) -> bool | str | None:
174
+ if raw is None:
175
+ return None
176
+ low = raw.strip().lower()
177
+ if low in {"true", "1", "yes"}:
178
+ return True
179
+ if low in {"false", "0", "no"}:
180
+ return False
181
+ return raw.strip()
182
+
183
+
184
+ def _format_inspect_text(info: dict[str, Any]) -> str:
185
+ """Format an ``inspect_data`` dict into concise plain text for terminals."""
186
+ src = info.get("source") or "<in-memory>"
187
+ lines = [f"{src} — {info['rows']} rows × {len(info['columns'])} columns"]
188
+ lines.append("─" * 64)
189
+ for prof in info.get("column_profiles", []):
190
+ ctype = prof["type"]
191
+ if ctype == "numeric":
192
+ extra = f"min={prof['min']}, median={prof['median']}, max={prof['max']}"
193
+ if prof.get("spans_decades"):
194
+ extra += " (spans decades -> log)"
195
+ elif ctype == "date":
196
+ extra = f"{prof['min']} .. {prof['max']} ({prof['unique']} unique)"
197
+ else:
198
+ samples = ", ".join(prof.get("samples", [])[:4])
199
+ extra = f"{prof['unique']} unique [{samples}]"
200
+ miss = f", {prof['missing']} missing" if prof.get("missing") else ""
201
+ lines.append(f" {prof['name']:<18} {ctype:<12} {extra}{miss}")
202
+ recs = info.get("recommendations", [])
203
+ if recs:
204
+ lines.append("\nRecommended mintfig forms:")
205
+ for idx, rec in enumerate(recs, 1):
206
+ lines.append(f" {idx}. {rec['kind']}: {rec['reason']}")
207
+ lines.append(f" Python: {rec['python']}")
208
+ if rec.get("cli"):
209
+ lines.append(f" CLI: {rec['cli']}")
210
+ return "\n".join(lines)
211
+
212
+
213
+ def _build_parser() -> argparse.ArgumentParser:
214
+ parser = argparse.ArgumentParser(
215
+ prog="mintfig",
216
+ description="Publication-ready scientific figure runner, preflight linter, and skill CLI.",
217
+ )
218
+ subparsers = parser.add_subparsers(dest="command", required=True)
219
+
220
+ # `mintfig run <script.py> [--journal nature] [--width ...] [--bundle out/] [--no-proof] [--json] [--strict]`
221
+ run_parser = subparsers.add_parser(
222
+ "run",
223
+ help="Execute a plotting script, run preflight compliance checks, and optionally export a bundle.",
224
+ )
225
+ run_parser.add_argument(
226
+ "script_path",
227
+ type=Path,
228
+ help="Path to the Python plotting script exposing build(), plate, or fig.",
229
+ )
230
+ run_parser.add_argument(
231
+ "--journal",
232
+ "-j",
233
+ default="nature",
234
+ help="Target journal preset name (default: nature).",
235
+ )
236
+ run_parser.add_argument(
237
+ "--width",
238
+ "-w",
239
+ default=None,
240
+ help="Optional column preset (single/double/full) or mm width forwarded to build(width=...).",
241
+ )
242
+ run_parser.add_argument(
243
+ "--bundle",
244
+ "-b",
245
+ type=Path,
246
+ default=None,
247
+ help="Output directory for the submission bundle (PDF, SVG, PNG, proof, TeX, report.json).",
248
+ )
249
+ run_parser.add_argument(
250
+ "--no-proof",
251
+ action="store_true",
252
+ help="Skip proof.png generation when exporting a bundle.",
253
+ )
254
+ run_parser.add_argument(
255
+ "--json",
256
+ action="store_true",
257
+ dest="as_json",
258
+ help="Output the structured v0.2 JSON report.",
259
+ )
260
+ run_parser.add_argument(
261
+ "--strict",
262
+ action="store_true",
263
+ help="Treat warnings as failures (exit code 1 on any warning or error).",
264
+ )
265
+
266
+ # `mintfig check <pdf_path> --journal nature [--json] [--strict]`
267
+ check_parser = subparsers.add_parser(
268
+ "check",
269
+ help="Run automated journal preflight checks on an exported PDF figure.",
270
+ )
271
+ check_parser.add_argument(
272
+ "pdf_path",
273
+ type=Path,
274
+ help="Path to the PDF figure to verify.",
275
+ )
276
+ check_parser.add_argument(
277
+ "--journal",
278
+ "-j",
279
+ default="nature",
280
+ help="Target journal preset name (default: nature).",
281
+ )
282
+ check_parser.add_argument(
283
+ "--json",
284
+ action="store_true",
285
+ dest="as_json",
286
+ help="Output the preflight report as formatted JSON.",
287
+ )
288
+ check_parser.add_argument(
289
+ "--strict",
290
+ action="store_true",
291
+ help="Treat warnings as failures (exit code 1 on any warning or failure).",
292
+ )
293
+
294
+ # `mintfig specs [--journal nature] [--json]`
295
+ specs_parser = subparsers.add_parser(
296
+ "specs",
297
+ help="Display official journal physical dimension and typography specifications.",
298
+ )
299
+ specs_parser.add_argument(
300
+ "--journal",
301
+ "-j",
302
+ default=None,
303
+ help="Show detailed specification for a specific journal preset.",
304
+ )
305
+ specs_parser.add_argument(
306
+ "--json",
307
+ action="store_true",
308
+ dest="as_json",
309
+ help="Output journal specification(s) as formatted JSON.",
310
+ )
311
+
312
+ # `mintfig explain <spec.json | -> --out fig.png [--write-spec]` / `mintfig explain --example`
313
+ explain_parser = subparsers.add_parser(
314
+ "explain",
315
+ help="Render a message-first chat figure from a JSON spec (takeaway + panels).",
316
+ )
317
+ explain_parser.add_argument(
318
+ "spec_path",
319
+ nargs="?",
320
+ default=None,
321
+ help="Path to the JSON spec, a PNG saved by mintfig (it carries its spec), or '-' "
322
+ "to read JSON from stdin.",
323
+ )
324
+ explain_parser.add_argument(
325
+ "--out",
326
+ type=Path,
327
+ default=None,
328
+ help="Output image path (.png, .svg, .pdf, or .html). Required unless --example.",
329
+ )
330
+ explain_parser.add_argument(
331
+ "--style",
332
+ default=None,
333
+ help="Visual style override: mintfig (default), bold, editorial, paper, dark, mono, or sketch.",
334
+ )
335
+ explain_parser.add_argument(
336
+ "--palette",
337
+ default=None,
338
+ help="Color palette override: default, okabe_ito, tol, earth, ocean, or berry.",
339
+ )
340
+ explain_parser.add_argument(
341
+ "--accent",
342
+ default=None,
343
+ help="Custom primary highlight accent color override (e.g. '#D97757').",
344
+ )
345
+ explain_parser.add_argument(
346
+ "--lenient",
347
+ "--no-strict",
348
+ action="store_true",
349
+ dest="lenient",
350
+ help="Non-strict mode: auto-adjust soft limits instead of rejecting, and ship if no visual defects remain.",
351
+ )
352
+ explain_parser.add_argument(
353
+ "--write-spec",
354
+ action="store_true",
355
+ help="Also write <out>.json, the normalised spec that reproduces the figure.",
356
+ )
357
+ explain_parser.add_argument(
358
+ "--show-spec",
359
+ action="store_true",
360
+ help="Print the spec embedded in a mintfig PNG (or the JSON spec) and exit.",
361
+ )
362
+ explain_parser.add_argument(
363
+ "--example",
364
+ action="store_true",
365
+ help="Print an example spec to stdout and exit.",
366
+ )
367
+
368
+ # `mintfig show <path_or_spec> [--mode auto|kitty|iterm2|unicode|ascii] [--width 78] [--no-color]`
369
+ show_parser = subparsers.add_parser(
370
+ "show",
371
+ help="Display a mintfig spec or PNG in the terminal (Kitty/iTerm2 graphics or Unicode/ASCII).",
372
+ )
373
+ show_parser.add_argument(
374
+ "path_or_spec",
375
+ help="Path to a JSON spec, a PNG file, or '-' to read a JSON spec from stdin.",
376
+ )
377
+ show_parser.add_argument(
378
+ "--mode",
379
+ choices=("auto", "kitty", "iterm2", "unicode", "ascii"),
380
+ default="auto",
381
+ help="Rendering mode (default: auto).",
382
+ )
383
+ show_parser.add_argument(
384
+ "--width",
385
+ type=int,
386
+ default=78,
387
+ help="Target text width in columns for unicode/ascii modes (default: 78).",
388
+ )
389
+ show_parser.add_argument(
390
+ "--no-color",
391
+ action="store_true",
392
+ help="Disable ANSI color sequences in unicode/ascii output.",
393
+ )
394
+
395
+ # `mintfig inspect <data.csv|tsv|json|jsonl> [--json]`
396
+ inspect_parser = subparsers.add_parser(
397
+ "inspect",
398
+ help="Profile a CSV/TSV/JSON/JSONL file without pandas and recommend mintfig forms.",
399
+ )
400
+ inspect_parser.add_argument(
401
+ "data_path",
402
+ type=Path,
403
+ help="Path to a .csv, .tsv, .json, or .jsonl data file.",
404
+ )
405
+ inspect_parser.add_argument(
406
+ "--json",
407
+ action="store_true",
408
+ dest="as_json",
409
+ help="Output column profiles and recommendations as formatted JSON.",
410
+ )
411
+
412
+ # `mintfig plot <data.csv|tsv|json|jsonl> --kind <form> --takeaway "..." --out fig.png`
413
+ plot_parser = subparsers.add_parser(
414
+ "plot",
415
+ help="Render a message-first figure directly from a CSV/TSV/JSON/JSONL file without writing Python.",
416
+ )
417
+ plot_parser.add_argument("data_path", type=Path, help="Input .csv, .tsv, .json, or .jsonl file.")
418
+ plot_parser.add_argument(
419
+ "--kind",
420
+ "-k",
421
+ required=True,
422
+ choices=(
423
+ "auto",
424
+ "compare",
425
+ "trend",
426
+ "change",
427
+ "distribution",
428
+ "histogram",
429
+ "relate",
430
+ "share",
431
+ "matrix",
432
+ "table",
433
+ "waterfall",
434
+ "timeline",
435
+ "flow",
436
+ ),
437
+ help="Chart form to render (use 'auto' to pick the top recommended form).",
438
+ )
439
+ plot_parser.add_argument("--takeaway", "-t", required=True, help="One-sentence takeaway title.")
440
+ plot_parser.add_argument("--out", "-o", type=Path, default=None, help="Output path (.png, .svg, .pdf, or .html).")
441
+ plot_parser.add_argument("--show", action="store_true", help="Display the figure in the terminal.")
442
+ plot_parser.add_argument(
443
+ "--show-mode",
444
+ choices=("auto", "kitty", "iterm2", "unicode", "ascii"),
445
+ default="auto",
446
+ help="Terminal rendering mode when --show is set (default: auto).",
447
+ )
448
+ plot_parser.add_argument("--show-width", type=int, default=78, help="Terminal text width when --show is set.")
449
+ plot_parser.add_argument("--subtitle", default=None, help="Figure subtitle.")
450
+ plot_parser.add_argument("--source", default=None, help="Data source line.")
451
+ plot_parser.add_argument("--note", default=None, help="Figure footer note.")
452
+ plot_parser.add_argument("--style", default="mintfig", help="Visual theme name.")
453
+ plot_parser.add_argument("--palette", default=None, help="Color palette name.")
454
+ plot_parser.add_argument("--accent", default=None, help="Custom accent hex color.")
455
+ plot_parser.add_argument("--width", default="chat", help="Target width preset ('narrow', 'chat', 'slide') or mm.")
456
+ plot_parser.add_argument("--title", default=None, help="Panel headline.")
457
+ plot_parser.add_argument("--label", default=None, help="Measured quantity label.")
458
+ plot_parser.add_argument("--unit", default=None, help="Short unit symbol (e.g. ms, %).")
459
+ plot_parser.add_argument("--x-label", default=None, help="X-axis label.")
460
+ plot_parser.add_argument("--y-label", default=None, help="Y-axis label (relate).")
461
+ plot_parser.add_argument("--name", default=None, help="Item/stage name column.")
462
+ plot_parser.add_argument("--value", default=None, help="Value/delta column.")
463
+ plot_parser.add_argument("--group", default=None, help="Group/lane column.")
464
+ plot_parser.add_argument("--x", default=None, help="X column (trend/relate).")
465
+ plot_parser.add_argument("--y", default=None, help="Y column (trend/relate).")
466
+ plot_parser.add_argument("--series", default=None, help="Series column (trend).")
467
+ plot_parser.add_argument("--before", default=None, help="Before column (change).")
468
+ plot_parser.add_argument("--after", default=None, help="After column (change).")
469
+ plot_parser.add_argument("--rows", default=None, help="Row category column (matrix).")
470
+ plot_parser.add_argument("--cols", default=None, help="Column category column (matrix).")
471
+ plot_parser.add_argument("--start", default=None, help="Start column (timeline).")
472
+ plot_parser.add_argument("--end", default=None, help="End column (timeline).")
473
+ plot_parser.add_argument("--names", default=None, help="Point name column (relate).")
474
+ plot_parser.add_argument("--groups", default=None, help="Point group column (relate).")
475
+ plot_parser.add_argument("--highlight", action="append", default=None, help="Highlight name(s), comma-separated or repeated.")
476
+ plot_parser.add_argument("--baseline", default=None, help="Baseline/control item name.")
477
+ plot_parser.add_argument("--reference", default=None, help="Reference value or value:label.")
478
+ plot_parser.add_argument("--sort", default=None, help="Sort order (true/false/asc/desc/column).")
479
+ plot_parser.add_argument("--fmt", default=None, help="Value format spec.")
480
+ plot_parser.add_argument("--log", action="store_true", help="Use log scale on y/value axis.")
481
+ plot_parser.add_argument("--log-x", action="store_true", help="Use log scale on x axis.")
482
+ plot_parser.add_argument("--no-zero", action="store_true", help="Do not force zero baseline (compare dots).")
483
+ plot_parser.add_argument("--show-delta", action="store_true", help="Show inline baseline delta (compare).")
484
+ plot_parser.add_argument("--mode", default=None, help="Distribution mode ('dots' or 'quantile').")
485
+ plot_parser.add_argument("--bins", default=None, help="Histogram bins ('auto' or integer).")
486
+ plot_parser.add_argument("--frontier", action="store_true", help="Draw Pareto frontier (relate).")
487
+ plot_parser.add_argument("--label-all", action="store_true", help="Label all points (relate).")
488
+ plot_parser.add_argument("--connect-groups", action="store_true", help="Connect group trajectories (relate).")
489
+ plot_parser.add_argument("--fit", action="store_true", help="Draw linear fit (relate).")
490
+ plot_parser.add_argument("--bold-best", action="store_true", help="Bold numeric column winners (table).")
491
+ plot_parser.add_argument("--waterfall-start", default=None, help="Waterfall start value or label:value.")
492
+ plot_parser.add_argument("--total-label", default="Total", help="Waterfall total bar label.")
493
+ plot_parser.add_argument("--no-total", action="store_true", help="Omit waterfall final total bar.")
494
+ plot_parser.add_argument("--reason", default=None, help="Drop reason column (flow).")
495
+ plot_parser.add_argument("--triangle", choices=("lower", "upper"), default=None, help="Triangle mask (matrix).")
496
+ plot_parser.add_argument("--mask-diagonal", action="store_true", help="Mask self-diagonal (matrix).")
497
+ plot_parser.add_argument("--lenient", "--no-strict", action="store_true", dest="lenient", help="Auto-adjust soft limits.")
498
+ plot_parser.add_argument("--write-spec", action="store_true", help="Also write <out>.json spec.")
499
+
500
+ # `mintfig brief <fig1.png|spec1.json> [<fig2.png> ...] --title "..." --out report.html|report.md`
501
+ brief_parser = subparsers.add_parser(
502
+ "brief",
503
+ help="Compose 1–12 saved mintfig PNGs or JSON specs into a single HTML or Markdown briefing.",
504
+ )
505
+ brief_parser.add_argument(
506
+ "figures",
507
+ nargs="+",
508
+ type=Path,
509
+ help="One or more mintfig PNG files (embedded spec) or JSON spec files.",
510
+ )
511
+ brief_parser.add_argument("--title", "-t", required=True, help="Briefing title.")
512
+ brief_parser.add_argument("--out", "-o", type=Path, required=True, help="Output .html or .md path.")
513
+ brief_parser.add_argument("--subtitle", default=None, help="Briefing subtitle.")
514
+ brief_parser.add_argument(
515
+ "--summary",
516
+ action="append",
517
+ default=None,
518
+ help="Key finding bullet (repeatable).",
519
+ )
520
+ brief_parser.add_argument("--source", default=None, help="Briefing footer source.")
521
+ brief_parser.add_argument("--style", default=None, help="Optional theme override for HTML styling.")
522
+
523
+ # `mintfig edit <fig.png|spec.json> [flags] --out out.png`
524
+ edit_parser = subparsers.add_parser(
525
+ "edit",
526
+ help="Surgically edit an existing mintfig PNG or JSON spec without rewriting a script.",
527
+ )
528
+ edit_parser.add_argument("figure_path", type=Path, help="Path to a mintfig PNG (embedded spec) or JSON spec.")
529
+ edit_parser.add_argument("--out", "-o", type=Path, default=None, help="Output path (.png, .svg, .pdf, or .html).")
530
+ edit_parser.add_argument("--show", action="store_true", help="Display the edited figure in the terminal.")
531
+ edit_parser.add_argument(
532
+ "--show-mode",
533
+ choices=("auto", "kitty", "iterm2", "unicode", "ascii"),
534
+ default="auto",
535
+ help="Terminal rendering mode when --show is set (default: auto).",
536
+ )
537
+ edit_parser.add_argument("--show-width", type=int, default=78, help="Terminal text width when --show is set.")
538
+ edit_parser.add_argument("--takeaway", "-t", default=None, help="New takeaway title.")
539
+ edit_parser.add_argument("--subtitle", default=None, help="New subtitle (pass '' to clear).")
540
+ edit_parser.add_argument("--source", default=None, help="New source line (pass '' to clear).")
541
+ edit_parser.add_argument("--note", default=None, help="New note (pass '' to clear).")
542
+ edit_parser.add_argument("--style", default=None, help="New theme name.")
543
+ edit_parser.add_argument("--palette", default=None, help="New palette name.")
544
+ edit_parser.add_argument("--accent", default=None, help="New accent hex color (pass '' to clear).")
545
+ edit_parser.add_argument("--width", default=None, help="New target width ('narrow', 'chat', 'slide', or mm).")
546
+ edit_parser.add_argument("--panel", default="a", help="Panel key ('a', 'b', ...) to edit (default: a).")
547
+ edit_parser.add_argument("--title", default=None, help="New panel headline.")
548
+ edit_parser.add_argument("--label", default=None, help="New panel label.")
549
+ edit_parser.add_argument("--unit", default=None, help="New panel unit.")
550
+ edit_parser.add_argument("--highlight", action="append", default=None, help="New highlight name(s), comma-separated or repeated.")
551
+ edit_parser.add_argument("--baseline", default=None, help="New baseline item (pass '' to clear).")
552
+ edit_parser.add_argument("--sort", default=None, help="New sort order.")
553
+ edit_parser.add_argument("--reference", default=None, help="New reference value or value:label.")
554
+ edit_parser.add_argument("--show-delta", action="store_true", default=None, help="Enable inline baseline delta.")
555
+ edit_parser.add_argument("--drop", action="append", default=None, help="Item/series name(s) to remove from --panel.")
556
+ edit_parser.add_argument("--keep", action="append", default=None, help="Keep only these item/series name(s) in --panel.")
557
+ edit_parser.add_argument("--drop-panel", default=None, help="Drop an entire panel by key (e.g. 'b').")
558
+ edit_parser.add_argument("--lenient", "--no-strict", action="store_true", dest="lenient", help="Auto-adjust soft limits.")
559
+ edit_parser.add_argument("--write-spec", action="store_true", help="Also write <out>.json spec.")
560
+
561
+ # `mintfig skill [--install] [--target ...] [--root .] [--print] [--snippet]`
562
+ skill_parser = subparsers.add_parser(
563
+ "skill",
564
+ help="Print or install mintfig agent skill instructions (Claude, Antigravity, Cursor, Codex, AGENTS.md).",
565
+ )
566
+ skill_parser.add_argument(
567
+ "--install",
568
+ action="store_true",
569
+ help="Install skill and/or instruction files into --root.",
570
+ )
571
+ skill_parser.add_argument(
572
+ "--target",
573
+ action="append",
574
+ default=None,
575
+ help=(
576
+ "Comma-separated install target(s): "
577
+ f"{','.join(VALID_TARGETS)} (default: claude,antigravity,agents-md)."
578
+ ),
579
+ )
580
+ skill_parser.add_argument(
581
+ "--root",
582
+ type=Path,
583
+ default=Path("."),
584
+ help="Project root directory for --install (default: current directory).",
585
+ )
586
+ skill_parser.add_argument(
587
+ "--print",
588
+ action="store_true",
589
+ dest="print_skill",
590
+ help="Print the bundled SKILL.md to stdout without modifying disk.",
591
+ )
592
+ skill_parser.add_argument(
593
+ "--snippet",
594
+ action="store_true",
595
+ help="Print the marker-wrapped AGENTS.md / CLAUDE.md snippet without modifying disk.",
596
+ )
597
+
598
+ return parser
599
+
600
+
601
+ def _run_explain(args: argparse.Namespace) -> int:
602
+ """Render a JSON explain spec; always prints one JSON object for the calling agent.
603
+
604
+ Exit codes: 0 rendered with no errors, 1 rendered but an issue has
605
+ severity "error", 2 the spec was rejected (nothing rendered).
606
+ """
607
+ from .explainer import EXAMPLE_SPEC, ExplainError, explain_from_spec, read_png_text
608
+
609
+ if args.example:
610
+ print(json.dumps(EXAMPLE_SPEC, indent=2, ensure_ascii=False))
611
+ return 0
612
+
613
+ def _reject(message: str, fix_hint: str, rule: str = "explain_spec") -> int:
614
+ payload = {
615
+ "schema_version": "0.2",
616
+ "ok": False,
617
+ "rendered": False,
618
+ "stage": "spec",
619
+ "rule": rule,
620
+ "error": message,
621
+ "fix_hint": fix_hint,
622
+ }
623
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
624
+ return 2
625
+
626
+ if args.spec_path is None or (args.out is None and not args.show_spec):
627
+ return _reject(
628
+ "mintfig explain needs a spec and --out.",
629
+ "Run `mintfig explain spec.json --out fig.png` (or `-` to read stdin, or a PNG saved "
630
+ "by mintfig); `mintfig explain --example` prints a spec to start from.",
631
+ )
632
+ try:
633
+ if args.spec_path != "-" and Path(args.spec_path).read_bytes()[:8] == b"\x89PNG\r\n\x1a\n":
634
+ embedded = read_png_text(args.spec_path)
635
+ if "mintfig:spec" not in embedded:
636
+ return _reject(
637
+ f"{args.spec_path} carries no mintfig spec.",
638
+ "Only PNGs written by mintfig (Explanation.save, embed on by default) carry "
639
+ "their spec; pass the .json spec instead.",
640
+ )
641
+ raw = embedded["mintfig:spec"]
642
+ else:
643
+ raw = (
644
+ sys.stdin.read() if args.spec_path == "-" else Path(args.spec_path).read_text("utf-8")
645
+ )
646
+ spec = json.loads(raw)
647
+ except OSError as exc:
648
+ return _reject(f"Cannot read the spec: {exc}", "Check the path, or pipe the JSON to `-`.")
649
+ except UnicodeDecodeError as exc:
650
+ return _reject(
651
+ f"The spec is not text: {exc}", "Pass a JSON spec or a PNG saved by mintfig."
652
+ )
653
+ except json.JSONDecodeError as exc:
654
+ return _reject(f"The spec is not valid JSON: {exc}", "Fix the JSON syntax and re-run.")
655
+ if args.show_spec:
656
+ print(json.dumps(spec, indent=2, ensure_ascii=False))
657
+ return 0
658
+ if not isinstance(spec, dict):
659
+ return _reject(
660
+ "The spec must be a JSON object.",
661
+ 'Use {"takeaway": "...", "panels": [...]}; see `mintfig explain --example`.',
662
+ )
663
+ if args.style is not None:
664
+ spec = {**spec, "style": args.style}
665
+ if args.palette is not None:
666
+ spec = {**spec, "palette": args.palette}
667
+ if getattr(args, "accent", None) is not None:
668
+ spec = {**spec, "accent": args.accent}
669
+ try:
670
+ explanation = explain_from_spec(spec, strict=not args.lenient)
671
+ except ExplainError as exc:
672
+ return _reject(exc.message, exc.fix_hint, exc.rule)
673
+ except (KeyError, TypeError, ValueError) as exc:
674
+ return _reject(str(exc), "See `mintfig explain --example` for the expected shape.")
675
+ if args.out.suffix.lower() in {".html", ".htm"}:
676
+ from .interactive import render_html
677
+
678
+ out_path = Path(args.out)
679
+ out_path.parent.mkdir(parents=True, exist_ok=True)
680
+ out_path.write_text(render_html(explanation, interactive=True), encoding="utf-8")
681
+ explanation.saved_path = out_path.resolve()
682
+ explanation.saved_px = None
683
+ if args.write_spec:
684
+ out_path.with_suffix(".json").write_text(
685
+ json.dumps(explanation.to_spec(), indent=2, ensure_ascii=False) + "\n",
686
+ encoding="utf-8",
687
+ )
688
+ summary = explanation.summary()
689
+ else:
690
+ summary = explanation.save(args.out, write_spec=args.write_spec)
691
+ print(summary)
692
+ return 0 if summary["ok"] else 1
693
+
694
+
695
+ def _run_show(args: argparse.Namespace) -> int:
696
+ """Render a mintfig spec or PNG to the terminal."""
697
+ from .explainer import ExplainError
698
+ from .terminal import show_in_terminal
699
+
700
+ try:
701
+ target: Any
702
+ if args.path_or_spec == "-":
703
+ raw = sys.stdin.read()
704
+ target = json.loads(raw)
705
+ if not isinstance(target, dict):
706
+ raise ValueError("JSON spec from stdin must be a JSON object.")
707
+ else:
708
+ target = Path(args.path_or_spec)
709
+ rendered = show_in_terminal(
710
+ target,
711
+ mode=args.mode,
712
+ width=args.width,
713
+ color=not args.no_color,
714
+ )
715
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError, ExplainError, ValueError, TypeError) as exc:
716
+ print(f"Error: {exc}", file=sys.stderr)
717
+ return 1
718
+ print(rendered)
719
+ return 0
720
+
721
+
722
+ def _emit_explanation(
723
+ explanation: Any,
724
+ *,
725
+ out: Path | None,
726
+ write_spec: bool,
727
+ show: bool,
728
+ show_mode: str,
729
+ show_width: int,
730
+ ) -> int:
731
+ """Save ``explanation`` to ``out`` (PNG/SVG/PDF/HTML) and/or render to terminal."""
732
+ if out is not None:
733
+ if out.suffix.lower() in {".html", ".htm"}:
734
+ from .interactive import render_html
735
+
736
+ out.parent.mkdir(parents=True, exist_ok=True)
737
+ out.write_text(render_html(explanation, interactive=True), encoding="utf-8")
738
+ explanation.saved_path = out.resolve()
739
+ explanation.saved_px = None
740
+ if write_spec:
741
+ out.with_suffix(".json").write_text(
742
+ json.dumps(explanation.to_spec(), indent=2, ensure_ascii=False) + "\n",
743
+ encoding="utf-8",
744
+ )
745
+ summary = explanation.summary()
746
+ else:
747
+ summary = explanation.save(out, write_spec=write_spec)
748
+ else:
749
+ summary = explanation.summary()
750
+
751
+ if show:
752
+ from .terminal import show_in_terminal
753
+
754
+ print(show_in_terminal(explanation, mode=show_mode, width=show_width))
755
+ else:
756
+ print(summary)
757
+ return 0 if summary["ok"] else 1
758
+
759
+
760
+ def _run_inspect(args: argparse.Namespace) -> int:
761
+ """Inspect a CSV/TSV/JSON/JSONL file and recommend mintfig forms."""
762
+ from .explainer import ExplainError
763
+ from .inspect_data import inspect_data
764
+
765
+ try:
766
+ info = inspect_data(args.data_path)
767
+ except (ExplainError, OSError, ValueError) as exc:
768
+ if args.as_json:
769
+ payload = {
770
+ "ok": False,
771
+ "error": exc.message if isinstance(exc, ExplainError) else str(exc),
772
+ "fix_hint": exc.fix_hint if isinstance(exc, ExplainError) else "Check the file path and format.",
773
+ }
774
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
775
+ else:
776
+ print(f"Error: {exc}", file=sys.stderr)
777
+ return 2
778
+ if args.as_json:
779
+ print(json.dumps(info, indent=2, ensure_ascii=False))
780
+ else:
781
+ print(_format_inspect_text(info))
782
+ return 0
783
+
784
+
785
+ def _run_plot(args: argparse.Namespace) -> int:
786
+ """Build and render a figure directly from a CSV/TSV/JSON/JSONL file."""
787
+ from . import explainer as fm_exp
788
+ from .explainer import ExplainError
789
+ from .inspect_data import load_table_file
790
+
791
+ def _reject(message: str, fix_hint: str, rule: str = "plot_cli") -> int:
792
+ payload = {
793
+ "schema_version": "0.2",
794
+ "ok": False,
795
+ "rendered": False,
796
+ "stage": "spec",
797
+ "rule": rule,
798
+ "error": message,
799
+ "fix_hint": fix_hint,
800
+ }
801
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
802
+ return 2
803
+
804
+ if args.out is None and not args.show:
805
+ return _reject(
806
+ "mintfig plot needs --out <path> or --show.",
807
+ "Pass --out fig.png (or fig.html) to write a file, or --show for terminal display.",
808
+ )
809
+
810
+ try:
811
+ rows = load_table_file(args.data_path)
812
+ hl = _parse_list_arg(args.highlight)
813
+ ref = _parse_reference_arg(args.reference)
814
+ sort_v = _parse_sort_arg(args.sort)
815
+ common: dict[str, Any] = {}
816
+ if args.title is not None:
817
+ common["title"] = args.title
818
+ if args.label is not None:
819
+ common["label"] = args.label
820
+ if args.unit is not None:
821
+ common["unit"] = args.unit
822
+ if hl is not None:
823
+ common["highlight"] = hl if len(hl) > 1 else hl[0]
824
+ if args.fmt is not None:
825
+ common["fmt"] = args.fmt
826
+
827
+ kind = args.kind
828
+ with fm_exp.lenient() if args.lenient else _null_ctx():
829
+ if kind == "auto":
830
+ from .inspect_data import auto_panel
831
+
832
+ panel = auto_panel(
833
+ rows,
834
+ title=args.title,
835
+ label=args.label,
836
+ unit=args.unit,
837
+ highlight=common.get("highlight"),
838
+ baseline=args.baseline,
839
+ )
840
+ elif kind == "compare":
841
+ kw = {**common}
842
+ if args.name:
843
+ kw["name"] = args.name
844
+ if args.group:
845
+ kw["group"] = args.group
846
+ if args.value:
847
+ kw["value"] = args.value
848
+ if args.baseline:
849
+ kw["baseline"] = args.baseline
850
+ if ref is not None:
851
+ kw["reference"] = ref
852
+ if sort_v is not None:
853
+ kw["sort"] = sort_v
854
+ if args.log:
855
+ kw["log"] = True
856
+ if args.no_zero:
857
+ kw["zero"] = False
858
+ if args.show_delta:
859
+ kw["show_delta"] = True
860
+ panel = fm_exp.compare(rows, **kw)
861
+ elif kind == "share":
862
+ kw = {**common}
863
+ if args.name:
864
+ kw["name"] = args.name
865
+ if args.value:
866
+ kw["value"] = args.value
867
+ panel = fm_exp.share(rows, **kw)
868
+ elif kind == "change":
869
+ if not (args.before and args.after):
870
+ raise ExplainError(
871
+ "mintfig plot --kind change requires --before and --after column names.",
872
+ fix_hint="Pass --before col1 --after col2 --name item_col.",
873
+ )
874
+ kw = {**common, "data": rows}
875
+ if args.name:
876
+ kw["name"] = args.name
877
+ panel = fm_exp.change(args.before, args.after, **kw)
878
+ elif kind == "trend":
879
+ if not args.x:
880
+ raise ExplainError(
881
+ "mintfig plot --kind trend requires --x column name.",
882
+ fix_hint="Pass --x step_col --y val_col (and optional --series group_col).",
883
+ )
884
+ kw = {**common, "data": rows}
885
+ if args.y:
886
+ kw["y"] = args.y
887
+ if args.x_label:
888
+ kw["x_label"] = args.x_label
889
+ if args.baseline:
890
+ kw["baseline"] = args.baseline
891
+ if ref is not None:
892
+ kw["reference"] = ref
893
+ if args.log:
894
+ kw["log"] = True
895
+ if args.log_x:
896
+ kw["log_x"] = True
897
+ if args.fit:
898
+ kw["fit"] = True
899
+ panel = fm_exp.trend(args.x, args.series, **kw)
900
+ elif kind in {"distribution", "histogram"}:
901
+ kw = {**common}
902
+ if args.group:
903
+ kw["group"] = args.group
904
+ if args.value:
905
+ kw["value"] = args.value
906
+ if args.baseline:
907
+ kw["baseline"] = args.baseline
908
+ if ref is not None:
909
+ kw["reference"] = ref
910
+ if args.log:
911
+ kw["log"] = True
912
+ if args.mode:
913
+ kw["mode"] = args.mode
914
+ if args.bins is not None:
915
+ kw["bins"] = int(args.bins) if args.bins.isdigit() else args.bins
916
+ panel = (
917
+ fm_exp.histogram(rows, **kw)
918
+ if kind == "histogram"
919
+ else fm_exp.distribution(rows, **kw)
920
+ )
921
+ elif kind == "relate":
922
+ if not (args.x and args.y):
923
+ raise ExplainError(
924
+ "mintfig plot --kind relate requires --x and --y column names.",
925
+ fix_hint="Pass --x cost_col --y score_col [--names model_col] [--groups family_col].",
926
+ )
927
+ kw = {**common, "data": rows}
928
+ kw["x_label"] = args.x_label or args.x
929
+ kw["y_label"] = args.y_label or args.y
930
+ if args.names:
931
+ kw["names"] = args.names
932
+ if args.groups:
933
+ kw["groups"] = args.groups
934
+ if ref is not None:
935
+ kw["reference"] = ref
936
+ if args.log:
937
+ kw["log_y"] = True
938
+ if args.log_x:
939
+ kw["log_x"] = True
940
+ if args.frontier:
941
+ kw["frontier"] = True
942
+ if args.label_all:
943
+ kw["label_all"] = True
944
+ if args.connect_groups:
945
+ kw["connect_groups"] = True
946
+ if args.fit:
947
+ kw["fit"] = True
948
+ panel = fm_exp.relate(args.x, args.y, **kw)
949
+ elif kind == "matrix":
950
+ kw = {**common}
951
+ if args.rows:
952
+ kw["rows"] = args.rows
953
+ if args.cols:
954
+ kw["cols"] = args.cols
955
+ if args.value:
956
+ kw["value"] = args.value
957
+ if args.triangle:
958
+ kw["triangle"] = args.triangle
959
+ if args.mask_diagonal:
960
+ kw["mask_diagonal"] = True
961
+ panel = fm_exp.matrix(rows, **kw)
962
+ elif kind == "table":
963
+ kw = {**common}
964
+ if args.baseline:
965
+ kw["baseline"] = args.baseline
966
+ if args.bold_best:
967
+ kw["bold_best"] = True
968
+ if sort_v is not None and isinstance(sort_v, str):
969
+ kw["sort"] = sort_v
970
+ panel = fm_exp.table(rows, **kw)
971
+ elif kind == "waterfall":
972
+ kw = {**common}
973
+ if args.name:
974
+ kw["name"] = args.name
975
+ if args.value:
976
+ kw["value"] = args.value
977
+ if args.waterfall_start is not None:
978
+ kw["start"] = _parse_waterfall_start(args.waterfall_start)
979
+ if args.total_label != "Total":
980
+ kw["total_label"] = args.total_label
981
+ if args.no_total:
982
+ kw["show_total"] = False
983
+ if ref is not None:
984
+ kw["reference"] = ref
985
+ panel = fm_exp.waterfall(rows, **kw)
986
+ elif kind == "timeline":
987
+ kw = {**common}
988
+ if args.name:
989
+ kw["name"] = args.name
990
+ if args.start:
991
+ kw["start"] = args.start
992
+ if args.end:
993
+ kw["end"] = args.end
994
+ if args.group:
995
+ kw["group"] = args.group
996
+ if args.x_label:
997
+ kw["x_label"] = args.x_label
998
+ if ref is not None:
999
+ kw["reference"] = ref
1000
+ if sort_v is not None:
1001
+ kw["sort"] = bool(sort_v)
1002
+ panel = fm_exp.timeline(rows, **kw)
1003
+ elif kind == "flow":
1004
+ kw = {**common}
1005
+ if args.name:
1006
+ kw["name"] = args.name
1007
+ if args.value:
1008
+ kw["value"] = args.value
1009
+ if args.reason:
1010
+ kw["reason"] = args.reason
1011
+ panel = fm_exp.flow(rows, **kw)
1012
+ else:
1013
+ raise ExplainError(f"Unsupported kind {kind!r}.", fix_hint="Choose a valid form.")
1014
+
1015
+ explanation = fm_exp.explain(
1016
+ args.takeaway,
1017
+ panel,
1018
+ subtitle=args.subtitle,
1019
+ source=args.source,
1020
+ note=args.note,
1021
+ style=args.style,
1022
+ palette=args.palette,
1023
+ accent=args.accent,
1024
+ width=_parse_width_arg(args.width) or "chat",
1025
+ strict=not args.lenient,
1026
+ )
1027
+ except ExplainError as exc:
1028
+ return _reject(exc.message, exc.fix_hint, exc.rule)
1029
+ except (OSError, ValueError, TypeError, KeyError) as exc:
1030
+ return _reject(str(exc), "Check column names with `mintfig inspect <file>` and re-run.")
1031
+
1032
+ return _emit_explanation(
1033
+ explanation,
1034
+ out=args.out,
1035
+ write_spec=args.write_spec,
1036
+ show=args.show,
1037
+ show_mode=args.show_mode,
1038
+ show_width=args.show_width,
1039
+ )
1040
+
1041
+
1042
+ def _run_edit(args: argparse.Namespace) -> int:
1043
+ """Surgically edit a saved mintfig PNG or JSON spec from the CLI."""
1044
+ from .edit import edit as _edit
1045
+ from .explainer import ExplainError
1046
+
1047
+ def _reject(message: str, fix_hint: str, rule: str = "edit_cli") -> int:
1048
+ payload = {
1049
+ "schema_version": "0.2",
1050
+ "ok": False,
1051
+ "rendered": False,
1052
+ "stage": "spec",
1053
+ "rule": rule,
1054
+ "error": message,
1055
+ "fix_hint": fix_hint,
1056
+ }
1057
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1058
+ return 2
1059
+
1060
+ if args.out is None and not args.show:
1061
+ return _reject(
1062
+ "mintfig edit needs --out <path> or --show.",
1063
+ "Pass --out edited.png (or edited.html) or --show.",
1064
+ )
1065
+
1066
+ def _clearable(val: str | None) -> Any:
1067
+ return None if val == "" else val
1068
+
1069
+ try:
1070
+ kwargs: dict[str, Any] = {
1071
+ "panel": args.panel,
1072
+ "strict": not args.lenient,
1073
+ }
1074
+ if args.takeaway is not None:
1075
+ kwargs["takeaway"] = args.takeaway
1076
+ if args.subtitle is not None:
1077
+ kwargs["subtitle"] = _clearable(args.subtitle)
1078
+ if args.source is not None:
1079
+ kwargs["source"] = _clearable(args.source)
1080
+ if args.note is not None:
1081
+ kwargs["note"] = _clearable(args.note)
1082
+ if args.style is not None:
1083
+ kwargs["style"] = args.style
1084
+ if args.palette is not None:
1085
+ kwargs["palette"] = _clearable(args.palette)
1086
+ if args.accent is not None:
1087
+ kwargs["accent"] = _clearable(args.accent)
1088
+ if args.width is not None:
1089
+ kwargs["width"] = _parse_width_arg(args.width)
1090
+ if args.title is not None:
1091
+ kwargs["title"] = _clearable(args.title)
1092
+ if args.label is not None:
1093
+ kwargs["label"] = _clearable(args.label)
1094
+ if args.unit is not None:
1095
+ kwargs["unit"] = _clearable(args.unit)
1096
+ hl = _parse_list_arg(args.highlight)
1097
+ if hl is not None:
1098
+ kwargs["highlight"] = hl if len(hl) > 1 else hl[0]
1099
+ if args.baseline is not None:
1100
+ kwargs["baseline"] = _clearable(args.baseline)
1101
+ if args.sort is not None:
1102
+ kwargs["sort"] = _parse_sort_arg(args.sort)
1103
+ if args.reference is not None:
1104
+ kwargs["reference"] = _parse_reference_arg(args.reference)
1105
+ if args.show_delta is not None:
1106
+ kwargs["show_delta"] = args.show_delta
1107
+ drops = _parse_list_arg(args.drop)
1108
+ if drops is not None:
1109
+ kwargs["drop"] = drops
1110
+ keeps = _parse_list_arg(args.keep)
1111
+ if keeps is not None:
1112
+ kwargs["keep"] = keeps
1113
+ if args.drop_panel is not None:
1114
+ kwargs["drop_panel"] = args.drop_panel
1115
+
1116
+ explanation = _edit(args.figure_path, **kwargs)
1117
+ except ExplainError as exc:
1118
+ return _reject(exc.message, exc.fix_hint, exc.rule)
1119
+ except (OSError, ValueError, TypeError, KeyError) as exc:
1120
+ return _reject(str(exc), "Verify the input PNG/JSON path and edit flags.")
1121
+
1122
+ return _emit_explanation(
1123
+ explanation,
1124
+ out=args.out,
1125
+ write_spec=args.write_spec,
1126
+ show=args.show,
1127
+ show_mode=args.show_mode,
1128
+ show_width=args.show_width,
1129
+ )
1130
+
1131
+
1132
+ class _null_ctx:
1133
+ """Minimal no-op context manager for strict mode inside ``_run_plot``."""
1134
+
1135
+ def __enter__(self) -> None:
1136
+ return None
1137
+
1138
+ def __exit__(self, *args: object) -> None:
1139
+ return None
1140
+
1141
+
1142
+ def _run_brief(args: argparse.Namespace) -> int:
1143
+ """Compose saved mintfig PNGs / JSON specs into a cohesive HTML or Markdown briefing."""
1144
+ from .brief import brief as _brief
1145
+ from .explainer import ExplainError
1146
+
1147
+ try:
1148
+ report = _brief(
1149
+ args.title,
1150
+ *args.figures,
1151
+ subtitle=args.subtitle,
1152
+ summary=args.summary,
1153
+ source=args.source,
1154
+ style=args.style,
1155
+ )
1156
+ meta = report.save(args.out)
1157
+ except (ExplainError, OSError, ValueError, TypeError) as exc:
1158
+ payload = {
1159
+ "ok": False,
1160
+ "error": exc.message if isinstance(exc, ExplainError) else str(exc),
1161
+ "fix_hint": exc.fix_hint if isinstance(exc, ExplainError) else "Check input PNG/JSON paths and --out.",
1162
+ }
1163
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1164
+ return 2
1165
+ print(json.dumps(meta, indent=2, ensure_ascii=False))
1166
+ return 0 if meta["ship_all"] else 1
1167
+
1168
+
1169
+ def _rerun_with_fixed_hash_seed() -> int | None:
1170
+ """Re-run ``mintfig run`` or ``mintfig explain`` with ``PYTHONHASHSEED=0``.
1171
+
1172
+ Matplotlib's PDF font subsetting iterates hash-ordered sets, so the bytes of
1173
+ an embedded bold font (every panel label) vary with Python's per-process
1174
+ string hash seed. The seed can only be chosen before the interpreter starts,
1175
+ so the real CLI re-invokes itself once with a fixed seed to keep
1176
+ ``figure.pdf`` byte-reproducible. Returns the child's exit code, or ``None``
1177
+ when the seed is already set by the caller and no re-run is needed.
1178
+ """
1179
+ if os.environ.get("PYTHONHASHSEED") is not None:
1180
+ return None
1181
+ env = dict(os.environ, PYTHONHASHSEED="0")
1182
+ return subprocess.call([sys.executable, "-m", "mintfig.cli", *sys.argv[1:]], env=env)
1183
+
1184
+
1185
+ def main(argv: Sequence[str] | None = None) -> int:
1186
+ """CLI entry point for `mintfig`."""
1187
+ parser = _build_parser()
1188
+ args = parser.parse_args(list(argv) if argv is not None else None)
1189
+
1190
+ # Only the real command line (argv is None) re-runs; in-process callers keep
1191
+ # their interpreter and can set PYTHONHASHSEED themselves.
1192
+ if argv is None and args.command in {"run", "explain", "plot", "edit"}:
1193
+ child_code = _rerun_with_fixed_hash_seed()
1194
+ if child_code is not None:
1195
+ return child_code
1196
+
1197
+ if args.command == "specs":
1198
+ if args.journal is not None:
1199
+ try:
1200
+ spec = get_spec(args.journal)
1201
+ except (KeyError, ValueError) as exc:
1202
+ print(f"Error: {exc}", file=sys.stderr)
1203
+ return 1
1204
+ if args.as_json:
1205
+ print(json.dumps(_spec_to_dict(spec), indent=2))
1206
+ else:
1207
+ print(_format_single_spec(spec))
1208
+ else:
1209
+ if args.as_json:
1210
+ payload = {key: _spec_to_dict(spec) for key, spec in JOURNALS.items()}
1211
+ print(json.dumps(payload, indent=2))
1212
+ else:
1213
+ print(_format_all_specs())
1214
+ return 0
1215
+
1216
+ if args.command == "check":
1217
+ try:
1218
+ report = preflight_pdf(args.pdf_path, journal=args.journal)
1219
+ except (FileNotFoundError, KeyError, ValueError) as exc:
1220
+ print(f"Error: {exc}", file=sys.stderr)
1221
+ return 1
1222
+
1223
+ if args.as_json:
1224
+ print(json.dumps(report.to_dict(), indent=2))
1225
+ else:
1226
+ print(report.summary())
1227
+
1228
+ passed = report.passed and (not args.strict or not report.warnings)
1229
+ return 0 if passed else 1
1230
+
1231
+ if args.command == "run":
1232
+ try:
1233
+ result = run_script(
1234
+ args.script_path,
1235
+ journal=args.journal,
1236
+ width=_parse_width_arg(args.width),
1237
+ bundle_dir=args.bundle,
1238
+ include_proof=not args.no_proof,
1239
+ strict=args.strict,
1240
+ )
1241
+ except (KeyError, ValueError) as exc:
1242
+ print(f"Error: {exc}", file=sys.stderr)
1243
+ return 2
1244
+
1245
+ if args.as_json:
1246
+ print(json.dumps(result.to_dict(), indent=2))
1247
+ elif result.report is not None:
1248
+ print(result.report.summary())
1249
+ for issue in result.report.issues:
1250
+ if issue.fix_hint:
1251
+ print(f" hint ({issue.rule}): {issue.fix_hint}")
1252
+ if result.bundle is not None:
1253
+ print(f"Bundle written to: {result.bundle.out_dir}")
1254
+ else:
1255
+ print(f"[{result.stage.upper()} ERROR] {result.error}", file=sys.stderr)
1256
+ if result.fix_hint:
1257
+ print(f"Fix hint: {result.fix_hint}", file=sys.stderr)
1258
+ return result.exit_code
1259
+
1260
+ if args.command == "explain":
1261
+ return _run_explain(args)
1262
+
1263
+ if args.command == "show":
1264
+ return _run_show(args)
1265
+
1266
+ if args.command == "inspect":
1267
+ return _run_inspect(args)
1268
+
1269
+ if args.command == "plot":
1270
+ return _run_plot(args)
1271
+
1272
+ if args.command == "edit":
1273
+ return _run_edit(args)
1274
+
1275
+ if args.command == "brief":
1276
+ return _run_brief(args)
1277
+
1278
+ if args.command == "skill":
1279
+ if args.snippet:
1280
+ print(get_agents_snippet(), end="")
1281
+ return 0
1282
+ if args.install:
1283
+ targets = _parse_targets_arg(args.target)
1284
+ try:
1285
+ written = install_skill(root=args.root, targets=targets)
1286
+ except ValueError as exc:
1287
+ print(f"Error: {exc}", file=sys.stderr)
1288
+ return 1
1289
+ for path in written:
1290
+ print(f"Installed: {path}")
1291
+ return 0
1292
+ # Default or --print: output SKILL.md without touching disk
1293
+ print(get_skill_markdown(), end="")
1294
+ return 0
1295
+
1296
+ return 1
1297
+
1298
+
1299
+ if __name__ == "__main__":
1300
+ raise SystemExit(main())