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.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/runner.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Strict-contract script runner for automated preflight and bundle generation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
import runpy
|
|
9
|
+
import sys
|
|
10
|
+
import traceback
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
import matplotlib as mpl
|
|
17
|
+
import matplotlib.pyplot as plt
|
|
18
|
+
from matplotlib import rcsetup
|
|
19
|
+
from matplotlib.figure import Figure
|
|
20
|
+
|
|
21
|
+
from . import style
|
|
22
|
+
from .bundle import BundleResult, bundle_figure
|
|
23
|
+
from .explainer import Explanation
|
|
24
|
+
from .plate import Plate
|
|
25
|
+
from .preflight import PreflightReport, preflight_figure, preflight_pdf
|
|
26
|
+
from .specs import JournalSpec, get_spec
|
|
27
|
+
|
|
28
|
+
RunStage = Literal["preflight", "contract", "runtime"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class RunResult:
|
|
33
|
+
"""Outcome of running a plotting script through mintfig preflight & bundling."""
|
|
34
|
+
|
|
35
|
+
ok: bool
|
|
36
|
+
exit_code: int
|
|
37
|
+
stage: RunStage
|
|
38
|
+
script_path: Path
|
|
39
|
+
report: PreflightReport | None
|
|
40
|
+
bundle: BundleResult | None
|
|
41
|
+
error: str | None
|
|
42
|
+
fix_hint: str | None
|
|
43
|
+
pdf_report: PreflightReport | None
|
|
44
|
+
journal: str = "nature"
|
|
45
|
+
spec_version: str = ""
|
|
46
|
+
spec_source_url: str = ""
|
|
47
|
+
|
|
48
|
+
def to_dict(self) -> dict[str, Any]:
|
|
49
|
+
"""Return the structured v0.2 JSON payload for agents and CI."""
|
|
50
|
+
if self.stage == "preflight" and self.report is not None:
|
|
51
|
+
artifacts = self.bundle.to_dict() if self.bundle is not None else {}
|
|
52
|
+
payload = self.report.to_agent_dict(artifacts=artifacts)
|
|
53
|
+
payload["ok"] = self.ok
|
|
54
|
+
payload["exit_code"] = self.exit_code
|
|
55
|
+
payload["stage"] = self.stage
|
|
56
|
+
payload["script_path"] = str(self.script_path)
|
|
57
|
+
return payload
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
"schema_version": "0.2",
|
|
61
|
+
"ok": False,
|
|
62
|
+
"exit_code": self.exit_code,
|
|
63
|
+
"stage": self.stage,
|
|
64
|
+
"script_path": str(self.script_path),
|
|
65
|
+
"journal": self.journal,
|
|
66
|
+
"spec_version": self.spec_version,
|
|
67
|
+
"spec_source_url": self.spec_source_url,
|
|
68
|
+
"dimensions_mm": None,
|
|
69
|
+
"summary": {"errors": 1, "warnings": 0, "passed": 0},
|
|
70
|
+
"recommended_max_loops": 2,
|
|
71
|
+
"error": self.error,
|
|
72
|
+
"fix_hint": self.fix_hint,
|
|
73
|
+
"issues": [
|
|
74
|
+
{
|
|
75
|
+
"rule": f"script_{self.stage}",
|
|
76
|
+
"severity": "error",
|
|
77
|
+
"panel": None,
|
|
78
|
+
"elements": [self.script_path.name],
|
|
79
|
+
"message": self.error or f"Script {self.stage} failure",
|
|
80
|
+
"fix_hint": self.fix_hint,
|
|
81
|
+
}
|
|
82
|
+
],
|
|
83
|
+
"artifacts": {},
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _script_line_info(exc: BaseException, script_path: Path) -> str:
|
|
88
|
+
"""Return `` at script.py:LINE`` for the innermost traceback frame in the script, or ``""``."""
|
|
89
|
+
if isinstance(exc, SyntaxError) and exc.lineno is not None:
|
|
90
|
+
return f" at {script_path.name}:{exc.lineno}"
|
|
91
|
+
target_str = str(script_path.resolve())
|
|
92
|
+
for frame in reversed(traceback.extract_tb(exc.__traceback__)):
|
|
93
|
+
if str(Path(frame.filename).resolve()) == target_str:
|
|
94
|
+
return f" at {script_path.name}:{frame.lineno}"
|
|
95
|
+
return ""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _format_runtime_error(exc: BaseException, script_path: Path) -> str:
|
|
99
|
+
"""Format a concise runtime error message including script line number when available."""
|
|
100
|
+
return f"{type(exc).__name__}{_script_line_info(exc, script_path)}: {exc}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _merge_pdf_errors(report: PreflightReport, pdf_report: PreflightReport) -> bool:
|
|
104
|
+
"""Merge PDF-only failures (e.g. Type 3 fonts or MediaBox drift) into ``report``.
|
|
105
|
+
|
|
106
|
+
A live-figure check that marks itself ``details["authoritative"] = False``
|
|
107
|
+
(a prediction from current rcParams, such as ``vector_fonts``) is replaced
|
|
108
|
+
by the exported PDF's result for the same rule whatever that result is,
|
|
109
|
+
because the file on disk is what gets submitted.
|
|
110
|
+
|
|
111
|
+
Returns True if ``report`` was modified.
|
|
112
|
+
"""
|
|
113
|
+
modified = False
|
|
114
|
+
existing_by_rule = {c.rule: idx for idx, c in enumerate(report.checks)}
|
|
115
|
+
pdf_by_rule = {c.rule: c for c in pdf_report.checks}
|
|
116
|
+
for rule, idx in existing_by_rule.items():
|
|
117
|
+
live = report.checks[idx]
|
|
118
|
+
pdf_check = pdf_by_rule.get(rule)
|
|
119
|
+
if (
|
|
120
|
+
pdf_check is not None
|
|
121
|
+
and live.details.get("authoritative") is False
|
|
122
|
+
and live.status != pdf_check.status
|
|
123
|
+
):
|
|
124
|
+
report.checks[idx] = pdf_check
|
|
125
|
+
modified = True
|
|
126
|
+
for pdf_check in pdf_report.failures:
|
|
127
|
+
idx = existing_by_rule.get(pdf_check.rule)
|
|
128
|
+
if idx is None:
|
|
129
|
+
report.checks.append(pdf_check)
|
|
130
|
+
modified = True
|
|
131
|
+
elif report.checks[idx].status != "fail":
|
|
132
|
+
report.checks[idx] = pdf_check
|
|
133
|
+
modified = True
|
|
134
|
+
return modified
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _explanation_figure(explanation: Explanation) -> Figure:
|
|
138
|
+
"""Unwrap ``mint.explain(...)`` for the runner, keeping its style active for export.
|
|
139
|
+
|
|
140
|
+
An Explanation renders under a scoped style; fonts are resolved at draw
|
|
141
|
+
time, so the same rcParams must be live while the runner saves the bundle.
|
|
142
|
+
``run_script`` restores the caller's rcParams afterwards.
|
|
143
|
+
"""
|
|
144
|
+
style.apply(explanation.spec)
|
|
145
|
+
return explanation.fig
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _discover_target(
|
|
149
|
+
namespace: dict[str, Any],
|
|
150
|
+
*,
|
|
151
|
+
spec: JournalSpec,
|
|
152
|
+
width: str | float | None,
|
|
153
|
+
script_path: Path | None = None,
|
|
154
|
+
) -> tuple[Plate | Figure | None, RunStage | None, str | None, str | None]:
|
|
155
|
+
"""Resolve ``build()``, ``plate``, or ``fig`` according to the strict script contract."""
|
|
156
|
+
build_fn = namespace.get("build")
|
|
157
|
+
if callable(build_fn):
|
|
158
|
+
try:
|
|
159
|
+
sig = inspect.signature(build_fn)
|
|
160
|
+
except (TypeError, ValueError):
|
|
161
|
+
sig = None
|
|
162
|
+
|
|
163
|
+
kwargs: dict[str, Any] = {}
|
|
164
|
+
if sig is not None:
|
|
165
|
+
if "journal" in sig.parameters:
|
|
166
|
+
kwargs["journal"] = spec.name
|
|
167
|
+
if "width" in sig.parameters and width is not None:
|
|
168
|
+
kwargs["width"] = width
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
target = build_fn(**kwargs)
|
|
172
|
+
except Exception as exc: # noqa: BLE001
|
|
173
|
+
line_info = _script_line_info(exc, script_path) if script_path is not None else ""
|
|
174
|
+
return (
|
|
175
|
+
None,
|
|
176
|
+
"runtime",
|
|
177
|
+
f"{type(exc).__name__} in build(){line_info}: {exc}",
|
|
178
|
+
"Fix the runtime exception inside build() and re-run `mintfig run`.",
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if isinstance(target, Explanation):
|
|
182
|
+
target = _explanation_figure(target)
|
|
183
|
+
if isinstance(target, (Plate, Figure)):
|
|
184
|
+
return target, None, None, None
|
|
185
|
+
return (
|
|
186
|
+
None,
|
|
187
|
+
"contract",
|
|
188
|
+
f"build() returned {type(target).__name__}, expected mintfig.Plate or matplotlib.figure.Figure.",
|
|
189
|
+
"Return a `mint.Plate` or `matplotlib.figure.Figure` from `def build() -> mint.Plate:`.",
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
for name in ("explanation", "fig"):
|
|
193
|
+
if isinstance(namespace.get(name), Explanation):
|
|
194
|
+
return _explanation_figure(namespace[name]), None, None, None
|
|
195
|
+
|
|
196
|
+
plate_obj = namespace.get("plate")
|
|
197
|
+
if isinstance(plate_obj, Plate):
|
|
198
|
+
return plate_obj, None, None, None
|
|
199
|
+
|
|
200
|
+
fig_obj = namespace.get("fig")
|
|
201
|
+
if isinstance(fig_obj, Figure):
|
|
202
|
+
return fig_obj, None, None, None
|
|
203
|
+
|
|
204
|
+
return (
|
|
205
|
+
None,
|
|
206
|
+
"contract",
|
|
207
|
+
"Script did not expose a `build()` callable, top-level `plate` (Plate), or top-level `fig` (Figure).",
|
|
208
|
+
"Expose `plate = mint.Plate(...)` at module scope or define `def build() -> mint.Plate:`.",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@contextlib.contextmanager
|
|
213
|
+
def _headless_backend() -> Iterator[None]:
|
|
214
|
+
"""Run the enclosed block under the non-interactive Agg backend.
|
|
215
|
+
|
|
216
|
+
Interactive backends (e.g. ``macosx``) resize new figures to whole screen
|
|
217
|
+
pixels, which breaks the millimetre lock. While active, ``matplotlib.use``
|
|
218
|
+
and ``pyplot.switch_backend`` calls from user scripts are ignored. The
|
|
219
|
+
caller's backend (or its unresolved auto-selection state) is restored on exit.
|
|
220
|
+
"""
|
|
221
|
+
prev_backend = mpl.rcParams._get("backend") # raw value; may be the auto sentinel
|
|
222
|
+
prev_default = mpl.rcParamsDefault._get("backend")
|
|
223
|
+
prev_backend_mod = plt._backend_mod
|
|
224
|
+
orig_switch = plt.switch_backend
|
|
225
|
+
orig_use = mpl.use
|
|
226
|
+
|
|
227
|
+
orig_switch("agg")
|
|
228
|
+
|
|
229
|
+
def _ignore_switch(*_args: Any, **_kwargs: Any) -> None:
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
plt.switch_backend = _ignore_switch # type: ignore[assignment]
|
|
233
|
+
mpl.use = _ignore_switch # type: ignore[assignment]
|
|
234
|
+
try:
|
|
235
|
+
yield
|
|
236
|
+
finally:
|
|
237
|
+
plt.switch_backend = orig_switch # type: ignore[assignment]
|
|
238
|
+
mpl.use = orig_use # type: ignore[assignment]
|
|
239
|
+
if prev_backend is rcsetup._auto_backend_sentinel or prev_backend_mod is None:
|
|
240
|
+
# Backend had not been resolved yet: restore lazy auto-selection.
|
|
241
|
+
mpl.rcParams._set("backend", prev_backend)
|
|
242
|
+
mpl.rcParamsDefault._set("backend", prev_default)
|
|
243
|
+
plt._backend_mod = None
|
|
244
|
+
else:
|
|
245
|
+
if str(prev_backend).lower() != "agg":
|
|
246
|
+
orig_switch(prev_backend)
|
|
247
|
+
mpl.rcParamsDefault._set("backend", prev_default)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def run_script(
|
|
251
|
+
script_path: str | Path,
|
|
252
|
+
*,
|
|
253
|
+
journal: str | JournalSpec = "nature",
|
|
254
|
+
width: str | float | None = None,
|
|
255
|
+
bundle_dir: str | Path | None = None,
|
|
256
|
+
include_proof: bool = True,
|
|
257
|
+
strict: bool = False,
|
|
258
|
+
) -> RunResult:
|
|
259
|
+
"""Execute a plotting script, preflight its figure, and optionally export a bundle."""
|
|
260
|
+
path = Path(script_path).resolve()
|
|
261
|
+
spec = get_spec(journal)
|
|
262
|
+
spec_version = getattr(spec, "spec_version", "")
|
|
263
|
+
spec_source_url = getattr(spec, "source_url", "")
|
|
264
|
+
|
|
265
|
+
if not path.exists():
|
|
266
|
+
return RunResult(
|
|
267
|
+
ok=False,
|
|
268
|
+
exit_code=2,
|
|
269
|
+
stage="runtime",
|
|
270
|
+
script_path=path,
|
|
271
|
+
report=None,
|
|
272
|
+
bundle=None,
|
|
273
|
+
error=f"Script not found: {path}",
|
|
274
|
+
fix_hint=f"Verify that the script path {path} exists and is readable.",
|
|
275
|
+
pdf_report=None,
|
|
276
|
+
journal=spec.name,
|
|
277
|
+
spec_version=spec_version,
|
|
278
|
+
spec_source_url=spec_source_url,
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
orig_sys_path = list(sys.path)
|
|
282
|
+
orig_show = plt.show
|
|
283
|
+
existing_fignums = set(plt.get_fignums())
|
|
284
|
+
created_fig: Figure | None = None
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
with _headless_backend(), mpl.rc_context():
|
|
288
|
+
script_dir = str(path.parent)
|
|
289
|
+
if not sys.path or sys.path[0] != script_dir:
|
|
290
|
+
sys.path.insert(0, script_dir)
|
|
291
|
+
# Prevent user scripts calling plt.show() from blocking headless runs
|
|
292
|
+
plt.show = lambda *_args, **_kwargs: None # type: ignore[assignment]
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
namespace = runpy.run_path(str(path), run_name="__mintfig_run__")
|
|
296
|
+
except Exception as exc: # noqa: BLE001
|
|
297
|
+
return RunResult(
|
|
298
|
+
ok=False,
|
|
299
|
+
exit_code=2,
|
|
300
|
+
stage="runtime",
|
|
301
|
+
script_path=path,
|
|
302
|
+
report=None,
|
|
303
|
+
bundle=None,
|
|
304
|
+
error=_format_runtime_error(exc, path),
|
|
305
|
+
fix_hint="Fix the Python exception in the plotting script and re-run `mintfig run`.",
|
|
306
|
+
pdf_report=None,
|
|
307
|
+
journal=spec.name,
|
|
308
|
+
spec_version=spec_version,
|
|
309
|
+
spec_source_url=spec_source_url,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
target, err_stage, err_msg, err_hint = _discover_target(
|
|
313
|
+
namespace, spec=spec, width=width, script_path=path
|
|
314
|
+
)
|
|
315
|
+
if target is None:
|
|
316
|
+
return RunResult(
|
|
317
|
+
ok=False,
|
|
318
|
+
exit_code=2,
|
|
319
|
+
stage=err_stage or "contract",
|
|
320
|
+
script_path=path,
|
|
321
|
+
report=None,
|
|
322
|
+
bundle=None,
|
|
323
|
+
error=err_msg,
|
|
324
|
+
fix_hint=err_hint,
|
|
325
|
+
pdf_report=None,
|
|
326
|
+
journal=spec.name,
|
|
327
|
+
spec_version=spec_version,
|
|
328
|
+
spec_source_url=spec_source_url,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
created_fig = target.fig if isinstance(target, Plate) else target
|
|
332
|
+
report = preflight_figure(created_fig, spec, strict=False)
|
|
333
|
+
|
|
334
|
+
bundle_res: BundleResult | None = None
|
|
335
|
+
pdf_report: PreflightReport | None = None
|
|
336
|
+
if bundle_dir is not None:
|
|
337
|
+
raw_caption = namespace.get("CAPTION")
|
|
338
|
+
script_caption = (
|
|
339
|
+
raw_caption.strip()
|
|
340
|
+
if isinstance(raw_caption, str) and raw_caption.strip()
|
|
341
|
+
else None
|
|
342
|
+
)
|
|
343
|
+
raw_label = namespace.get("LABEL")
|
|
344
|
+
script_label = (
|
|
345
|
+
raw_label.strip()
|
|
346
|
+
if isinstance(raw_label, str) and raw_label.strip()
|
|
347
|
+
else "fig:fig1"
|
|
348
|
+
)
|
|
349
|
+
raw_takeaway = namespace.get("TAKEAWAY")
|
|
350
|
+
script_takeaway = (
|
|
351
|
+
raw_takeaway.strip()
|
|
352
|
+
if isinstance(raw_takeaway, str) and raw_takeaway.strip()
|
|
353
|
+
else None
|
|
354
|
+
)
|
|
355
|
+
raw_notes = namespace.get("PANEL_NOTES")
|
|
356
|
+
script_notes = (
|
|
357
|
+
{str(k): str(v) for k, v in raw_notes.items()}
|
|
358
|
+
if isinstance(raw_notes, dict)
|
|
359
|
+
else None
|
|
360
|
+
)
|
|
361
|
+
bundle_res = bundle_figure(
|
|
362
|
+
target,
|
|
363
|
+
bundle_dir,
|
|
364
|
+
journal=spec,
|
|
365
|
+
report=report,
|
|
366
|
+
source_path=path,
|
|
367
|
+
caption=script_caption,
|
|
368
|
+
label=script_label,
|
|
369
|
+
takeaway=script_takeaway,
|
|
370
|
+
panel_notes=script_notes,
|
|
371
|
+
include_proof=include_proof,
|
|
372
|
+
)
|
|
373
|
+
pdf_report = preflight_pdf(bundle_res.figure_pdf, spec)
|
|
374
|
+
if _merge_pdf_errors(report, pdf_report):
|
|
375
|
+
payload = report.to_agent_dict(artifacts=bundle_res.to_dict())
|
|
376
|
+
bundle_res.report_json.write_text(
|
|
377
|
+
json.dumps(payload, indent=2) + "\n", encoding="utf-8"
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
ok = report.passed and (not strict or not report.warnings)
|
|
381
|
+
exit_code = 0 if ok else 1
|
|
382
|
+
|
|
383
|
+
return RunResult(
|
|
384
|
+
ok=ok,
|
|
385
|
+
exit_code=exit_code,
|
|
386
|
+
stage="preflight",
|
|
387
|
+
script_path=path,
|
|
388
|
+
report=report,
|
|
389
|
+
bundle=bundle_res,
|
|
390
|
+
error=None,
|
|
391
|
+
fix_hint=None,
|
|
392
|
+
pdf_report=pdf_report,
|
|
393
|
+
journal=spec.name,
|
|
394
|
+
spec_version=spec_version,
|
|
395
|
+
spec_source_url=spec_source_url,
|
|
396
|
+
)
|
|
397
|
+
finally:
|
|
398
|
+
plt.show = orig_show
|
|
399
|
+
sys.path[:] = orig_sys_path
|
|
400
|
+
if created_fig is not None:
|
|
401
|
+
plt.close(created_fig)
|
|
402
|
+
for num in set(plt.get_fignums()) - existing_fignums:
|
|
403
|
+
plt.close(num)
|
mintfig/skill.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Bundled agent skill and project instruction installers for mintfig."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from importlib import resources
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
VALID_TARGETS: tuple[str, ...] = (
|
|
10
|
+
"claude",
|
|
11
|
+
"antigravity",
|
|
12
|
+
"cursor",
|
|
13
|
+
"codex",
|
|
14
|
+
"agents-md",
|
|
15
|
+
"claude-md",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
MARKER_START: str = "<!-- mintfig:start -->"
|
|
19
|
+
MARKER_END: str = "<!-- mintfig:end -->"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_skill_markdown() -> str:
|
|
23
|
+
"""Return the bundled mintfig SKILL.md content."""
|
|
24
|
+
return resources.files("mintfig.assets").joinpath("SKILL.md").read_text(encoding="utf-8")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_agents_snippet() -> str:
|
|
28
|
+
"""Return the bundled marker-wrapped AGENTS.md / CLAUDE.md snippet."""
|
|
29
|
+
return (
|
|
30
|
+
resources.files("mintfig.assets")
|
|
31
|
+
.joinpath("AGENTS_SNIPPET.md")
|
|
32
|
+
.read_text(encoding="utf-8")
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_skill_references() -> dict[str, str]:
|
|
37
|
+
"""Return bundled skill reference markdown files keyed by filename."""
|
|
38
|
+
ref_dir = resources.files("mintfig.assets").joinpath("references")
|
|
39
|
+
if not ref_dir.is_dir():
|
|
40
|
+
return {}
|
|
41
|
+
out: dict[str, str] = {}
|
|
42
|
+
for entry in sorted(ref_dir.iterdir(), key=lambda p: p.name):
|
|
43
|
+
if entry.name.endswith(".md"):
|
|
44
|
+
out[entry.name] = entry.read_text(encoding="utf-8")
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _strip_yaml_frontmatter(markdown: str) -> str:
|
|
49
|
+
"""Remove leading YAML frontmatter block if present."""
|
|
50
|
+
if not markdown.startswith("---\n"):
|
|
51
|
+
return markdown
|
|
52
|
+
end = markdown.find("\n---\n", 4)
|
|
53
|
+
if end == -1:
|
|
54
|
+
return markdown
|
|
55
|
+
return markdown[end + len("\n---\n") :].lstrip("\n")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _build_cursor_mdc(skill_md: str) -> str:
|
|
59
|
+
"""Wrap the skill body with valid Cursor .mdc rule frontmatter."""
|
|
60
|
+
body = _strip_yaml_frontmatter(skill_md).rstrip() + "\n"
|
|
61
|
+
frontmatter = (
|
|
62
|
+
"---\n"
|
|
63
|
+
"description: Explain data with message-first chat figures and tables (mint.explain, mint.table), "
|
|
64
|
+
"or generate publication-ready Nature, Science, Cell, PNAS, and NeurIPS scientific figures with mintfig\n"
|
|
65
|
+
"globs:\n"
|
|
66
|
+
' - "**/*.py"\n'
|
|
67
|
+
' - "**/*.csv"\n'
|
|
68
|
+
' - "**/*.json"\n'
|
|
69
|
+
"alwaysApply: false\n"
|
|
70
|
+
"---\n\n"
|
|
71
|
+
)
|
|
72
|
+
return frontmatter + body
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _upsert_marked_block(path: Path, snippet: str) -> Path:
|
|
76
|
+
"""Idempotently insert or replace the marker-wrapped snippet inside ``path``."""
|
|
77
|
+
block = snippet.strip()
|
|
78
|
+
if MARKER_START not in block or MARKER_END not in block:
|
|
79
|
+
block = f"{MARKER_START}\n{block}\n{MARKER_END}"
|
|
80
|
+
|
|
81
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
if not path.exists():
|
|
83
|
+
path.write_text(block + "\n", encoding="utf-8")
|
|
84
|
+
return path
|
|
85
|
+
|
|
86
|
+
existing = path.read_text(encoding="utf-8")
|
|
87
|
+
start_idx = existing.find(MARKER_START)
|
|
88
|
+
end_idx = existing.find(MARKER_END, start_idx + len(MARKER_START)) if start_idx != -1 else -1
|
|
89
|
+
|
|
90
|
+
if start_idx != -1 and end_idx != -1:
|
|
91
|
+
updated = existing[:start_idx] + block + existing[end_idx + len(MARKER_END) :]
|
|
92
|
+
elif not existing.strip():
|
|
93
|
+
updated = block + "\n"
|
|
94
|
+
else:
|
|
95
|
+
sep = "\n\n" if not existing.endswith("\n") else ("\n" if not existing.endswith("\n\n") else "")
|
|
96
|
+
updated = existing + sep + block + "\n"
|
|
97
|
+
|
|
98
|
+
path.write_text(updated, encoding="utf-8")
|
|
99
|
+
return path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def install_skill(
|
|
103
|
+
root: str | Path = ".",
|
|
104
|
+
*,
|
|
105
|
+
targets: Sequence[str] = ("claude", "antigravity", "agents-md"),
|
|
106
|
+
) -> list[Path]:
|
|
107
|
+
"""Install mintfig agent skills and/or project instruction snippets under ``root``.
|
|
108
|
+
|
|
109
|
+
Parameters
|
|
110
|
+
----------
|
|
111
|
+
root:
|
|
112
|
+
Target project root directory.
|
|
113
|
+
targets:
|
|
114
|
+
One or more target identifiers from :data:`VALID_TARGETS`:
|
|
115
|
+
``"claude"``, ``"antigravity"``, ``"cursor"``, ``"codex"``,
|
|
116
|
+
``"agents-md"``, ``"claude-md"``.
|
|
117
|
+
|
|
118
|
+
Returns
|
|
119
|
+
-------
|
|
120
|
+
list[Path]
|
|
121
|
+
Paths created or updated, in the order requested.
|
|
122
|
+
"""
|
|
123
|
+
normalized: list[str] = []
|
|
124
|
+
seen: set[str] = set()
|
|
125
|
+
for raw in targets:
|
|
126
|
+
key = raw.strip().lower()
|
|
127
|
+
if key not in VALID_TARGETS:
|
|
128
|
+
valid = ", ".join(VALID_TARGETS)
|
|
129
|
+
raise ValueError(f"Unknown skill install target {raw!r}. Valid targets: {valid}")
|
|
130
|
+
if key not in seen:
|
|
131
|
+
normalized.append(key)
|
|
132
|
+
seen.add(key)
|
|
133
|
+
|
|
134
|
+
root_path = Path(root)
|
|
135
|
+
skill_md = get_skill_markdown()
|
|
136
|
+
references = get_skill_references()
|
|
137
|
+
snippet = get_agents_snippet()
|
|
138
|
+
written: list[Path] = []
|
|
139
|
+
|
|
140
|
+
def _write_skill_dir(dest: Path) -> Path:
|
|
141
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
dest.write_text(skill_md, encoding="utf-8")
|
|
143
|
+
if references:
|
|
144
|
+
ref_root = dest.parent / "references"
|
|
145
|
+
ref_root.mkdir(parents=True, exist_ok=True)
|
|
146
|
+
for fname, content in references.items():
|
|
147
|
+
(ref_root / fname).write_text(content, encoding="utf-8")
|
|
148
|
+
return dest
|
|
149
|
+
|
|
150
|
+
for target in normalized:
|
|
151
|
+
if target == "claude":
|
|
152
|
+
written.append(_write_skill_dir(root_path / ".claude" / "skills" / "mintfig" / "SKILL.md"))
|
|
153
|
+
elif target == "antigravity":
|
|
154
|
+
written.append(_write_skill_dir(root_path / ".agents" / "skills" / "mintfig" / "SKILL.md"))
|
|
155
|
+
elif target == "cursor":
|
|
156
|
+
dest = root_path / ".cursor" / "rules" / "mintfig.mdc"
|
|
157
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
dest.write_text(_build_cursor_mdc(skill_md), encoding="utf-8")
|
|
159
|
+
written.append(dest)
|
|
160
|
+
elif target == "codex":
|
|
161
|
+
written.append(_write_skill_dir(root_path / ".codex" / "skills" / "mintfig" / "SKILL.md"))
|
|
162
|
+
elif target == "agents-md":
|
|
163
|
+
written.append(_upsert_marked_block(root_path / "AGENTS.md", snippet))
|
|
164
|
+
elif target == "claude-md":
|
|
165
|
+
written.append(_upsert_marked_block(root_path / "CLAUDE.md", snippet))
|
|
166
|
+
|
|
167
|
+
return written
|