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/skill.py ADDED
@@ -0,0 +1,332 @@
1
+ """Bundled agent skill and project instruction installers for mintchip.
2
+
3
+ Generates ``SKILL.md`` and marker-wrapped ``AGENTS.md`` / ``CLAUDE.md`` snippets directly
4
+ from :mod:`mintchip.guide`, so installed skills never drift from the code and work cleanly
5
+ from an installed wheel without requiring repository-root ``skills/`` files.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from collections.abc import Sequence
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from . import guide
17
+ from .spec import ChipError
18
+
19
+ __all__ = [
20
+ "GLOBAL_TARGETS",
21
+ "MARKER_END",
22
+ "MARKER_START",
23
+ "VALID_TARGETS",
24
+ "add_skill_parser",
25
+ "cmd_skill",
26
+ "detect_installed_agents",
27
+ "get_agents_snippet",
28
+ "get_skill_markdown",
29
+ "install_skill",
30
+ ]
31
+
32
+ VALID_TARGETS: tuple[str, ...] = (
33
+ "claude",
34
+ "antigravity",
35
+ "cursor",
36
+ "codex",
37
+ "agents-md",
38
+ "claude-md",
39
+ )
40
+
41
+ GLOBAL_TARGETS: tuple[str, ...] = (
42
+ "claude",
43
+ "antigravity",
44
+ "cursor",
45
+ "codex",
46
+ )
47
+
48
+ _DEFAULT_LOCAL_TARGETS: tuple[str, ...] = ("claude", "antigravity", "agents-md")
49
+ _DEFAULT_GLOBAL_FALLBACK: tuple[str, ...] = ("claude", "antigravity")
50
+
51
+ _AGENT_HOME_DIRS: tuple[tuple[str, str], ...] = (
52
+ ("claude", ".claude"),
53
+ ("codex", ".codex"),
54
+ ("antigravity", ".gemini"),
55
+ ("cursor", ".cursor"),
56
+ )
57
+
58
+ MARKER_START: str = "<!-- mintchip:start -->"
59
+ MARKER_END: str = "<!-- mintchip:end -->"
60
+
61
+
62
+ def detect_installed_agents(home: str | Path | None = None) -> list[str]:
63
+ """Return agent targets whose standard home directory exists under ``home``.
64
+
65
+ Checks ``~/.claude`` (``"claude"``), ``~/.codex`` (``"codex"``),
66
+ ``~/.gemini`` (``"antigravity"``), and ``~/.cursor`` (``"cursor"``).
67
+ """
68
+ home_path = Path(home).expanduser() if home is not None else Path.home()
69
+ detected: list[str] = []
70
+ for target, dirname in _AGENT_HOME_DIRS:
71
+ if (home_path / dirname).is_dir():
72
+ detected.append(target)
73
+ return detected
74
+
75
+
76
+ def get_skill_markdown() -> str:
77
+ """Return the generated ``SKILL.md`` directly from :func:`mintchip.guide.skill_text`."""
78
+ return guide.skill_text()
79
+
80
+
81
+ def get_agents_snippet() -> str:
82
+ """Return the marker-wrapped ``AGENTS.md`` / ``CLAUDE.md`` snippet."""
83
+ body = guide.agents_snippet().strip()
84
+ return f"{MARKER_START}\n{body}\n{MARKER_END}\n"
85
+
86
+
87
+ def _strip_yaml_frontmatter(markdown: str) -> str:
88
+ """Remove leading YAML frontmatter block if present."""
89
+ if not markdown.startswith("---\n"):
90
+ return markdown
91
+ end = markdown.find("\n---\n", 4)
92
+ if end == -1:
93
+ return markdown
94
+ return markdown[end + len("\n---\n") :].lstrip("\n")
95
+
96
+
97
+ def _build_cursor_mdc(skill_md: str) -> str:
98
+ """Wrap the skill body with valid Cursor ``.mdc`` rule frontmatter."""
99
+ body = _strip_yaml_frontmatter(skill_md).rstrip() + "\n"
100
+ desc = json.dumps(guide.SKILL_DESCRIPTION, ensure_ascii=False)
101
+ frontmatter = (
102
+ "---\n"
103
+ f"description: {desc}\n"
104
+ "globs:\n"
105
+ ' - "**/*.py"\n'
106
+ ' - "**/*.md"\n'
107
+ ' - "**/*.csv"\n'
108
+ ' - "**/*.json"\n'
109
+ "alwaysApply: false\n"
110
+ "---\n\n"
111
+ )
112
+ return frontmatter + body
113
+
114
+
115
+ def _upsert_marked_block(path: Path, snippet: str) -> Path:
116
+ """Idempotently insert or replace the marker-wrapped snippet inside ``path``."""
117
+ block = snippet.strip()
118
+ if MARKER_START not in block or MARKER_END not in block:
119
+ block = f"{MARKER_START}\n{block}\n{MARKER_END}"
120
+
121
+ path.parent.mkdir(parents=True, exist_ok=True)
122
+ if not path.exists():
123
+ path.write_text(block + "\n", encoding="utf-8")
124
+ return path
125
+
126
+ existing = path.read_text(encoding="utf-8")
127
+ start_idx = existing.find(MARKER_START)
128
+ end_idx = existing.find(MARKER_END, start_idx + len(MARKER_START)) if start_idx != -1 else -1
129
+
130
+ if start_idx != -1 and end_idx != -1:
131
+ updated = existing[:start_idx] + block + existing[end_idx + len(MARKER_END) :]
132
+ elif not existing.strip():
133
+ updated = block + "\n"
134
+ else:
135
+ sep = (
136
+ "\n\n"
137
+ if not existing.endswith("\n")
138
+ else ("\n" if not existing.endswith("\n\n") else "")
139
+ )
140
+ updated = existing + sep + block + "\n"
141
+
142
+ path.write_text(updated, encoding="utf-8")
143
+ return path
144
+
145
+
146
+ def _normalize_targets(
147
+ targets: Sequence[str] | None,
148
+ *,
149
+ global_install: bool,
150
+ home_path: Path,
151
+ ) -> list[str]:
152
+ if targets is None:
153
+ if global_install:
154
+ detected = detect_installed_agents(home_path)
155
+ return detected if detected else list(_DEFAULT_GLOBAL_FALLBACK)
156
+ return list(_DEFAULT_LOCAL_TARGETS)
157
+
158
+ expanded: list[str] = []
159
+ for raw in targets:
160
+ for part in raw.split(","):
161
+ key = part.strip().lower()
162
+ if not key:
163
+ continue
164
+ if key == "all":
165
+ expanded.extend(GLOBAL_TARGETS if global_install else VALID_TARGETS)
166
+ else:
167
+ expanded.append(key)
168
+
169
+ if not expanded:
170
+ return _normalize_targets(None, global_install=global_install, home_path=home_path)
171
+
172
+ normalized: list[str] = []
173
+ seen: set[str] = set()
174
+ for key in expanded:
175
+ if key not in VALID_TARGETS:
176
+ valid = ", ".join((*VALID_TARGETS, "all"))
177
+ raise ChipError(
178
+ f"mintchip skill: unknown install target {key!r}.",
179
+ fix_hint=f"Use --target with one of: {valid}.",
180
+ )
181
+ if key not in seen:
182
+ normalized.append(key)
183
+ seen.add(key)
184
+ return normalized
185
+
186
+
187
+ def install_skill(
188
+ root: str | Path = ".",
189
+ *,
190
+ targets: Sequence[str] | None = None,
191
+ global_install: bool = False,
192
+ home: str | Path | None = None,
193
+ ) -> list[Path]:
194
+ """Install mintchip agent skills and/or project instruction snippets.
195
+
196
+ When ``targets`` is omitted:
197
+ - Project-local installs default to ``("claude", "antigravity", "agents-md")``.
198
+ - Global installs auto-detect ``~/.claude``, ``~/.codex``, ``~/.gemini``,
199
+ and ``~/.cursor``, falling back to ``("claude", "antigravity")``.
200
+ """
201
+ home_path = Path(home).expanduser() if home is not None else Path.home()
202
+ normalized = _normalize_targets(targets, global_install=global_install, home_path=home_path)
203
+
204
+ root_path = Path(root)
205
+ skill_md = get_skill_markdown()
206
+ snippet = get_agents_snippet()
207
+ written: list[Path] = []
208
+
209
+ def _write_skill_file(dest: Path) -> Path:
210
+ dest.parent.mkdir(parents=True, exist_ok=True)
211
+ dest.write_text(skill_md, encoding="utf-8")
212
+ return dest
213
+
214
+ for target in normalized:
215
+ if target == "claude":
216
+ base = home_path if global_install else root_path
217
+ written.append(_write_skill_file(base / ".claude" / "skills" / "mintchip" / "SKILL.md"))
218
+ elif target == "antigravity":
219
+ if global_install:
220
+ dest = home_path / ".gemini" / "config" / "skills" / "mintchip" / "SKILL.md"
221
+ else:
222
+ dest = root_path / ".agents" / "skills" / "mintchip" / "SKILL.md"
223
+ written.append(_write_skill_file(dest))
224
+ elif target == "cursor":
225
+ base = home_path if global_install else root_path
226
+ dest = base / ".cursor" / "rules" / "mintchip.mdc"
227
+ dest.parent.mkdir(parents=True, exist_ok=True)
228
+ dest.write_text(_build_cursor_mdc(skill_md), encoding="utf-8")
229
+ written.append(dest)
230
+ elif target == "codex":
231
+ base = home_path if global_install else root_path
232
+ written.append(_write_skill_file(base / ".codex" / "skills" / "mintchip" / "SKILL.md"))
233
+ elif target == "agents-md":
234
+ dest = (
235
+ (home_path / ".codex" / "AGENTS.md")
236
+ if global_install
237
+ else (root_path / "AGENTS.md")
238
+ )
239
+ written.append(_upsert_marked_block(dest, snippet))
240
+ elif target == "claude-md":
241
+ dest = (
242
+ (home_path / ".claude" / "CLAUDE.md")
243
+ if global_install
244
+ else (root_path / "CLAUDE.md")
245
+ )
246
+ written.append(_upsert_marked_block(dest, snippet))
247
+
248
+ return written
249
+
250
+
251
+ def add_skill_parser(sub: Any, formatter_class: Any) -> argparse.ArgumentParser:
252
+ """Register the ``mintchip skill`` subcommand."""
253
+ p = sub.add_parser(
254
+ "skill",
255
+ help="Print or install the mintchip agent skill for Claude, Antigravity, Cursor, or Codex.",
256
+ description=(
257
+ "Print the generated SKILL.md (default / --print) or install it into local project\n"
258
+ "or user-home agent directories (--install). Upserts AGENTS.md / CLAUDE.md blocks\n"
259
+ "idempotently between <!-- mintchip:start --> and <!-- mintchip:end -->."
260
+ ),
261
+ formatter_class=formatter_class,
262
+ )
263
+ p.add_argument(
264
+ "--install",
265
+ action="store_true",
266
+ help="Install skill files and/or AGENTS.md/CLAUDE.md snippets.",
267
+ )
268
+ p.add_argument(
269
+ "--print",
270
+ dest="print_skill",
271
+ action="store_true",
272
+ help="Print the generated SKILL.md to stdout (default when --install is not given).",
273
+ )
274
+ p.add_argument(
275
+ "--snippet",
276
+ action="store_true",
277
+ help="Print the marker-wrapped AGENTS.md / CLAUDE.md snippet.",
278
+ )
279
+ p.add_argument(
280
+ "--global",
281
+ dest="global_install",
282
+ action="store_true",
283
+ help="Install into user-home agent directories (~/.claude, ~/.codex, ~/.gemini, ~/.cursor).",
284
+ )
285
+ p.add_argument(
286
+ "--root",
287
+ default=".",
288
+ metavar="DIR",
289
+ help="Target project root directory for local installs (default: .).",
290
+ )
291
+ p.add_argument(
292
+ "--home",
293
+ default=None,
294
+ metavar="DIR",
295
+ help="Override home directory for --global installs.",
296
+ )
297
+ p.add_argument(
298
+ "--target",
299
+ action="append",
300
+ default=None,
301
+ metavar="TARGET",
302
+ help=(
303
+ "Install target (repeatable or comma-separated): "
304
+ "claude, antigravity, cursor, codex, agents-md, claude-md, or all."
305
+ ),
306
+ )
307
+ p.set_defaults(func=cmd_skill, _parser=p)
308
+ return p
309
+
310
+
311
+ def cmd_skill(args: argparse.Namespace) -> int:
312
+ """Execute ``mintchip skill``."""
313
+ from .cli import _error, _out
314
+
315
+ if args.snippet:
316
+ _out(get_agents_snippet())
317
+ return 0
318
+ if args.install:
319
+ try:
320
+ written = install_skill(
321
+ root=args.root,
322
+ targets=args.target,
323
+ global_install=args.global_install,
324
+ home=args.home,
325
+ )
326
+ except ChipError as e:
327
+ return _error(e)
328
+ for path in written:
329
+ _out(f"Installed: {path}")
330
+ return 0
331
+ _out(get_skill_markdown())
332
+ return 0