SPB Git

spb/ultra-sharp-agent-skills Public

Ultra-Sharp Agent Skills — a research-first skill-authoring system + 72 production-ready skills for AI agents.

Python 100%
5.2 KB · 135 lines markdown
Rendered Raw Blame History
1<!--2Author: Simon-Pierre Boucher3Contact: contact@spboucher.ai4-->56# Markdown Recipes78## Contents9- Parse document structure (headings, sections)10- Replace one section in place11- Generate a table of contents12- Check links and images13- Extract tables and code blocks14- Pandoc conversion options15- Gotchas (flavors, fences, whitespace)1617## Parse document structure (headings, sections)1819Heading detection must ignore ``` fenced regions — `#` inside code is not a heading:2021```python22def headings(path):23    """Yield (line_no, level, title) for real headings only."""24    in_fence = False25    for i, line in enumerate(open(path, encoding="utf-8")):26        if line.lstrip().startswith("```"):27            in_fence = not in_fence28        elif not in_fence and line.startswith("#"):29            level = len(line) - len(line.lstrip("#"))30            if level <= 6 and line[level:level + 1] == " ":31                yield i, level, line[level:].strip()32```3334## Replace one section in place3536A section spans from its heading to the next heading of the same or higher level:3738```python39def replace_section(path, title, new_body):40    lines = open(path, encoding="utf-8").read().splitlines(keepends=True)41    hs = list(headings(path))42    match = [h for h in hs if h[2] == title]43    if len(match) != 1:44        raise ValueError(f"'{title}': found {len(match)} occurrences, need exactly 1")45    start_line, level, _ = match[0]46    later = [h for h in hs if h[0] > start_line and h[1] <= level]47    end_line = later[0][0] if later else len(lines)48    new = lines[:start_line + 1] + [new_body.rstrip() + "\n\n"] + lines[end_line:]49    open(path, "w", encoding="utf-8").writelines(new)50```5152## Generate a table of contents5354GitHub anchor rule: lowercase, spaces → `-`, strip everything except word chars and hyphens:5556```python57import re5859def toc(path, max_level=3):60    out = []61    for _, level, title in headings(path):62        if 2 <= level <= max_level:          # skip the H1 itself63            anchor = re.sub(r"[^\w\- ]", "", title).strip().lower().replace(" ", "-")64            out.append(f"{'  ' * (level - 2)}- [{title}](#{anchor})")65    return "\n".join(out)66```6768Duplicate titles get `-1`, `-2` suffixes on GitHub — deduplicate with a counter if titles repeat.6970## Check links and images7172Run before any pandoc conversion; missing images abort PDF builds:7374```python75import os, re7677def broken_refs(path):78    text = open(path, encoding="utf-8").read()79    base = os.path.dirname(os.path.abspath(path))80    broken = []81    for target in re.findall(r"!?\[[^\]]*\]\(([^)#\s]+)[^)]*\)", text):82        if not target.startswith(("http://", "https://", "mailto:")):83            if not os.path.exists(os.path.join(base, target)):84                broken.append(target)85    return broken86```8788(External URLs: check only if the user asks — needs network calls.)8990## Extract tables and code blocks9192```python93import re9495text = open("doc.md", encoding="utf-8").read()9697# Fenced code blocks with language → [(lang, code), ...]98blocks = re.findall(r"```(\w*)\n(.*?)```", text, flags=re.S)99100# Pipe tables → rows of cells (skip the |---| separator line)101rows = [[c.strip() for c in line.strip().strip("|").split("|")]102        for line in text.splitlines()103        if line.lstrip().startswith("|") and not re.match(r"^\s*\|[\s:|-]+\|\s*$", line)]104```105106## Pandoc conversion options107108```bash109# Standalone HTML with title metadata (otherwise pandoc emits a fragment)110pandoc README.md -s --metadata title="README" -o README.html111112# GFM input explicitly (tables, task lists, strikethrough)113pandoc -f gfm README.md -o out.docx114115# PDF with margins and a TOC116pandoc report.md --toc -V geometry:margin=1in -o report.pdf117118# Word → Markdown, keep images119pandoc report.docx --extract-media=./media -t gfm -o report.md120121# Custom Word styling: reuse an existing doc's styles122pandoc report.md --reference-doc=template.docx -o styled.docx123```124125## Gotchas (flavors, fences, whitespace)126127- **Flavor differences.** Tables, task lists (`- [ ]`), footnotes, and strikethrough are GFM/extensions — original Markdown renderers ignore them. Pandoc's default input is *pandoc markdown*, not GFM: pass `-f gfm` when the source came from GitHub.128- **Fences must balance.** An unclosed ``` swallows the rest of the document. Count fence lines before structural edits (the `headings()` recipe already guards this).129- **Indented code blocks.** 4-space-indented lines are code in classic Markdown — a list continuation indented 4+ spaces can silently become a code block. Prefer fenced blocks everywhere.130- **Two trailing spaces = line break.** Invisible but meaningful; don't strip trailing whitespace blindly in an existing file.131- **Bare URLs** don't auto-link in all renderers — wrap in `<...>` or `[text](url)`.132- **HTML inside Markdown** passes through most renderers but is stripped by some (and by pandoc to some formats) — flag it when converting.133- **Setext headings** (`Title\n=====`) are equivalent to `#`/`##`; the structure parser above misses them — normalize them first if a file mixes both styles, but only with the user's agreement (it rewrites lines).134- **Anchor links differ across renderers.** The GitHub rule in the TOC recipe does not match GitLab/MkDocs exactly for punctuation-heavy titles; verify on the target platform.135