mintchip 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.
mintchip/doctor.py ADDED
@@ -0,0 +1,145 @@
1
+ """Terminal & environment diagnostics for ``mintchip doctor``.
2
+
3
+ Reports Python version, mintchip version, stdout encoding/TTY/ANSI color support, and
4
+ renders compact Unicode, ANSI, and ASCII probe lines across key chips so users and agents
5
+ can verify glyph legibility in their terminal or editor.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import platform
14
+ import sys
15
+ from typing import Any
16
+
17
+ import mintchip as mc
18
+
19
+ __all__ = ["PROBE_KINDS", "add_doctor_parser", "cmd_doctor", "doctor_report", "format_doctor"]
20
+
21
+ PROBE_KINDS: tuple[str, ...] = ("spark", "ci", "dist", "bar", "strip")
22
+
23
+
24
+ def _probe_chips() -> list[tuple[str, mc.Chip]]:
25
+ return [
26
+ ("spark", mc.spark([1.84, 1.32, 0.96, 0.62, 0.42], band=(0.38, 0.48))),
27
+ ("ci", mc.ci(0.08, (0.05, 0.11), level=0.95)),
28
+ (
29
+ "dist",
30
+ mc.dist(
31
+ [18.9, 19.4, 19.8, 20.1, 20.3, 20.9, 21.6, 22.8, 47.8],
32
+ threshold=21.0,
33
+ unit="ms",
34
+ ),
35
+ ),
36
+ ("bar", mc.bar(0.82, target=0.9)),
37
+ ("strip", mc.strip([True, True, True, "warn", True, False, True, None])),
38
+ ]
39
+
40
+
41
+ def _ansi_color_status(isatty: bool) -> tuple[bool, str]:
42
+ """Determine ANSI color readiness from standard env vars and TTY state."""
43
+ if os.environ.get("NO_COLOR", "") != "":
44
+ return False, "disabled (NO_COLOR is set)"
45
+ if os.environ.get("FORCE_COLOR", "") not in ("", "0"):
46
+ return True, "enabled (FORCE_COLOR is set)"
47
+ term = os.environ.get("TERM", "")
48
+ if term.lower() == "dumb":
49
+ return False, "disabled (TERM=dumb)"
50
+ if isatty:
51
+ return True, f"enabled (TTY, TERM={term or 'unset'})"
52
+ return False, "inactive (stdout is not a TTY; pass --format ansi to force)"
53
+
54
+
55
+ def doctor_report() -> dict[str, Any]:
56
+ """Collect environment details and Unicode/ANSI/ASCII chip probe lines."""
57
+ encoding = getattr(sys.stdout, "encoding", None) or "unknown"
58
+ isatty_fn = getattr(sys.stdout, "isatty", None)
59
+ isatty = bool(isatty_fn()) if callable(isatty_fn) else False
60
+ unicode_ok = encoding.lower().replace("_", "-").startswith("utf")
61
+ ansi_ok, ansi_reason = _ansi_color_status(isatty)
62
+
63
+ probes: list[dict[str, str]] = []
64
+ for kind, chip in _probe_chips():
65
+ probes.append(
66
+ {
67
+ "kind": kind,
68
+ "unicode": chip.text(ascii=False, compact=True, color=False),
69
+ "ansi": chip.text(ascii=False, compact=True, color=True),
70
+ "ascii": chip.text(ascii=True, compact=True, color=False),
71
+ }
72
+ )
73
+
74
+ return {
75
+ "mintchip": mc.__version__,
76
+ "python": platform.python_version(),
77
+ "platform": platform.platform(),
78
+ "stdout": {
79
+ "encoding": encoding,
80
+ "isatty": isatty,
81
+ "unicode": unicode_ok,
82
+ "ansi_color": ansi_ok,
83
+ "ansi_reason": ansi_reason,
84
+ "term": os.environ.get("TERM", ""),
85
+ "no_color": os.environ.get("NO_COLOR", "") != "",
86
+ },
87
+ "probes": probes,
88
+ }
89
+
90
+
91
+ def format_doctor(report: dict[str, Any], *, ascii: bool = False) -> str:
92
+ """Format a :func:`doctor_report` dictionary for human/agent terminal display."""
93
+ out = report["stdout"]
94
+ rule = "-" * 64 if ascii else "─" * 64
95
+ lines = [
96
+ f"mintchip doctor (mintchip {report['mintchip']})",
97
+ rule,
98
+ f" Python : {report['python']}",
99
+ f" mintchip : {report['mintchip']}",
100
+ f" stdout encoding : {out['encoding']} ({'UTF ok' if out['unicode'] else 'non-UTF; use --ascii'})",
101
+ f" stdout TTY : {'yes' if out['isatty'] else 'no'}",
102
+ f" ANSI color : {out['ansi_reason']}",
103
+ "",
104
+ "Glyph probes (verify sparkline blocks, whiskers, histogram, bars, and strip cells):",
105
+ ]
106
+ kind_w = max(len(p["kind"]) for p in report["probes"])
107
+ for probe in report["probes"]:
108
+ k = f"{probe['kind']:<{kind_w}}"
109
+ if ascii:
110
+ lines.append(f" {k} ascii {probe['ascii']}")
111
+ else:
112
+ lines.append(f" {k} uni {probe['unicode']}")
113
+ lines.append(f" {' ' * kind_w} ansi {probe['ansi']}")
114
+ lines.append(f" {' ' * kind_w} ascii {probe['ascii']}")
115
+ return "\n".join(lines)
116
+
117
+
118
+ def add_doctor_parser(sub: Any, formatter_class: Any) -> argparse.ArgumentParser:
119
+ """Register the ``mintchip doctor`` subcommand."""
120
+ p = sub.add_parser(
121
+ "doctor",
122
+ help="Check Python/TTY/UTF-8/ANSI readiness and print chip glyph probes.",
123
+ description=(
124
+ "Report Python version, mintchip version, stdout encoding, TTY and ANSI color status,\n"
125
+ "and render compact Unicode, ANSI, and ASCII probe lines across spark, ci, dist, bar,\n"
126
+ "and strip so you can verify glyph legibility in your terminal or editor."
127
+ ),
128
+ formatter_class=formatter_class,
129
+ )
130
+ p.add_argument("--json", dest="as_json", action="store_true", help="Print report as JSON.")
131
+ p.add_argument("--ascii", action="store_true", help="ASCII-only probe output.")
132
+ p.set_defaults(func=cmd_doctor, _parser=p)
133
+ return p
134
+
135
+
136
+ def cmd_doctor(args: argparse.Namespace) -> int:
137
+ """Execute ``mintchip doctor``."""
138
+ from .cli import _out
139
+
140
+ report = doctor_report()
141
+ if args.as_json:
142
+ _out(json.dumps(report, indent=2, ensure_ascii=args.ascii))
143
+ else:
144
+ _out(format_doctor(report, ascii=args.ascii))
145
+ return 0
mintchip/fmt.py ADDED
@@ -0,0 +1,135 @@
1
+ """Number formatting shared by every chip.
2
+
3
+ Formatters return Unicode (the minus sign is U+2212). ``Chip.text(ascii=True)`` transliterates
4
+ the whole output afterwards, so renderers never branch on ASCII for numbers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+
12
+ __all__ = [
13
+ "MINUS", "count", "decimals", "fixed", "num", "pct", "places", "pm", "resolving", "with_unit",
14
+ ] # fmt: skip
15
+
16
+ MINUS = "\N{MINUS SIGN}"
17
+ _TIGHT_UNITS = frozenset({"%", "‰", "°", "°C", "°F", "×"})
18
+
19
+
20
+ def with_unit(core: str, unit: str | None) -> str:
21
+ """Attach a unit: ``20.3 ms``, but ``82%`` and ``21°C`` with no space."""
22
+ if not unit:
23
+ return core
24
+ return f"{core}{unit}" if unit in _TIGHT_UNITS else f"{core} {unit}"
25
+
26
+
27
+ def _sign(v: float, core: str, signed: bool) -> str:
28
+ if core == "0":
29
+ return core
30
+ if v < 0:
31
+ return MINUS + core
32
+ return f"+{core}" if signed else core
33
+
34
+
35
+ def _strip(s: str) -> str:
36
+ return s.rstrip("0").rstrip(".") if "." in s else s
37
+
38
+
39
+ def _sci(a: float, sig: int) -> str:
40
+ mant, exp = f"{a:.{max(sig - 1, 0)}e}".split("e")
41
+ e = int(exp)
42
+ return f"{_strip(mant)}e{MINUS if e < 0 else ''}{abs(e)}"
43
+
44
+
45
+ def num(v: float, *, sig: int = 3, signed: bool = False, unit: str | None = None) -> str:
46
+ """``sig`` significant figures, thousands separators, scientific below 1e-3 and from 1e6."""
47
+ if not math.isfinite(v):
48
+ raise ValueError(f"cannot format non-finite value {v!r}")
49
+ a = abs(v)
50
+ if a == 0:
51
+ core = "0"
52
+ elif a >= 1e6 or a < 1e-3:
53
+ core = _sci(a, sig)
54
+ else:
55
+ dec = max(0, sig - 1 - math.floor(math.log10(a)))
56
+ core = _strip(f"{round(a, dec):,.{dec}f}")
57
+ return with_unit(_sign(v, core, signed), unit)
58
+
59
+
60
+ def count(n: float, *, unit: str | None = None) -> str:
61
+ """An integer count with thousands separators: ``1,200``."""
62
+ return with_unit(_sign(n, f"{round(abs(n)):,}", False), unit)
63
+
64
+
65
+ def pct(frac: float, *, sig: int = 2, signed: bool = False, decimals: int | None = None) -> str:
66
+ """A fraction as a percentage: 0.82 → ``82%``, 0.064 → ``6.4%``, 0.9993 → ``99.9%``;
67
+ ``decimals`` fixes the places instead (0.82 at 1 → ``82.0%``)."""
68
+ p = frac * 100
69
+ a = abs(p)
70
+ if decimals is not None:
71
+ core = fixed(a, decimals)
72
+ if float(core.replace(",", "")) >= 100 > a: # never round a shortfall up to 100%
73
+ step = 10.0 ** -max(decimals, 0)
74
+ core = fixed(math.floor(a / step) * step, decimals)
75
+ return _sign(p, core, signed) + "%"
76
+ if 10 <= a < 1e6:
77
+ core = f"{round(a):,}"
78
+ if core == "100" and a < 100: # never round a shortfall up to 100%
79
+ core = _strip(f"{math.floor(a * 10) / 10:.1f}")
80
+ return _sign(p, core, signed) + "%"
81
+ return num(p, sig=sig, signed=signed) + "%"
82
+
83
+
84
+ def decimals(err: float) -> int:
85
+ """Decimal places that show an uncertainty at 1 significant figure, or 2 when its first
86
+ digit is 1 or 2 (0.03 → 2, 0.012 → 3, 23 → 0, 230 → −1)."""
87
+ if err <= 0 or not math.isfinite(err):
88
+ raise ValueError(f"decimals needs a positive uncertainty, got {err!r}")
89
+ mag = math.floor(math.log10(err))
90
+ return (1 if int(err / 10**mag + 1e-9) <= 2 else 0) - mag
91
+
92
+
93
+ def resolving(values: list[float], width: float, *, tol: float = 0.03) -> int:
94
+ """The fewest decimal places (negative rounds to tens, hundreds...) at which rounding moves
95
+ none of ``values`` by more than ``tol`` × ``width``: 0.031 within 0.012 to 0.050 → 3,
96
+ 0.08 within 0.05 to 0.11 → 2, 1.2 within −0.6 to 3.0 → 1. A zero ``width`` falls back to the
97
+ largest magnitude, so equal values still get a sensible place."""
98
+ if not width > 0:
99
+ width = max((abs(v) for v in values), default=0.0) or 1.0
100
+ allowed = tol * width * (1 + 1e-9)
101
+ dec = -math.floor(math.log10(width)) - 1
102
+ while dec < 15 and any(abs(round(v, dec) - v) > allowed for v in values):
103
+ dec += 1
104
+ return dec
105
+
106
+
107
+ def places(s: str) -> int | None:
108
+ """Decimal places shown by a formatted number (``"0.420 ms"`` → 3, ``"1,200"`` → 0); None
109
+ when it is in scientific notation or holds no number."""
110
+ m = _FIRST.search(s)
111
+ if m is None or m[3]:
112
+ return None
113
+ return len(m[2]) - 1 if m[2] else 0
114
+
115
+
116
+ _FIRST = re.compile(r"(\d[\d,]*)(\.\d+)?(e[−-]?\d+)?")
117
+
118
+
119
+ def fixed(v: float, dec: int, *, signed: bool = False, unit: str | None = None) -> str:
120
+ """``v`` rounded to ``dec`` decimal places (negative ``dec`` rounds to tens, hundreds...),
121
+ keeping trailing zeros so numbers in one chip line up: fixed(0.1, 2) == "0.10", and zero
122
+ too: fixed(0, 2) == "0.00"."""
123
+ core = f"{round(abs(v), dec):,.{max(dec, 0)}f}"
124
+ if float(core.replace(",", "")) == 0:
125
+ return with_unit(core, unit)
126
+ return with_unit(_sign(v, core, signed), unit)
127
+
128
+
129
+ def pm(value: float, err: float, *, unit: str | None = None, signed: bool = False) -> str:
130
+ """``value ± err`` with ``err`` at the precision ``decimals`` gives and ``value`` rounded to
131
+ the same place: ``0.82 ± 0.03``."""
132
+ if err <= 0:
133
+ return num(value, signed=signed, unit=unit)
134
+ dec = decimals(err)
135
+ return with_unit(f"{fixed(value, dec, signed=signed)} ± {fixed(err, dec)}", unit)
mintchip/guide.py ADDED
@@ -0,0 +1,189 @@
1
+ """The agent guide: ``mintchip guide``, the Claude Code skill and ``llms.txt``.
2
+
3
+ Everything here is generated: the data-shape table from each kind's ``have`` and ``example``,
4
+ and every example's output by running the real command in-process, so the guide cannot drift
5
+ from the code. ``tests/test_guide.py`` keeps it under 6,000 characters and checks that the
6
+ committed ``skills/mintchip/SKILL.md`` and ``llms.txt`` match ``write()``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import shlex
13
+ from pathlib import Path
14
+
15
+ from .directives import example_call, render
16
+ from .spec import catalog
17
+
18
+ __all__ = [
19
+ "LIMIT",
20
+ "SKILL_DESCRIPTION",
21
+ "agents_snippet",
22
+ "guide_text",
23
+ "llms_text",
24
+ "skill_text",
25
+ "write",
26
+ ]
27
+
28
+ LIMIT = 6000 # characters; the guide is meant to be pasted into a system prompt
29
+
30
+ SKILL_DESCRIPTION = (
31
+ "Turn numbers with shape into word-sized graphics (sparklines, confidence intervals, "
32
+ "before/after deltas, pass/fail strips, distributions, shares, shared-scale tables) in text, "
33
+ "Markdown or HTML with one zero-dep shell command. Use when reporting results, benchmarks, "
34
+ "test runs, timings, diffs, or comparisons. Do NOT use for routine code edits, bug fixes, "
35
+ "refactoring, stack traces, or 1-3 bare scalars with no shape. Reach for mintfig when you "
36
+ "need full multi-panel plots, 2D relationships, publication plates, or Matplotlib auditing."
37
+ )
38
+
39
+ _ROWS = [
40
+ {"model": "retrieval", "acc": 0.82, "lift": [0.08, 0.05, 0.11], "loss": [1.84, 0.96, 0.42]},
41
+ {"model": "warmup", "acc": 0.75, "lift": [0.01, -0.02, 0.04], "loss": [1.8, 1.3, 0.7]},
42
+ {"model": "baseline", "acc": 0.74, "lift": None, "loss": [1.85, 1.4, 0.78]},
43
+ ]
44
+ _TABLE_ARGS = [
45
+ "--col", "model", "--col", "acc:bar", "--col", "lift:ci", "--col", "loss:spark",
46
+ "--set", "lift.level=0.95", "--sort", "acc",
47
+ ] # fmt: skip
48
+
49
+
50
+ def _run(argv: list[str], stdin: str | None = None) -> str:
51
+ from .cli import run
52
+
53
+ code, out, err = run(argv, stdin)
54
+ if code != 0 or err:
55
+ raise RuntimeError(f"guide example failed: mintchip {' '.join(argv)}\n{err}")
56
+ return out.rstrip("\n")
57
+
58
+
59
+ def _directive(kind: str) -> str:
60
+ return example_call(kind, "directive", omit=("label",))
61
+
62
+
63
+ def _shape_table() -> str:
64
+ lines = ["| You have | Directive | Prints |", "|---|---|---|"]
65
+ for entry in catalog():
66
+ d = _directive(entry["name"])
67
+ lines.append(f"| {entry['have']} | `{d}` | `{render(d)[0]}` |")
68
+ lines.append("| Three or more of the same thing | `mintchip table` (below) | |")
69
+ return "\n".join(lines)
70
+
71
+
72
+ def guide_text() -> str:
73
+ """The agent cheat-sheet printed by ``mintchip guide`` (Markdown, under ``LIMIT``)."""
74
+ one = shlex.split(example_call("ci"))[1:]
75
+ spark, ci = _directive("spark"), "{{ci 0.08 0.05:0.11 level=0.95}}"
76
+ message = f"Val loss settled at {spark}, and retrieval lifted accuracy by {ci}."
77
+ rows = "[\n" + ",\n".join(json.dumps(r) for r in _ROWS) + "\n]"
78
+ table_cmd = " ".join(shlex.quote(t) for t in ["mintchip", "table", "-", *_TABLE_ARGS])
79
+ return f"""\
80
+ # mintchip: numbers with shape, from one shell command
81
+
82
+ mintchip prints numbers as word-sized graphics for a sentence or a table cell, as text,
83
+ Markdown or HTML. The number comes first, so the sentence reads even without the glyph.
84
+
85
+ ## When to use a chip
86
+ - Give numbers with shape a chip (trend, interval, before/after, pass/fail, share) right after
87
+ the words it supports.
88
+ - A number with no shape is just a number: write 0.82. One chip per sentence is normal;
89
+ two is the ceiling. Three or more comparable values make a table (`mintchip table`).
90
+ - Do NOT use for routine code edits, bug fixes, refactoring, stack traces, or 1–3 bare scalars
91
+ with no shape.
92
+ - Use `mintchip` for inline chips & zero-dep terminal/Markdown/PR tables; reach for `mintfig`
93
+ for multi-panel plots, 2D relationships, publication plates, or Matplotlib auditing.
94
+
95
+ ## Pick a chip by what you have
96
+ {_shape_table()}
97
+
98
+ Reading the glyphs: a spark's number is its latest value (the full form adds the range);
99
+ strip `█` pass, `▄` warn, `×` fail, `·` skip; ci `●` when the interval excludes the reference
100
+ `│`, `○` when it crosses it.
101
+
102
+ ## One grammar for commands and directives
103
+ `mintchip spark 1.84 0.96 0.42 --band 0.38:0.48` is the directive
104
+ `{{{{spark 1.84 0.96 0.42 band=0.38:0.48}}}}`. Values fill the chip's slots in order; options
105
+ are `--name value` on the command line and `name=value` in a directive.
106
+ - numbers: spaces or commas; `null` or `nan` is a gap; negatives work: `-0.2`
107
+ - ranges: `lo:hi`, e.g. `0.05:0.11`
108
+ - named parts: `name=value` (`"signed up"=520`); spans: `name=start:end`
109
+ - results: `pass warn fail skip`, or `true false null`
110
+ - flags: `--higher-is-better` / `--no-higher-is-better`; `higher_is_better=true` in a directive
111
+ - `label` and `unit` work on most chips; quote text with spaces: `--label 'Val loss'`,
112
+ `label="Val loss"`, `unit=ms`
113
+ - all options of a chip: `mintchip KIND --help`
114
+
115
+ ## 1. One chip
116
+ ```
117
+ $ {example_call("ci")}
118
+ {_run(one)}
119
+ ```
120
+
121
+ ## 2. A whole message: render
122
+ ```
123
+ $ mintchip render - <<'EOF'
124
+ {message}
125
+ EOF
126
+ {_run(["render", "-"], message + chr(10))}
127
+ ```
128
+ Text outside `{{{{…}}}}` is copied unchanged (`\\{{{{` is a literal `{{{{`). A file works in
129
+ place of `-`. `--check` also flags too many chips per sentence.
130
+
131
+ ## 3. A table
132
+ ```
133
+ $ {table_cmd} <<'EOF'
134
+ {rows}
135
+ EOF
136
+ {_run(["table", "-", *_TABLE_ARGS], rows)}
137
+ ```
138
+ Rows: a JSON list of objects or CSV, from a file or `-`. `--col KEY[:KIND[:HEADER]]` in order;
139
+ KIND is any chip name above or `text` (left out: inferred). A `ci` cell is `[estimate, low,
140
+ high]`; each chip column shares one scale. `--set KEY.OPTION=VALUE` applies to a whole column,
141
+ e.g. `--set KEY.unit=s`. `--sort KEY` (largest first, text A to Z; `--asc` or `--desc` to
142
+ choose), `--limit N`.
143
+
144
+ ## Output & errors
145
+ `--format text|md|ansi|html|svg|json`, `--ascii`, `--compact`. stdout holds only the result.
146
+ Errors go to stderr (`mintchip: error: …` + `fix:`, exit 2). Warnings (`mintchip: warning: …`,
147
+ exit 0; exit 1 with `--strict`) flag distortions like clipped outliers.
148
+
149
+ More: `mintchip from`, `mintchip diff`, `mintchip doctor`, `mintchip skill`, `mintchip schema`,
150
+ `mintchip catalog`, or `python -m mintchip`.
151
+ """
152
+
153
+
154
+ def agents_snippet() -> str:
155
+ """A short block for a user's own AGENTS.md or CLAUDE.md."""
156
+ return """\
157
+ ## Reporting numbers with mintchip
158
+ When you report numbers (results, benchmarks, test runs, timings, comparisons), give the ones
159
+ with a shape a word-sized chip. Run `mintchip guide` once for the syntax. Then write the
160
+ message with `{{kind …}}` directives, e.g. `{{spark 1.84 0.96 0.42}}` or
161
+ `{{ci 0.08 0.05:0.11 level=0.95}}`, and pipe it through `mintchip render` (`--format md` for
162
+ Markdown); put three or more comparable rows in `mintchip table`. Keep one chip per sentence,
163
+ two at most, and leave numbers with no shape as plain numbers.
164
+ """
165
+
166
+
167
+ def skill_text() -> str:
168
+ """``skills/mintchip/SKILL.md``: the guide with Claude Code skill frontmatter."""
169
+ desc = json.dumps(SKILL_DESCRIPTION, ensure_ascii=False) # a valid YAML quoted scalar
170
+ return f"---\nname: mintchip\ndescription: {desc}\n---\n\n{guide_text()}"
171
+
172
+
173
+ def llms_text() -> str:
174
+ """``llms.txt``: a title, a one-line summary, then the guide."""
175
+ body = guide_text().split("\n", 1)[1].lstrip("\n")
176
+ return f"# mintchip\n\n> {SKILL_DESCRIPTION}\n\n{body}"
177
+
178
+
179
+ def write(dest: str | Path) -> list[Path]:
180
+ """Write ``dest/skills/mintchip/SKILL.md`` and ``dest/llms.txt``; returns the paths."""
181
+ root = Path(dest)
182
+ files = {
183
+ root / "skills" / "mintchip" / "SKILL.md": skill_text(),
184
+ root / "llms.txt": llms_text(),
185
+ }
186
+ for path, text in files.items():
187
+ path.parent.mkdir(parents=True, exist_ok=True)
188
+ path.write_text(text, encoding="utf-8")
189
+ return list(files)