-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskill_builder.py
More file actions
7217 lines (6159 loc) · 308 KB
/
Copy pathskill_builder.py
File metadata and controls
7217 lines (6159 loc) · 308 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""GENERATED — DO NOT EDIT. The all-in-one skill_builder tool.
Rebuild after editing the source components with: python builder_components/_assemble.py
(or `python skill_builder.py --rebuild`). Every component's verbatim source is embedded in the _SRC
dict below, each under a `# ===MODULE` banner; the bootstrap registers each as a builder_components.*
module (in dependency order) and runs the CLI. The editable source of truth is the sibling
builder_components/ package; each component is also usable on its own via
`python -m builder_components.<module>`.
"""
import os as _os
import sys as _sys
import types as _types
_PACKAGES = {"builder_components", "builder_components.util"}
_ORDER = [
'builder_components',
'builder_components.util',
'builder_components.htmlmd',
'builder_components.index',
'builder_components.readme',
'builder_components.recontext_core',
'builder_components.util.config',
'builder_components.util.frontmatter',
'builder_components.util.repo_paths',
'builder_components.util.text_io',
'builder_components.finalize',
'builder_components.ingest',
'builder_components.policy_engine',
'builder_components.recontext',
'builder_components.recontext_subagent',
'builder_components.validate',
'builder_components.corpus',
'builder_components.policy_cmd',
'builder_components.packing',
'builder_components.build',
'builder_components.maintain',
'builder_components.split_engine',
'builder_components.lint',
'builder_components.split_cmd',
'builder_components.cli',
]
# Where the editable component package lives, beside this file. Each embedded module's __file__ is set
# to its real source path so the few load-time `__file__` users (recontext's scripts/ locator, readme's
# template locator) resolve exactly as they do when run as the package. Module IMPORTS still resolve
# purely from the embedded _SRC (no disk dependency); only those data-file lookups touch disk.
_PKG = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), "builder_components")
def _modfile(name):
"""Real on-disk source path for an embedded module (used as its __file__)."""
rel = name.split(".")[1:]
if name in _PACKAGES:
return _os.path.join(_PKG, *rel, "__init__.py")
return _os.path.join(_PKG, *rel) + ".py"
def _bootstrap():
"""Register every embedded component as a real module (in _ORDER) and exec its source there."""
for name in _ORDER:
mod = _types.ModuleType(name)
mod.__file__ = _modfile(name)
if name in _PACKAGES:
mod.__path__ = []
mod.__package__ = name
else:
mod.__package__ = name.rpartition(".")[0]
_sys.modules[name] = mod
exec(compile(_SRC[name], mod.__file__, "exec"), mod.__dict__)
parent, _, leaf = name.rpartition(".")
if parent and parent in _sys.modules:
setattr(_sys.modules[parent], leaf, mod)
_SRC = {}
# ===MODULE builder_components===
_SRC['builder_components'] = """
\"\"\"builder_components — the skill-drafting tooling package.
One importable home for the skill build/maintain pipeline (`skill_builder`), the package
validator, the skill-invocation-policy manager, and the recontextualization engine + locked
writer. The loose scripts in `scripts/` are thin launchers that delegate here so every
documented invocation path (and the VALIDATOR path baked into built skills' SKILL.md) keeps
working. Shared, single-concern helpers live under `builder_components.util`.
Stdlib only; no third-party dependencies.
\"\"\"
"""
# ===MODULE builder_components.util===
_SRC['builder_components.util'] = """
\"\"\"builder_components.util — single-concern helpers shared across the tooling modules.
Each module here holds one canonical copy of a helper that was previously duplicated across the
standalone scripts (frontmatter parsing, project-root resolution, the LF-forced file writer).
Splitting the monoliths into submodules turns these former in-file helpers into genuinely shared
utilities, so they live here once and every consumer imports them.
\"\"\"
"""
# ===MODULE builder_components.htmlmd===
_SRC['builder_components.htmlmd'] = """
\"\"\"HTML -> Markdown conversion (was the htmlmd.py section of skill_builder.py).\"\"\"
from __future__ import annotations
import html
import re
from html import unescape
from html.parser import HTMLParser
from urllib.parse import urljoin
# ==============================================================================
# SHARED — HTML -> Markdown (was htmlmd.py)
# ==============================================================================
_SKIP = {"script", "style", "head", "nav", "header", "footer", "aside", "noscript", "svg", "button", "form"}
_BLOCK = {"p", "div", "section", "article", "ul", "ol", "li", "pre", "blockquote", "table",
"tr", "thead", "tbody", "h1", "h2", "h3", "h4", "h5", "h6", "hr"}
class _MD(HTMLParser):
\"\"\"Streaming HTML parser that emits Markdown, collecting headings and tables as it goes.\"\"\"
def __init__(self, base_url: str = ""):
\"\"\"Initialize parser state; base_url resolves relative link/image hrefs.\"\"\"
super().__init__(convert_charrefs=True)
self.base = base_url
self.out: list[str] = []
self.skip_depth = 0
self.pre_depth = 0 # inside <pre> (code block)
self.code_inline = 0 # inside inline <code> (not in pre)
self.pre_lang = ""
self.list_stack: list[str] = [] # 'ul'/'ol' with counters
self.ol_counters: list[int] = []
self.href: str | None = None
self.link_text: list[str] = []
self.in_table = False
self.row: list[str] | None = None
self.cell: list[str] | None = None
self.table_rows: list[list[str]] = []
self.table_header_done = False
self.headings: list[tuple[int, str, str]] = [] # (level, text, id) for callers
self._cur_id = ""
self._cur_h: list | None = None
self._a_class = "" # class of the anchor currently open (to drop ¶ headerlinks)
# ---- helpers ----
def _emit(self, s: str):
\"\"\"Append text to the current sink: open table cell, open link text, or main output.\"\"\"
if self.cell is not None:
self.cell.append(s)
elif self.link_text and self.href is not None:
self.link_text.append(s)
else:
self.out.append(s)
def _nl(self, n=1):
\"\"\"Emit n newlines to the main output, but only when not inside a cell or link text.\"\"\"
if self.cell is None and not (self.link_text and self.href is not None):
self.out.append("\\n" * n)
# ---- tags ----
def handle_starttag(self, tag, attrs):
\"\"\"Translate an opening HTML tag into its Markdown prefix and update parser state.\"\"\"
a = dict(attrs)
if self.skip_depth or tag in _SKIP:
if tag in _SKIP:
self.skip_depth += 1
return
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
lvl = int(tag[1])
self._nl(2)
self._emit("#" * lvl + " ")
self._cur_h = [lvl, [], a.get("id", "")]
self._cur_id = a.get("id", "")
elif tag == "p":
self._nl(2)
elif tag == "br":
self._emit(" \\n")
elif tag == "hr":
self._nl(2); self._emit("---"); self._nl(2)
elif tag == "pre":
if not self.pre_lang and "rust" in a.get("class", ""):
self.pre_lang = "rust" # rustdoc: <pre class="rust item-decl">
self.pre_depth += 1
self._nl(2); self._emit("```" + self.pre_lang); self._nl(1)
elif tag == "code":
cls = a.get("class", "")
m = re.search(r"language-([\\w+-]+)", cls) or re.search(r"\\b(rust|python|bash|sh|json|toml|c|cpp|js|ts|html)\\b", cls)
if self.pre_depth:
pass # text captured verbatim
else:
self.code_inline += 1
self._emit("`")
if m and self.pre_depth:
self.pre_lang = m.group(1)
elif tag in ("strong", "b"):
self._emit("**")
elif tag in ("em", "i"):
self._emit("*")
elif tag == "a":
if not self.pre_depth: # inside a code fence, anchors emit their text only (clean signatures)
self.href = a.get("href", "")
self._a_class = a.get("class", "") or ""
self.link_text = [""]
elif tag == "dt": # definition-list term (Sphinx API signature) -> own line
self._nl(2)
elif tag == "dd": # definition body (the description) -> indented new line
self._nl(1)
elif tag == "div": # Sphinx code wrapper carries the language: highlight-<lang>
cls = a.get("class", "")
m = re.search(r"highlight-(\\w+)", cls)
if m:
lang = m.group(1).lower()
self.pre_lang = {"default": "python", "python3": "python", "ipython3": "python",
"pycon": "pycon", "pycon3": "pycon", "py": "python"}.get(lang, lang)
elif tag == "ul":
self.list_stack.append("ul"); self.ol_counters.append(0)
elif tag == "ol":
self.list_stack.append("ol"); self.ol_counters.append(0)
elif tag == "li":
self._nl(1)
indent = " " * (len(self.list_stack) - 1)
if self.list_stack and self.list_stack[-1] == "ol":
self.ol_counters[-1] += 1
self._emit(f"{indent}{self.ol_counters[-1]}. ")
else:
self._emit(f"{indent}- ")
elif tag == "blockquote":
self._nl(2); self._emit("> ")
elif tag == "table":
self.in_table = True; self.table_rows = []; self.table_header_done = False
elif tag == "tr":
self.row = []
elif tag in ("td", "th"):
self.cell = []
elif tag == "img":
alt = a.get("alt", "").strip()
src = a.get("src", "")
cap = alt or re.sub(r"[-_]+", " ", re.sub(r"\\.[a-z0-9]+$", "", src.rsplit("/", 1)[-1], flags=re.I))
self._emit(f"(Figure: {cap})")
def handle_endtag(self, tag):
\"\"\"Translate a closing HTML tag into its Markdown suffix and finalize state (links, tables).\"\"\"
if tag in _SKIP and self.skip_depth:
self.skip_depth -= 1
return
if self.skip_depth:
return
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
if self._cur_h:
txt = "".join(self._cur_h[1]).replace("", "").strip()
self.headings.append((self._cur_h[0], txt, self._cur_h[2]))
self._cur_h = None
self._nl(2)
elif tag == "pre":
if self.pre_depth:
self.pre_depth -= 1
self._nl(1); self._emit("```"); self._nl(2); self.pre_lang = ""
elif tag == "code" and not self.pre_depth and self.code_inline:
self.code_inline -= 1; self._emit("`")
elif tag in ("strong", "b"):
self._emit("**")
elif tag in ("em", "i"):
self._emit("*")
elif tag == "a":
if self.href is None: # no open link (e.g. an anchor inside <pre>): text already emitted verbatim
self._a_class = ""; self.link_text = []
else:
text = "".join(self.link_text).strip()
href = self.href; acls = self._a_class
self.href = None; self.link_text = []; self._a_class = ""
if "headerlink" in acls or text in ("¶", "#"):
pass # Sphinx permalink pilcrow (¶) — drop it
elif href and not href.startswith("#") and text:
url = urljoin(self.base, href) if self.base else href
self._emit(f"[{text}]({url})")
else:
self._emit(text)
elif tag in ("dt", "dd"):
self._nl(1)
elif tag in ("ul", "ol"):
if self.list_stack:
self.list_stack.pop(); self.ol_counters.pop()
self._nl(1)
elif tag in ("p", "blockquote"):
self._nl(2)
elif tag in ("td", "th"):
if self.row is not None and self.cell is not None:
self.row.append(" ".join("".join(self.cell).split()))
self.cell = None
elif tag == "tr":
if self.row is not None:
self.table_rows.append(self.row); self.row = None
elif tag == "table":
self._flush_table(); self.in_table = False
def handle_data(self, data):
\"\"\"Emit text content; verbatim inside <pre>, whitespace-collapsed elsewhere.\"\"\"
if self.skip_depth:
return
if self.pre_depth:
self._emit(data)
return
text = data
if self._cur_h is not None:
self._cur_h[1].append(text)
# collapse whitespace outside code/pre
collapsed = re.sub(r"\\s+", " ", text)
if collapsed:
self._emit(collapsed)
def _flush_table(self):
\"\"\"Render the collected table rows as a padded GFM Markdown table into the output.\"\"\"
rows = [r for r in self.table_rows if r]
if not rows:
return
self.out.append("\\n")
ncols = max(len(r) for r in rows)
head = rows[0] + [""] * (ncols - len(rows[0]))
self.out.append("| " + " | ".join(head) + " |\\n")
self.out.append("| " + " | ".join(["---"] * ncols) + " |\\n")
for r in rows[1:]:
r = r + [""] * (ncols - len(r))
self.out.append("| " + " | ".join(r) + " |\\n")
self.out.append("\\n")
def _balanced_div_inner(html: str, open_match: "re.Match") -> str:
\"\"\"Given a match for an opening <div ...>, return its inner HTML up to the matching </div>
(depth-balanced — handles the nested divs that a non-greedy regex would stop short on).\"\"\"
start = open_match.end()
depth = 1
for m in re.finditer(r"<div\\b|</div\\s*>", html[start:], re.IGNORECASE):
if m.group(0)[1] == "/":
depth -= 1
if depth == 0:
return html[start:start + m.start()]
else:
depth += 1
return html[start:]
def split_main(html: str) -> str:
\"\"\"Return the inner HTML of the doc body. Tries, in order: a div with role="main" (Sphinx),
<main>, <div id="content">, <body>, else the whole document.\"\"\"
m = re.search(r'<div\\b[^>]*\\brole=["\\']main["\\'][^>]*>', html, re.IGNORECASE)
if m:
return _balanced_div_inner(html, m)
for pat in (r"<main\\b[^>]*>(.*?)</main>", r'<div[^>]*id="content"[^>]*>(.*?)</div>\\s*</div>'):
m = re.search(pat, html, re.DOTALL | re.IGNORECASE)
if m:
return m.group(1)
m = re.search(r"<body\\b[^>]*>(.*?)</body>", html, re.DOTALL | re.IGNORECASE)
return m.group(1) if m else html
def html_to_md(html: str, base_url: str = "") -> tuple[str, list]:
\"\"\"Convert HTML to Markdown. Returns (markdown, headings) where headings is a list of
(level, text, id). Pass the doc body (use split_main first for full pages).\"\"\"
p = _MD(base_url)
p.feed(html)
md = "".join(p.out)
md = unescape(md)
md = md.replace("", "") # strip zero-width-space anchor artifacts
md = re.sub(r"(?m)^[ \\t]*#{1,6}[ \\t]*$", "", md) # drop headings left empty after that
md = re.sub(r"[ \\t]+\\n", "\\n", md)
md = re.sub(r"\\n{3,}", "\\n\\n", md)
return md.strip() + "\\n", p.headings
"""
# ===MODULE builder_components.index===
_SRC['builder_components.index'] = """
\"\"\"Build the cross-skill master index (was the index section of skill_builder.py).\"\"\"
from __future__ import annotations
import argparse
import collections
import json
import re
from pathlib import Path
# ==============================================================================
# INDEX — cross-skill master index (was build_master_index.py)
# ==============================================================================
_STOP = {"and", "the", "for", "with", "use", "using", "a", "an", "to", "of", "in", "on", "or"}
def parse_frontmatter(text: str) -> dict:
\"\"\"Line-based YAML-lite parse of the SKILL.md frontmatter: handles inline scalars, folded/literal
block scalars (`>-`, `>`, `|`), inline lists (`[a, b]`), and block lists (`- a`).\"\"\"
m = re.match(r"^---\\n(.*?)\\n---", text, re.DOTALL)
if not m:
return {}
lines = m.group(1).split("\\n")
fm, i = {}, 0
while i < len(lines):
km = re.match(r"^(\\w+):\\s?(.*)$", lines[i])
if not km:
i += 1
continue
key, val = km.group(1), km.group(2).strip()
if val in (">-", ">", ">+", "|", "|-", "|+"): # block scalar
buf, i = [], i + 1
while i < len(lines) and (lines[i].startswith((" ", "\\t")) or not lines[i].strip()):
buf.append(lines[i].strip()); i += 1
fm[key] = " ".join(x for x in buf if x)
continue
if val.startswith("[") and val.endswith("]"): # inline list
fm[key] = [x.strip().strip("'\\"") for x in val[1:-1].split(",") if x.strip()]
elif val == "": # maybe a block list follows
buf, j = [], i + 1
while j < len(lines) and re.match(r"^\\s+-\\s", lines[j]):
buf.append(re.match(r"^\\s+-\\s*(.+)", lines[j]).group(1).strip().strip("'\\"")); j += 1
fm[key] = buf if buf else ""
i = j if buf else i + 1
continue
else:
fm[key] = val.strip("'\\"")
i += 1
return fm
def derive_covers(skill: Path) -> list:
\"\"\"Entities a skill covers. Router → its sub-skill area names (clean). Flat → distinctive
topics.json keywords filtered to clean single-concept terms (drops concatenated slugs).\"\"\"
subs = [d.name for d in sorted(skill.iterdir()) if d.is_dir() and (d / "SKILL.md").is_file()]
if subs:
return subs
terms = collections.Counter()
tj = skill / "references" / "topics.json"
if tj.is_file():
try:
d = json.loads(tj.read_text(encoding="utf-8"))
except Exception:
d = {"topics": []}
for t in d.get("topics", []):
for kw in t.get("keywords", []):
k = str(kw).replace("_", "-").strip().lower()
if k and k not in _STOP and 3 <= len(k) <= 30 and k.count("-") <= 3 and not k.isdigit():
terms[k] += 1
return [t for t, _ in terms.most_common()]
def seed_covers_in_skill(skill: Path, covers: list) -> bool:
\"\"\"Insert/replace a `covers:` block list in a SKILL.md frontmatter, preserving the bespoke body
byte-for-byte. Idempotent: an existing covers: block (inline or list) is stripped and rewritten.\"\"\"
p = skill / "SKILL.md"
text = p.read_text(encoding="utf-8")
m = re.match(r"^(---\\n)(.*?)(\\n---\\n)", text, re.DOTALL)
if not m:
return False
lines = m.group(2).split("\\n")
out, i = [], 0
while i < len(lines):
cm = re.match(r"^covers:\\s*(\\S.*)?$", lines[i])
if cm:
i += 1
if not cm.group(1): # block list follows — drop its items too
while i < len(lines) and re.match(r"^\\s+-\\s", lines[i]):
i += 1
continue
out.append(lines[i]); i += 1
body = "\\n".join(out).rstrip("\\n")
block = "covers:\\n" + "\\n".join(f" - {c}" for c in covers)
p.write_text(m.group(1) + body + "\\n" + block + m.group(3) + text[m.end():],
encoding="utf-8", newline="\\n")
return True
def skill_info(skill: Path) -> dict:
\"\"\"Return a skill's {name, trigger, covers} summary, deriving covers when not in frontmatter and
using the description's first sentence (capped at 200 chars) as the trigger.\"\"\"
fm = parse_frontmatter((skill / "SKILL.md").read_text(encoding="utf-8")) if (skill / "SKILL.md").is_file() else {}
covers = fm.get("covers") or derive_covers(skill)
desc = fm.get("description", "")
trigger = re.split(r"(?<=[.])\\s", desc, 1)[0] if desc else ""
return {"name": fm.get("name", skill.name), "trigger": trigger[:200], "covers": covers}
def build_master_text(root: Path) -> str:
\"\"\"Build the master INDEX.md Markdown for a skills root: a skills catalog table, a related-skills
list, and an entity->skill map for entities shared by more than one skill.\"\"\"
skills = [d for d in sorted(root.iterdir()) if d.is_dir() and (d / "SKILL.md").is_file()]
infos = {d.name: skill_info(d) for d in skills}
# Catalog column shows the curated `covers:` (capped); the overlap map/related-skills use the
# fuller derived entity set, so genuine cross-references aren't hidden by the display cap.
ent2skill = collections.defaultdict(set)
for d in skills:
for e in derive_covers(d):
ent2skill[e].add(d.name)
related = collections.defaultdict(collections.Counter)
for e, owners in ent2skill.items():
if len(owners) > 1:
for a in owners:
for b in owners:
if a != b:
related[a][b] += 1
out = ["# Skills — Master Index", "",
"Catalog of every skill in this folder, with the entities/domains each covers and which "
"skills are related. A discovery / audit entry point — agents still route via each skill's "
"`description`. Generated by `skill-drafting/scripts/skill_builder.py index`.", "",
"## Skills", "", "| Skill | Covers (top) | Trigger |", "| --- | --- | --- |"]
for name in sorted(infos):
info = infos[name]
cov = ", ".join(info["covers"][:8]) + (" …" if len(info["covers"]) > 8 else "")
out.append(f"| [{name}]({name}/SKILL.md) | {cov} | {info['trigger']} |")
out += ["", "## Related skills", "", "Skills that share covered entities:", ""]
for name in sorted(related):
rel = ", ".join(f"{b} ({n})" for b, n in related[name].most_common(6))
out.append(f"- **{name}** ↔ {rel}")
if not related:
out.append("- (no shared entities across skills)")
shared = {e: sorted(s) for e, s in ent2skill.items() if len(s) > 1}
out += ["", "## Entity → skill map (shared)", "",
"Entities documented by more than one skill (where to look, and overlaps):", "",
"| Entity | Skills |", "| --- | --- |"]
for e in sorted(shared):
out.append(f"| {e} | {', '.join(shared[e])} |")
if not shared:
out.append("| (none) | |")
return "\\n".join(out).rstrip() + "\\n"
def cmd_index(argv=None) -> int:
\"\"\"Run the `index` subcommand: optionally seed each SKILL.md `covers:` frontmatter, then write the
master INDEX.md to the root (and any --mirror root). Returns an exit code.\"\"\"
ap = argparse.ArgumentParser(prog="skill_builder.py index")
ap.add_argument("root", help="a skills root, e.g. .agents/skills")
ap.add_argument("--mirror", help="also write the identical index to this skills root")
ap.add_argument("--seed-covers", action="store_true",
help="seed/refresh each SKILL.md `covers:` frontmatter from derived entities "
"(routers: all area names; flat: top 12). Also seeds --mirror for parity.")
ap.add_argument("--flat-cap", type=int, default=12, help="max covers entries for a flat skill")
args = ap.parse_args(argv)
root = Path(args.root)
if args.seed_covers:
roots = [root] + ([Path(args.mirror)] if args.mirror else [])
for d in sorted(root.iterdir()):
if not (d.is_dir() and (d / "SKILL.md").is_file()):
continue
is_router = any(c.is_dir() and (c / "SKILL.md").is_file() for c in d.iterdir())
covers = derive_covers(d)
if not is_router:
covers = covers[:args.flat_cap]
for r in roots:
if (r / d.name / "SKILL.md").is_file() and seed_covers_in_skill(r / d.name, covers):
print(f"seeded covers ({len(covers)}) -> {(r / d.name).as_posix()}/SKILL.md")
text = build_master_text(root)
(root / "INDEX.md").write_text(text, encoding="utf-8", newline="\\n")
print(f"wrote {root}/INDEX.md ({text.count(chr(10))} lines)")
if args.mirror:
mroot = Path(args.mirror)
(mroot / "INDEX.md").write_text(text, encoding="utf-8", newline="\\n")
print(f"wrote {mroot}/INDEX.md (mirror)")
return 0
def main(argv=None) -> int:
\"\"\"Standalone entry point for `python -m builder_components.index`; delegates to cmd_index.\"\"\"
return cmd_index(argv)
if __name__ == "__main__":
raise SystemExit(main())
"""
# ===MODULE builder_components.readme===
_SRC['builder_components.readme'] = """
\"\"\"Skill README scaffold/apply against the single-sourced standard (was the readme section).\"\"\"
from __future__ import annotations
import argparse
import re
from pathlib import Path
# ==============================================================================
# README STANDARD — scaffold + managed-region apply (single-sourced template)
# ==============================================================================
# A skill's public README.md is part constant boilerplate and part per-skill prose. The constant
# blocks — the "Part of Agent Kaizen" intro paragraph, the full %DEVROOT% "Use it" section, the
# idle-context policy section, and the License — are single-sourced in references/readme-standard.md
# and re-applied in place. Regions are located by MARKDOWN STRUCTURE, never by HTML-comment markers:
# the intro by its leading "Part of **[Agent Kaizen](" text, the others as whole `## ` sections (the
# heading through the line before the next `## `). Shippable READMEs therefore carry NO tool markers;
# everything outside the managed regions is author-owned and never rewritten. No README prose lives here.
def _readme_store_root() -> Path:
\"\"\"The skills store this package ships inside
(skills/skill-drafting/scripts/builder_components -> skills).\"\"\"
return Path(__file__).resolve().parents[3]
def _readme_default_template() -> Path:
\"\"\"Path to the single-sourced README standard (skill-drafting/references/readme-standard.md).\"\"\"
# this module lives in skills/skill-drafting/scripts/builder_components/; the standard is two
# levels up under skill-drafting/references/.
return Path(__file__).resolve().parents[2] / "references" / "readme-standard.md"
def _readme_skill_dirs(store: Path):
\"\"\"Return the skill directories (those containing a SKILL.md) directly under `store`, sorted.\"\"\"
return [d for d in sorted(store.iterdir()) if d.is_dir() and (d / "SKILL.md").is_file()]
def _readme_fill(text: str, *, skill=None, title=None, tagline=None, article=None) -> str:
\"\"\"Substitute the {{skill}}/{{title}}/{{tagline}}/{{article}} placeholders present in `text`.\"\"\"
for token, val in (("{{skill}}", skill), ("{{title}}", title),
("{{tagline}}", tagline), ("{{article}}", article)):
if val is not None:
text = text.replace(token, val)
return text
def _readme_strip(block):
\"\"\"Drop leading/trailing blank lines from a list of lines.\"\"\"
s, e = 0, len(block)
while s < e and block[s].strip() == "":
s += 1
while e > s and block[e - 1].strip() == "":
e -= 1
return block[s:e]
#: Managed regions, in document order. Each is located by markdown structure (see _readme_region_locate);
#: their canonical content is single-sourced from the template skeletons. `intro` and `license` are
#: Pattern A only; `use-it` and `idle-context` appear in every skill (presence-driven, so absent regions
#: are simply skipped).
_README_REGIONS = ("intro", "use-it", "idle-context", "license")
#: Heading prefix that locates each `## ` section region (intro is located separately, by leading text).
_README_HEADINGS = {
"use-it": "## Use it",
"idle-context": "## Reducing idle context cost",
"license": "## License",
}
def _readme_region_locate(lines, name):
\"\"\"Span (lo, hi) of a managed region located by markdown structure, or None if absent. `intro` is the
single 'Part of **[Agent Kaizen](' paragraph; the rest are whole `## ` sections (heading through the
line before the next `## `).\"\"\"
if name == "intro":
return _readme_anchor_intro(lines)
prefix = _README_HEADINGS.get(name)
return _readme_anchor_section(lines, prefix) if prefix else None
def _readme_strip_markers(lines):
\"\"\"Remove any leftover '<!-- ak:readme:* -->' marker lines and collapse the resulting blank runs to a
single blank, outside fenced code blocks. Idempotent; un-migrates READMEs that still carry markers.\"\"\"
marker = re.compile(r"<!-- ak:readme:.*(START|END) -->$")
kept, in_fence = [], False
for ln in lines:
s = ln.strip()
if s.startswith("```"):
in_fence = not in_fence
kept.append(ln)
continue
if not in_fence and marker.match(s):
continue
kept.append(ln)
out, in_fence = [], False
for ln in kept:
s = ln.strip()
if s.startswith("```"):
in_fence = not in_fence
out.append(ln)
continue
if not in_fence and s == "" and out and out[-1].strip() == "":
continue
out.append(ln)
return out
def _readme_parse_template(path: Path):
\"\"\"Return (regions, skeletons). The template holds the markerless Pattern A/B exemplar READMEs in its
>=4-backtick fenced blocks; regions[name] = canonical content lines, extracted from the Pattern A
skeleton by the SAME markdown anchors the tool uses on real READMEs (so the standard and the detection
can never drift apart).\"\"\"
lines = path.read_text(encoding="utf-8").split("\\n")
skel = []
i = 0
while i < len(lines):
f = re.match(r"(`{4,})", lines[i])
if f and "markdown" in lines[i]:
fence = f.group(1)
for j in range(i + 1, len(lines)):
s = lines[j].strip()
if s and set(s) == {"`"} and len(s) >= len(fence):
skel.append(lines[i + 1:j])
i = j
break
i += 1
skeletons = {}
if skel:
skeletons["a"] = "\\n".join(skel[0])
if len(skel) >= 2:
skeletons["b"] = "\\n".join(skel[1])
regions = {}
if skel:
a = skel[0]
for name in _README_REGIONS:
span = _readme_region_locate(a, name)
if span:
lo, hi = span
regions[name] = _readme_strip(a[lo:hi])
return regions, skeletons
def _readme_refresh(lines, regions, skill):
\"\"\"Replace each managed region (located by markdown structure) with the canonical content from the
template, where the region is present. Presence-driven. Returns (new_lines, changed_region_names).\"\"\"
changed = []
for name in _README_REGIONS:
if name not in regions:
continue
span = _readme_region_locate(lines, name)
if not span:
continue
lo, hi = span
canonical = [_readme_fill(ln, skill=skill) for ln in regions[name]]
if lines[lo:hi] != canonical:
lines = lines[:lo] + canonical + lines[hi:]
changed.append(name)
return lines, changed
def _readme_anchor_intro(lines):
\"\"\"Span (lo, hi) of the single 'Part of **[Agent Kaizen]' intro paragraph, or None if absent.\"\"\"
for i, ln in enumerate(lines):
if ln.startswith("Part of **[Agent Kaizen]"):
return (i, i + 1)
return None
def _readme_anchor_section(lines, prefix):
\"\"\"Span (lo, hi) of the `## ` section whose heading starts with `prefix` — heading line through
the last non-blank line before the next `## ` heading — or None if absent.\"\"\"
for i, ln in enumerate(lines):
if ln.startswith(prefix):
last, j = i, i + 1
while j < len(lines) and not lines[j].startswith("## "):
if lines[j].strip():
last = j
j += 1
return (i, last + 1)
return None
def _readme_ensure_full_use_it(lines, content_lines):
\"\"\"Ensure a '## Use it' section exists (`content_lines` = the canonical use-it section, heading
included). If the heading is already present, leave it for refresh; otherwise insert the canonical
section right after the '## What's inside' section. Returns (new_lines, acted).\"\"\"
if any(l.strip() == "## Use it" for l in lines):
return lines, False
wi = next((i for i, l in enumerate(lines) if l.strip() == "## What's inside"), None)
if wi is None:
return lines, False
last, j = wi, wi + 1
while j < len(lines) and not lines[j].startswith("## "):
if lines[j].strip():
last = j
j += 1
return lines[:last + 1] + [""] + content_lines + lines[last + 1:], True
def _readme_targets(args, store):
\"\"\"Resolve which skill dirs to act on: all of them (`--all`), the named ones, or None if neither
was given (the caller treats None as a usage error). Unknown names are warned and skipped.\"\"\"
dirs = _readme_skill_dirs(store)
if args.all:
return dirs
if args.skills:
by_name = {d.name: d for d in dirs}
out = []
for s in args.skills:
if s in by_name:
out.append(by_name[s])
else:
print(f" ! unknown skill: {s}")
return out
return None
def _readme_scaffold(args, store, tmpl) -> int:
\"\"\"Write a brand-new README.md for one skill from the Pattern A/B skeleton, placeholders filled.
Refuses to overwrite an existing README without --force. Returns 0 on write, 1 if it would
overwrite, 2 if the requested pattern has no skeleton in the template.
\"\"\"
regions, skeletons = _readme_parse_template(tmpl)
if args.pattern not in skeletons:
print(f"template has no Pattern {args.pattern.upper()} skeleton")
return 2
skill = args.skill
out_dir = Path(args.dir).resolve() if args.dir else (store / skill)
readme = out_dir / "README.md"
if readme.exists() and not args.force:
print(f"refusing to overwrite {readme} (use --force)")
return 1
title = args.title if args.title is not None else skill
tagline = args.tagline if args.tagline is not None else f"_TODO: one-line summary of the {skill} skill._"
body = _readme_fill(skeletons[args.pattern], skill=skill, title=title,
tagline=tagline, article=args.article)
if not body.endswith("\\n"):
body += "\\n"
out_dir.mkdir(parents=True, exist_ok=True)
readme.write_text(body, encoding="utf-8", newline="\\n")
print(f"WROTE {readme} (Pattern {args.pattern.upper()})")
return 0
def _readme_apply(args, store, tmpl) -> int:
\"\"\"Refresh the managed regions of existing skill READMEs from the single-sourced standard.
For each target: strip any legacy markers, optionally ensure a full "Use it" section
(--ensure-use-it), then replace each present managed region with the template's canonical content.
Honors --dry-run (no writes) and --check (exit 1 on any drift). Returns the process exit code.
\"\"\"
regions, _ = _readme_parse_template(tmpl)
targets = _readme_targets(args, store)
if targets is None:
print("specify skill name(s) or --all")
return 2
rc, drift = 0, False
for d in targets:
readme = d / "README.md"
if not readme.is_file():
print(f" ! {d.name}: no README.md")
rc = max(rc, 1)
continue
text = readme.read_text(encoding="utf-8")
new_lines = _readme_strip_markers(text.split("\\n"))
acted = []
if args.ensure_use_it and "use-it" in regions:
canonical = [_readme_fill(ln, skill=d.name) for ln in regions["use-it"]]
new_lines, did = _readme_ensure_full_use_it(new_lines, canonical)
if did:
acted.append("insert use-it")
new_lines, changed = _readme_refresh(new_lines, regions, d.name)
acted += changed
new_text = "\\n".join(new_lines)
if new_text == text:
print(f" unchanged {d.name}")
continue
if not acted:
acted = ["stripped markers"]
if args.check:
print(f" DRIFT {d.name}: would update ({', '.join(acted)})")
drift = True
continue
if args.dry_run:
print(f" [dry-run] {d.name}: would update ({', '.join(acted)})")
continue
readme.write_text(new_text, encoding="utf-8", newline="\\n")
print(f" WROTE {d.name}: {', '.join(acted)}")
return 1 if (args.check and drift) else rc
def cmd_readme(argv=None) -> int:
\"\"\"Parse the `readme` CLI (`scaffold` | `apply`) and dispatch to the matching handler.
Resolves the store root and the README standard template, then scaffolds a new README or applies
the standard to existing ones. Returns the process exit code.
\"\"\"
ap = argparse.ArgumentParser(
prog="skill_builder.py readme",
description="Scaffold and maintain skill README.md files from the single-sourced standard "
"(references/readme-standard.md).")
common = argparse.ArgumentParser(add_help=False)
common.add_argument("--store", help="skills store root (default: the store this script lives in)")
common.add_argument("--template", help="standard/template file (default: references/readme-standard.md)")
sub = ap.add_subparsers(dest="op", required=True)
sp = sub.add_parser("scaffold", parents=[common], help="write a brand-new README.md from the standard")
sp.add_argument("skill")
sp.add_argument("--pattern", choices=["a", "b"], default="a",
help="a = full domain/reference skill; b = lighter/status-driven (default a)")
sp.add_argument("--article", choices=["a", "the"], default="the")
sp.add_argument("--title", default=None)
sp.add_argument("--tagline", default=None)
sp.add_argument("--dir", default=None, help="output directory (default: <store>/<skill>)")
sp.add_argument("--force", action="store_true", help="overwrite an existing README.md")
sp = sub.add_parser("apply", parents=[common],
help="refresh managed regions of existing READMEs (presence-driven)")
sp.add_argument("skills", nargs="*", help="skill names (or use --all)")
sp.add_argument("--all", action="store_true", help="every skill in the store")
sp.add_argument("--ensure-use-it", action="store_true",
help="normalize: give every target skill the full 'Use it' section — insert it after "
"'What's inside' where absent — then refresh")
g = sp.add_mutually_exclusive_group()
g.add_argument("--dry-run", action="store_true", help="print what would change; write nothing")
g.add_argument("--check", action="store_true", help="exit 1 if any README is out of date; write nothing")
args = ap.parse_args(argv)
store = Path(args.store).resolve() if args.store else _readme_store_root()
tmpl = Path(args.template).resolve() if args.template else _readme_default_template()
if not tmpl.is_file():
print(f"template not found: {tmpl}")
return 2
if args.op == "scaffold":
return _readme_scaffold(args, store, tmpl)
if args.op == "apply":
return _readme_apply(args, store, tmpl)
return 2
def main(argv=None) -> int:
\"\"\"Standalone entry point for `python -m builder_components.readme`; delegates to cmd_readme.\"\"\"
return cmd_readme(argv)
if __name__ == "__main__":
raise SystemExit(main())
"""
# ===MODULE builder_components.recontext_core===
_SRC['builder_components.recontext_core'] = """
#!/usr/bin/env python3
\"\"\"recontext_core.py — generalized, stdlib-only recontextualization primitives.
The portable core shared by `skill_builder.py` (its `recontext` command group) and
`recontext_subagent.py` (the locked artifact writer). It carries the proven, deterministic
algorithms for turning a *verbatim* documentation reference file into *original prose* while
preserving every identifier — and for verifying that it did:
fence/code is_fence, iter_lines, strip_code, code_blocks
prose units prose_units, prose_lines, prose_ratio, prose_text, is_prose_line
cleanup clean_text (chrome/scrape-artifact removal + marker normalize + blank collapse)
extract/splice extract (prose packet), load_rewrites, splice (tamper-proof re-insertion)
triage score_file, classify (faction/tier/mode by prose density)
Gate A extract_protected, gate_a (protected-identifier multiset preserved)
Gate B gate_b (no >=13-word verbatim prose run shared w/ source)
Gate C gate_c (no residual scrape cruft)
run_gates all three gates over a (source, working) pair
NOTHING here is hardcoded to a skill, owner, repo, or absolute path: every location is supplied
by the caller. That is what makes the toolset broadly useful and lets the published skill ship a
self-contained engine with no gitignored dependency. Derived from the field-hardened recon-staged
pipeline (lib_recon/cleanup/extract/splice/gates/triage), kept algorithm-for-algorithm faithful so
verdicts match the originals.
\"\"\"
from __future__ import annotations
import json
import re
import sys
from collections import Counter
from pathlib import Path
try: # ensure tool stdout/stderr can emit any source glyph on a cp1252 Windows console
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
# --------------------------------------------------------------------------- #
# Fence detection and code/prose separation.
# --------------------------------------------------------------------------- #
_FENCE = re.compile(r"^(?:`{3,}|~{3,})[\\w+.\\-]*$")
def is_fence(stripped: str) -> bool:
\"\"\"True only for a clean opening/closing code-fence delimiter line.\"\"\"
return bool(_FENCE.match(stripped))
def iter_lines(text):
\"\"\"Yield (line, in_fence) for each line. The fence delimiter itself is in_fence=True.\"\"\"
in_fence = False
for ln in text.split("\\n"):
if is_fence(ln.strip()):
in_fence = not in_fence
yield ln, True
continue
yield ln, in_fence
def strip_code(text: str) -> str:
\"\"\"Return prose-only text (fenced code blocks removed, delimiters dropped).\"\"\"
out = []
for ln, in_fence in iter_lines(text):
if in_fence:
continue