feat: update skills & update hyprland

This commit is contained in:
johannes committed 2026-08-23 14:59:01 +02:00
1 parent f3bd31bb7c
commit 39b4594c22
172 files changed
+17160 -6309

No files matched your search

-82
View File
@@ -1,82 +0,0 @@
---
name: cavecrew
description: >
Decision guide for delegating to caveman-style subagents. Tells the main
thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder`
(1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the
work inline or using vanilla `Explore`. Subagent output is caveman-compressed
so the tool-result injected back into main context is ~60% smaller — main
context lasts longer across long sessions.
Trigger: "delegate to subagent", "use cavecrew", "spawn investigator/builder/reviewer",
"save context", "compressed agent output".
---
Cavecrew = three subagent presets that emit caveman output. Same job as Anthropic defaults (`Explore`, edit-style agents, reviewer); difference is the tool-result they return is compressed, so main context shrinks per delegation.
## When to use cavecrew vs alternatives
| Task | Use |
|---|---|
| "Where is X defined / what calls Y / list uses of Z" | `cavecrew-investigator` |
| Same but you also want suggestions/architecture commentary | `Explore` (vanilla) |
| Surgical edit, ≤2 files, scope obvious | `cavecrew-builder` |
| New feature / 3+ files / cross-cutting refactor | Main thread or `feature-dev:code-architect` |
| Review diff, branch, or file for bugs | `cavecrew-reviewer` |
| Deep code review with rationale + alternatives | `Code Reviewer` (vanilla) |
| One-line answer you already know | Main thread, no subagent |
Rule of thumb: **if you'd want the subagent's output in 1/3 the tokens, pick cavecrew. If you'd want prose, pick vanilla.**
## Why this exists (the real win)
Subagent tool results get injected into main context verbatim. A vanilla `Explore` that returns 2k tokens of prose costs 2k tokens of main-context budget every time. The same finding from `cavecrew-investigator` returns ~700 tokens. Across 20 delegations in one session that's the difference between context exhaustion and finishing the task.
## Output contracts
What main thread can rely on per agent:
**`cavecrew-investigator`**
```
<Header>:
- path:line — `symbol` — short note
totals: <counts>.
```
Or `No match.` Always file-path-first, line-number-attached, backticked symbols. Safe to grep with `path:\d+`.
**`cavecrew-builder`**
```
<path:line-range> — <change ≤10 words>.
verified: <re-read OK | mismatch @ path:line>.
```
Or one of: `too-big.` / `needs-confirm.` / `ambiguous.` / `regressed.` (terminal first token).
**`cavecrew-reviewer`**
```
path:line: <emoji> <severity>: <problem>. <fix>.
totals: N🔴 N🟡 N🔵 N❓
```
Or `No issues.` Findings sorted file → line ascending.
## Chaining patterns
**Locate → fix → verify** (most common):
1. `cavecrew-investigator` returns site list.
2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`.
3. `cavecrew-reviewer` audits the diff.
**Parallel scout** (when investigation is broad):
Spawn 2-3 `cavecrew-investigator` calls in one message (different angles: defs vs callers vs tests). Aggregate in main thread.
**Single-shot edit** (when site is already known):
Skip investigator. Hand exact path:line to `cavecrew-builder` directly.
## What NOT to do
- Don't use `cavecrew-builder` when you don't already know the file. Spawn investigator first or main thread will eat tokens passing context.
- Don't chain `cavecrew-investigator → cavecrew-builder` for a 5-file refactor. Builder will return `too-big.` and you'll have wasted a turn.
- Don't ask `cavecrew-reviewer` for "general feedback" — it returns findings only, no architecture opinions. Use `Code Reviewer` for that.
- Don't expect prose. Cavecrew output is structured, sometimes terse to the point of cryptic. If a human will read it directly, paraphrase.
## Auto-clarity (inherited)
Subagents drop caveman → normal English for security warnings, irreversible-action confirmations, and any output where fragment ambiguity could be misread. Resume caveman after.
-65
View File
@@ -1,65 +0,0 @@
---
name: caveman-commit
description: >
Ultra-compressed commit message generator. Cuts noise from commit messages while preserving
intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why"
isn't obvious. Use when user says "write a commit", "commit message", "generate commit",
"/commit", or invokes /caveman-commit. Auto-triggers when staging changes.
---
Write commit messages terse and exact. Conventional Commits format. No fluff. Why over what.
## Rules
**Subject line:**
- `<type>(<scope>): <imperative summary>` — `<scope>` optional
- Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `chore`, `build`, `ci`, `style`, `revert`
- Imperative mood: "add", "fix", "remove" — not "added", "adds", "adding"
- ≤50 chars when possible, hard cap 72
- No trailing period
- Match project convention for capitalization after the colon
**Body (only if needed):**
- Skip entirely when subject is self-explanatory
- Add body only for: non-obvious *why*, breaking changes, migration notes, linked issues
- Wrap at 72 chars
- Bullets `-` not `*`
- Reference issues/PRs at end: `Closes #42`, `Refs #17`
**What NEVER goes in:**
- "This commit does X", "I", "we", "now", "currently" — the diff says what
- "As requested by..." — use Co-authored-by trailer
- "Generated with Claude Code" or any AI attribution
- Emoji (unless project convention requires)
- Restating the file name when scope already says it
## Examples
Diff: new endpoint for user profile with body explaining the why
- ❌ "feat: add a new endpoint to get user profile information from the database"
- ✅
```
feat(api): add GET /users/:id/profile
Mobile client needs profile data without the full user payload
to reduce LTE bandwidth on cold-launch screens.
Closes #128
```
Diff: breaking API change
- ✅
```
feat(api)!: rename /v1/orders to /v1/checkout
BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
before 2026-06-01. Old route returns 410 after that date.
```
## Auto-Clarity
Always include body for: breaking changes, security fixes, data migrations, anything reverting a prior commit. Never compress these into subject-only — future debuggers need the context.
## Boundaries
Only generates the commit message. Does not run `git commit`, does not stage files, does not amend. Output the message as a code block ready to paste. "stop caveman-commit" or "normal mode": revert to verbose commit style.
-163
View File
@@ -1,163 +0,0 @@
<p align="center">
<img src="https://em-content.zobj.net/source/apple/391/rock_1faa8.png" width="80" />
</p>
<h1 align="center">caveman-compress</h1>
<p align="center">
<strong>shrink memory file. save token every session.</strong>
</p>
---
A Claude Code skill that compresses your project memory files (`CLAUDE.md`, todos, preferences) into caveman format — so every session loads fewer tokens automatically.
Claude read `CLAUDE.md` on every session start. If file big, cost big. Caveman make file small. Cost go down forever.
## What It Do
```
/caveman:compress CLAUDE.md
```
```
CLAUDE.md ← compressed (Claude reads this — fewer tokens every session)
CLAUDE.original.md ← human-readable backup (you edit this)
```
Original never lost. You can read and edit `.original.md`. Run skill again to re-compress after edits.
## Benchmarks
Real results on real project files:
| File | Original | Compressed | Saved |
|------|----------:|----------:|------:|
| `claude-md-preferences.md` | 706 | 285 | **59.6%** |
| `project-notes.md` | 1145 | 535 | **53.3%** |
| `claude-md-project.md` | 1122 | 636 | **43.3%** |
| `todo-list.md` | 627 | 388 | **38.1%** |
| `mixed-with-code.md` | 888 | 560 | **36.9%** |
| **Average** | **898** | **481** | **46%** |
All validations passed ✅ — headings, code blocks, URLs, file paths preserved exactly.
## Before / After
<table>
<tr>
<td width="50%">
### 📄 Original (706 tokens)
> "I strongly prefer TypeScript with strict mode enabled for all new code. Please don't use `any` type unless there's genuinely no way around it, and if you do, leave a comment explaining the reasoning. I find that taking the time to properly type things catches a lot of bugs before they ever make it to runtime."
</td>
<td width="50%">
### 🪨 Caveman (285 tokens)
> "Prefer TypeScript strict mode always. No `any` unless unavoidable — comment why if used. Proper types catch bugs early."
</td>
</tr>
</table>
**Same instructions. 60% fewer tokens. Every. Single. Session.**
## Security
`caveman-compress` is flagged as Snyk High Risk due to subprocess and file I/O patterns detected by static analysis. This is a false positive — see [SECURITY.md](./SECURITY.md) for a full explanation of what the skill does and does not do.
## Install
Compress is built in with the `caveman` plugin. Install `caveman` once, then use `/caveman:compress`.
If you need local files, the compress skill lives at:
```bash
caveman-compress/
```
**Requires:** Python 3.10+
## Usage
```
/caveman:compress <filepath>
```
Examples:
```
/caveman:compress CLAUDE.md
/caveman:compress docs/preferences.md
/caveman:compress todos.md
```
### What files work
| Type | Compress? |
|------|-----------|
| `.md`, `.txt`, `.rst` | ✅ Yes |
| Extensionless natural language | ✅ Yes |
| `.py`, `.js`, `.ts`, `.json`, `.yaml` | ❌ Skip (code/config) |
| `*.original.md` | ❌ Skip (backup files) |
## How It Work
```
/caveman:compress CLAUDE.md
↓
detect file type (no tokens)
↓
Claude compresses (tokens — one call)
↓
validate output (no tokens)
checks: headings, code blocks, URLs, file paths, bullets
↓
if errors: Claude fixes cherry-picked issues only (tokens — targeted fix)
does NOT recompress — only patches broken parts
↓
retry up to 2 times
↓
write compressed → CLAUDE.md
write original → CLAUDE.original.md
```
Only two things use tokens: initial compression + targeted fix if validation fails. Everything else is local Python.
## What Is Preserved
Caveman compress natural language. It never touch:
- Code blocks (` ``` ` fenced or indented)
- Inline code (`` `backtick content` ``)
- URLs and links
- File paths (`/src/components/...`)
- Commands (`npm install`, `git commit`)
- Technical terms, library names, API names
- Headings (exact text preserved)
- Tables (structure preserved, cell text compressed)
- Dates, version numbers, numeric values
## Why This Matter
`CLAUDE.md` loads on **every session start**. A 1000-token project memory file costs tokens every single time you open a project. Over 100 sessions that's 100,000 tokens of overhead — just for context you already wrote.
Caveman cut that by ~46% on average. Same instructions. Same accuracy. Less waste.
```
┌────────────────────────────────────────────┐
│ TOKEN SAVINGS PER FILE █████ 46% │
│ SESSIONS THAT BENEFIT ██████████ 100% │
│ INFORMATION PRESERVED ██████████ 100% │
│ SETUP TIME █ 1x │
└────────────────────────────────────────────┘
```
## Part of Caveman
This skill is part of the [caveman](https://github.com/JuliusBrussee/caveman) toolkit — making Claude use fewer tokens without losing accuracy.
- **caveman** — make Claude *speak* like caveman (cuts response tokens ~65%)
- **caveman-compress** — make Claude *read* less (cuts context tokens ~46%)
@@ -1,31 +0,0 @@
# Security
## Snyk High Risk Rating
`caveman-compress` receives a Snyk High Risk rating due to static analysis heuristics. This document explains what the skill does and does not do.
### What triggers the rating
1. **subprocess usage**: The skill calls the `claude` CLI via `subprocess.run()` as a fallback when `ANTHROPIC_API_KEY` is not set. The subprocess call uses a fixed argument list — no shell interpolation occurs. User file content is passed via stdin, not as a shell argument.
2. **File read/write**: The skill reads the file the user explicitly points it at, compresses it, and writes the result back to the same path. A `.original.md` backup is saved alongside it. No files outside the user-specified path are read or written.
### What the skill does NOT do
- Does not execute user file content as code
- Does not make network requests except to Anthropic's API (via SDK or CLI)
- Does not access files outside the path the user provides
- Does not use shell=True or string interpolation in subprocess calls
- Does not collect or transmit any data beyond the file being compressed
### Auth behavior
If `ANTHROPIC_API_KEY` is set, the skill uses the Anthropic Python SDK directly (no subprocess). If not set, it falls back to the `claude` CLI, which uses the user's existing Claude desktop authentication.
### File size limit
Files larger than 500KB are rejected before any API call is made.
### Reporting a vulnerability
If you believe you've found a genuine security issue, please open a GitHub issue with the label `security`.
-111
View File
@@ -1,111 +0,0 @@
---
name: caveman-compress
description: >
Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
to save input tokens. Preserves all technical substance, code, URLs, and structure.
Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
Trigger: /caveman:compress <filepath> or "compress memory file"
---
# Caveman Compress
## Purpose
Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
## Trigger
`/caveman:compress <filepath>` or when user asks to compress a memory file.
## Process
1. The compression scripts live in `caveman-compress/scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `caveman-compress/scripts/__main__.py`.
2. Run:
cd caveman-compress && python3 -m scripts <absolute_filepath>
3. The CLI will:
- detect file type (no tokens)
- call Claude to compress
- validate output (no tokens)
- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
- retry up to 2 times
- if still failing after 2 retries: report error to user, leave original file untouched
4. Return result to user
## Compression Rules
### Remove
- Articles: a, an, the
- Filler: just, really, basically, actually, simply, essentially, generally
- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
- Hedging: "it might be worth", "you could consider", "it would be good to"
- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
- Connective fluff: "however", "furthermore", "additionally", "in addition"
### Preserve EXACTLY (never modify)
- Code blocks (fenced ``` and indented)
- Inline code (`backtick content`)
- URLs and links (full URLs, markdown links)
- File paths (`/src/components/...`, `./config.yaml`)
- Commands (`npm install`, `git commit`, `docker build`)
- Technical terms (library names, API names, protocols, algorithms)
- Proper nouns (project names, people, companies)
- Dates, version numbers, numeric values
- Environment variables (`$HOME`, `NODE_ENV`)
### Preserve Structure
- All markdown headings (keep exact heading text, compress body below)
- Bullet point hierarchy (keep nesting level)
- Numbered lists (keep numbering)
- Tables (compress cell text, keep structure)
- Frontmatter/YAML headers in markdown files
### Compress
- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
- Fragments OK: "Run tests before commit" not "You should always run tests before committing"
- Drop "you should", "make sure to", "remember to" — just state the action
- Merge redundant bullets that say the same thing differently
- Keep one example where multiple examples show the same pattern
CRITICAL RULE:
Anything inside ``` ... ``` must be copied EXACTLY.
Do not:
- remove comments
- remove spacing
- reorder lines
- shorten commands
- simplify anything
Inline code (`...`) must be preserved EXACTLY.
Do not modify anything inside backticks.
If file contains code blocks:
- Treat code blocks as read-only regions
- Only compress text outside them
- Do not merge sections around code
## Pattern
Original:
> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
Compressed:
> Run tests before push to main. Catch bugs early, prevent broken prod deploys.
Original:
> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
Compressed:
> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
## Boundaries
- ONLY compress natural language files (.md, .txt, extensionless)
- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
- If file has mixed content (prose + code), compress ONLY the prose sections
- If unsure whether something is code or prose, leave it unchanged
- Original file is backed up as FILE.original.md before overwriting
- Never compress FILE.original.md (skip it)
@@ -1,9 +0,0 @@
"""Caveman compress scripts.
This package provides tools to compress natural language markdown files
into caveman format to save input tokens.
"""
__all__ = ["cli", "compress", "detect", "validate"]
__version__ = "1.0.0"
@@ -1,3 +0,0 @@
from .cli import main
main()
@@ -1,78 +0,0 @@
#!/usr/bin/env python3
from pathlib import Path
import sys
# Support both direct execution and module import
try:
from .validate import validate
except ImportError:
sys.path.insert(0, str(Path(__file__).parent))
from validate import validate
try:
import tiktoken
_enc = tiktoken.get_encoding("o200k_base")
except ImportError:
_enc = None
def count_tokens(text):
if _enc is None:
return len(text.split()) # fallback: word count
return len(_enc.encode(text))
def benchmark_pair(orig_path: Path, comp_path: Path):
orig_text = orig_path.read_text()
comp_text = comp_path.read_text()
orig_tokens = count_tokens(orig_text)
comp_tokens = count_tokens(comp_text)
saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0
result = validate(orig_path, comp_path)
return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid)
def print_table(rows):
print("\n| File | Original | Compressed | Saved % | Valid |")
print("|------|----------|------------|---------|-------|")
for r in rows:
print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |")
def main():
# Direct file pair: python3 benchmark.py original.md compressed.md
if len(sys.argv) == 3:
orig = Path(sys.argv[1]).resolve()
comp = Path(sys.argv[2]).resolve()
if not orig.exists():
print(f"❌ Not found: {orig}")
sys.exit(1)
if not comp.exists():
print(f"❌ Not found: {comp}")
sys.exit(1)
print_table([benchmark_pair(orig, comp)])
return
# Glob mode: repo_root/tests/caveman-compress/
tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress"
if not tests_dir.exists():
print(f"❌ Tests dir not found: {tests_dir}")
sys.exit(1)
rows = []
for orig in sorted(tests_dir.glob("*.original.md")):
comp = orig.with_name(orig.stem.removesuffix(".original") + ".md")
if comp.exists():
rows.append(benchmark_pair(orig, comp))
if not rows:
print("No compressed file pairs found.")
return
print_table(rows)
if __name__ == "__main__":
main()
@@ -1,73 +0,0 @@
#!/usr/bin/env python3
"""
Caveman Compress CLI
Usage:
caveman <filepath>
"""
import sys
from pathlib import Path
from .compress import compress_file
from .detect import detect_file_type, should_compress
def print_usage():
print("Usage: caveman <filepath>")
def main():
if len(sys.argv) != 2:
print_usage()
sys.exit(1)
filepath = Path(sys.argv[1])
# Check file exists
if not filepath.exists():
print(f"❌ File not found: {filepath}")
sys.exit(1)
if not filepath.is_file():
print(f"❌ Not a file: {filepath}")
sys.exit(1)
filepath = filepath.resolve()
# Detect file type
file_type = detect_file_type(filepath)
print(f"Detected: {file_type}")
# Check if compressible
if not should_compress(filepath):
print("Skipping: file is not natural language (code/config)")
sys.exit(0)
print("Starting caveman compression...\n")
try:
success = compress_file(filepath)
if success:
print("\nCompression completed successfully")
backup_path = filepath.with_name(filepath.stem + ".original.md")
print(f"Compressed: {filepath}")
print(f"Original: {backup_path}")
sys.exit(0)
else:
print("\n❌ Compression failed after retries")
sys.exit(2)
except KeyboardInterrupt:
print("\nInterrupted by user")
sys.exit(130)
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
@@ -1,176 +0,0 @@
#!/usr/bin/env python3
"""
Caveman Memory Compression Orchestrator
Usage:
python scripts/compress.py <filepath>
"""
import os
import re
import subprocess
from pathlib import Path
from typing import List
OUTER_FENCE_REGEX = re.compile(
r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
)
def strip_llm_wrapper(text: str) -> str:
"""Strip outer ```markdown ... ``` fence when it wraps the entire output."""
m = OUTER_FENCE_REGEX.match(text)
if m:
return m.group(2)
return text
from .detect import should_compress
from .validate import validate
MAX_RETRIES = 2
# ---------- Claude Calls ----------
def call_claude(prompt: str) -> str:
api_key = os.environ.get("ANTHROPIC_API_KEY")
if api_key:
try:
import anthropic
client = anthropic.Anthropic(api_key=api_key)
msg = client.messages.create(
model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
max_tokens=8192,
messages=[{"role": "user", "content": prompt}],
)
return strip_llm_wrapper(msg.content[0].text.strip())
except ImportError:
pass # anthropic not installed, fall back to CLI
# Fallback: use claude CLI (handles desktop auth)
try:
result = subprocess.run(
["claude", "--print"],
input=prompt,
text=True,
capture_output=True,
check=True,
)
return strip_llm_wrapper(result.stdout.strip())
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Claude call failed:\n{e.stderr}")
def build_compress_prompt(original: str) -> str:
return f"""
Compress this markdown into caveman format.
STRICT RULES:
- Do NOT modify anything inside ``` code blocks
- Do NOT modify anything inside inline backticks
- Preserve ALL URLs exactly
- Preserve ALL headings exactly
- Preserve file paths and commands
- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
Only compress natural language.
TEXT:
{original}
"""
def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
errors_str = "\n".join(f"- {e}" for e in errors)
return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
CRITICAL RULES:
- DO NOT recompress or rephrase the file
- ONLY fix the listed errors — leave everything else exactly as-is
- The ORIGINAL is provided as reference only (to restore missing content)
- Preserve caveman style in all untouched sections
ERRORS TO FIX:
{errors_str}
HOW TO FIX:
- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
- Do not touch any section not mentioned in the errors
ORIGINAL (reference only):
{original}
COMPRESSED (fix this):
{compressed}
Return ONLY the fixed compressed file. No explanation.
"""
# ---------- Core Logic ----------
def compress_file(filepath: Path) -> bool:
# Resolve and validate path
filepath = filepath.resolve()
MAX_FILE_SIZE = 500_000 # 500KB
if not filepath.exists():
raise FileNotFoundError(f"File not found: {filepath}")
if filepath.stat().st_size > MAX_FILE_SIZE:
raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
print(f"Processing: {filepath}")
if not should_compress(filepath):
print("Skipping (not natural language)")
return False
original_text = filepath.read_text(errors="ignore")
backup_path = filepath.with_name(filepath.stem + ".original.md")
# Check if backup already exists to prevent accidental overwriting
if backup_path.exists():
print(f"⚠️ Backup file already exists: {backup_path}")
print("The original backup may contain important content.")
print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
return False
# Step 1: Compress
print("Compressing with Claude...")
compressed = call_claude(build_compress_prompt(original_text))
# Save original as backup, write compressed to original path
backup_path.write_text(original_text)
filepath.write_text(compressed)
# Step 2: Validate + Retry
for attempt in range(MAX_RETRIES):
print(f"\nValidation attempt {attempt + 1}")
result = validate(backup_path, filepath)
if result.is_valid:
print("Validation passed")
break
print("❌ Validation failed:")
for err in result.errors:
print(f" - {err}")
if attempt == MAX_RETRIES - 1:
# Restore original on failure
filepath.write_text(original_text)
backup_path.unlink(missing_ok=True)
print("❌ Failed after retries — original restored")
return False
print("Fixing with Claude...")
compressed = call_claude(
build_fix_prompt(original_text, compressed, result.errors)
)
filepath.write_text(compressed)
return True
@@ -1,121 +0,0 @@
#!/usr/bin/env python3
"""Detect whether a file is natural language (compressible) or code/config (skip)."""
import json
import re
from pathlib import Path
# Extensions that are natural language and compressible
COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst"}
# Extensions that are code/config and should be skipped
SKIP_EXTENSIONS = {
".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
}
# Patterns that indicate a line is code
CODE_PATTERNS = [
re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
re.compile(r"^\s*(def |class |function |async function |export )"),
re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
re.compile(r"^\s*@\w+"), # decorators/annotations
re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
]
def _is_code_line(line: str) -> bool:
"""Check if a line looks like code."""
return any(p.match(line) for p in CODE_PATTERNS)
def _is_json_content(text: str) -> bool:
"""Check if content is valid JSON."""
try:
json.loads(text)
return True
except (json.JSONDecodeError, ValueError):
return False
def _is_yaml_content(lines: list[str]) -> bool:
"""Heuristic: check if content looks like YAML."""
yaml_indicators = 0
for line in lines[:30]:
stripped = line.strip()
if stripped.startswith("---"):
yaml_indicators += 1
elif re.match(r"^\w[\w\s]*:\s", stripped):
yaml_indicators += 1
elif stripped.startswith("- ") and ":" in stripped:
yaml_indicators += 1
# If most non-empty lines look like YAML
non_empty = sum(1 for l in lines[:30] if l.strip())
return non_empty > 0 and yaml_indicators / non_empty > 0.6
def detect_file_type(filepath: Path) -> str:
"""Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
Returns:
One of: 'natural_language', 'code', 'config', 'unknown'
"""
ext = filepath.suffix.lower()
# Extension-based classification
if ext in COMPRESSIBLE_EXTENSIONS:
return "natural_language"
if ext in SKIP_EXTENSIONS:
return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config"
# Extensionless files (like CLAUDE.md, TODO) — check content
if not ext:
try:
text = filepath.read_text(errors="ignore")
except (OSError, PermissionError):
return "unknown"
lines = text.splitlines()[:50]
if _is_json_content(text[:10000]):
return "config"
if _is_yaml_content(lines):
return "config"
code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l))
non_empty = sum(1 for l in lines if l.strip())
if non_empty > 0 and code_lines / non_empty > 0.4:
return "code"
return "natural_language"
return "unknown"
def should_compress(filepath: Path) -> bool:
"""Return True if the file is natural language and should be compressed."""
if not filepath.is_file():
return False
# Skip backup files
if filepath.name.endswith(".original.md"):
return False
return detect_file_type(filepath) == "natural_language"
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python detect.py <file1> [file2] ...")
sys.exit(1)
for path_str in sys.argv[1:]:
p = Path(path_str).resolve()
file_type = detect_file_type(p)
compress = should_compress(p)
print(f" {p.name:30s} type={file_type:20s} compress={compress}")
@@ -1,189 +0,0 @@
#!/usr/bin/env python3
import re
from pathlib import Path
URL_REGEX = re.compile(r"https?://[^\s)]+")
FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$")
HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE)
BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE)
# crude but effective path detection
# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match
PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+")
class ValidationResult:
def __init__(self):
self.is_valid = True
self.errors = []
self.warnings = []
def add_error(self, msg):
self.is_valid = False
self.errors.append(msg)
def add_warning(self, msg):
self.warnings.append(msg)
def read_file(path: Path) -> str:
return path.read_text(errors="ignore")
# ---------- Extractors ----------
def extract_headings(text):
return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)]
def extract_code_blocks(text):
"""Line-based fenced code block extractor.
Handles ``` and ~~~ fences with variable length (CommonMark: closing
fence must use same char and be at least as long as opening). Supports
nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick
content).
"""
blocks = []
lines = text.split("\n")
i = 0
n = len(lines)
while i < n:
m = FENCE_OPEN_REGEX.match(lines[i])
if not m:
i += 1
continue
fence_char = m.group(2)[0]
fence_len = len(m.group(2))
open_line = lines[i]
block_lines = [open_line]
i += 1
closed = False
while i < n:
close_m = FENCE_OPEN_REGEX.match(lines[i])
if (
close_m
and close_m.group(2)[0] == fence_char
and len(close_m.group(2)) >= fence_len
and close_m.group(3).strip() == ""
):
block_lines.append(lines[i])
closed = True
i += 1
break
block_lines.append(lines[i])
i += 1
if closed:
blocks.append("\n".join(block_lines))
# Unclosed fences are silently skipped — they indicate malformed markdown
# and including them would cause false-positive validation failures.
return blocks
def extract_urls(text):
return set(URL_REGEX.findall(text))
def extract_paths(text):
return set(PATH_REGEX.findall(text))
def count_bullets(text):
return len(BULLET_REGEX.findall(text))
# ---------- Validators ----------
def validate_headings(orig, comp, result):
h1 = extract_headings(orig)
h2 = extract_headings(comp)
if len(h1) != len(h2):
result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}")
if h1 != h2:
result.add_warning("Heading text/order changed")
def validate_code_blocks(orig, comp, result):
c1 = extract_code_blocks(orig)
c2 = extract_code_blocks(comp)
if c1 != c2:
result.add_error("Code blocks not preserved exactly")
def validate_urls(orig, comp, result):
u1 = extract_urls(orig)
u2 = extract_urls(comp)
if u1 != u2:
result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}")
def validate_paths(orig, comp, result):
p1 = extract_paths(orig)
p2 = extract_paths(comp)
if p1 != p2:
result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}")
def validate_bullets(orig, comp, result):
b1 = count_bullets(orig)
b2 = count_bullets(comp)
if b1 == 0:
return
diff = abs(b1 - b2) / b1
if diff > 0.15:
result.add_warning(f"Bullet count changed too much: {b1} -> {b2}")
# ---------- Main ----------
def validate(original_path: Path, compressed_path: Path) -> ValidationResult:
result = ValidationResult()
orig = read_file(original_path)
comp = read_file(compressed_path)
validate_headings(orig, comp, result)
validate_code_blocks(orig, comp, result)
validate_urls(orig, comp, result)
validate_paths(orig, comp, result)
validate_bullets(orig, comp, result)
return result
# ---------- CLI ----------
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python validate.py <original> <compressed>")
sys.exit(1)
orig = Path(sys.argv[1]).resolve()
comp = Path(sys.argv[2]).resolve()
res = validate(orig, comp)
print(f"\nValid: {res.is_valid}")
if res.errors:
print("\nErrors:")
for e in res.errors:
print(f" - {e}")
if res.warnings:
print("\nWarnings:")
for w in res.warnings:
print(f" - {w}")
-59
View File
@@ -1,59 +0,0 @@
---
name: caveman-help
description: >
Quick-reference card for all caveman modes, skills, and commands.
One-shot display, not a persistent mode. Trigger: /caveman-help,
"caveman help", "what caveman commands", "how do I use caveman".
---
# Caveman Help
Display this reference card when invoked. One-shot — do NOT change mode, write flag files, or persist anything. Output in caveman style.
## Modes
| Mode | Trigger | What change |
|------|---------|-------------|
| **Lite** | `/caveman lite` | Drop filler. Keep sentence structure. |
| **Full** | `/caveman` | Drop articles, filler, pleasantries, hedging. Fragments OK. Default. |
| **Ultra** | `/caveman ultra` | Extreme compression. Bare fragments. Tables over prose. |
| **Wenyan-Lite** | `/caveman wenyan-lite` | Classical Chinese style, light compression. |
| **Wenyan-Full** | `/caveman wenyan` | Full 文言文. Maximum classical terseness. |
| **Wenyan-Ultra** | `/caveman wenyan-ultra` | Extreme. Ancient scholar on a budget. |
Mode stick until changed or session end.
## Skills
| Skill | Trigger | What it do |
|-------|---------|-----------|
| **caveman-commit** | `/caveman-commit` | Terse commit messages. Conventional Commits. ≤50 char subject. |
| **caveman-review** | `/caveman-review` | One-line PR comments: `L42: bug: user null. Add guard.` |
| **caveman-compress** | `/caveman:compress <file>` | Compress .md files to caveman prose. Saves ~46% input tokens. |
| **caveman-help** | `/caveman-help` | This card. |
## Deactivate
Say "stop caveman" or "normal mode". Resume anytime with `/caveman`.
## Configure Default Mode
Default mode = `full`. Change it:
**Environment variable** (highest priority):
```bash
export CAVEMAN_DEFAULT_MODE=ultra
```
**Config file** (`~/.config/caveman/config.json`):
```json
{ "defaultMode": "lite" }
```
Set `"off"` to disable auto-activation on session start. User can still activate manually with `/caveman`.
Resolution: env var > config file > `full`.
## More
Full docs: https://github.com/JuliusBrussee/caveman
-55
View File
@@ -1,55 +0,0 @@
---
name: caveman-review
description: >
Ultra-compressed code review comments. Cuts noise from PR feedback while preserving
the actionable signal. Each comment is one line: location, problem, fix. Use when user
says "review this PR", "code review", "review the diff", "/review", or invokes
/caveman-review. Auto-triggers when reviewing pull requests.
---
Write code review comments terse and actionable. One line per finding. Location, problem, fix. No throat-clearing.
## Rules
**Format:** `L<line>: <problem>. <fix>.` — or `<file>:L<line>: ...` when reviewing multi-file diffs.
**Severity prefix (optional, when mixed):**
- `🔴 bug:` — broken behavior, will cause incident
- `🟡 risk:` — works but fragile (race, missing null check, swallowed error)
- `🔵 nit:` — style, naming, micro-optim. Author can ignore
- `❓ q:` — genuine question, not a suggestion
**Drop:**
- "I noticed that...", "It seems like...", "You might want to consider..."
- "This is just a suggestion but..." — use `nit:` instead
- "Great work!", "Looks good overall but..." — say it once at the top, not per comment
- Restating what the line does — the reviewer can read the diff
- Hedging ("perhaps", "maybe", "I think") — if unsure use `q:`
**Keep:**
- Exact line numbers
- Exact symbol/function/variable names in backticks
- Concrete fix, not "consider refactoring this"
- The *why* if the fix isn't obvious from the problem statement
## Examples
❌ "I noticed that on line 42 you're not checking if the user object is null before accessing the email property. This could potentially cause a crash if the user is not found in the database. You might want to add a null check here."
✅ `L42: 🔴 bug: user can be null after .find(). Add guard before .email.`
❌ "It looks like this function is doing a lot of things and might benefit from being broken up into smaller functions for readability."
✅ `L88-140: 🔵 nit: 50-line fn does 4 things. Extract validate/normalize/persist.`
❌ "Have you considered what happens if the API returns a 429? I think we should probably handle that case."
✅ `L23: 🟡 risk: no retry on 429. Wrap in withBackoff(3).`
## Auto-Clarity
Drop terse mode for: security findings (CVE-class bugs need full explanation + reference), architectural disagreements (need rationale, not just a one-liner), and onboarding contexts where the author is new and needs the "why". In those cases write a normal paragraph, then resume terse for the rest.
## Boundaries
Reviews only — does not write the code fix, does not approve/request-changes, does not run linters. Output the comment(s) ready to paste into the PR. "stop caveman-review" or "normal mode": revert to verbose review style.
-10
View File
@@ -1,10 +0,0 @@
---
name: caveman-stats
description: >
Show real token usage and estimated savings for the current session.
Reads directly from the Claude Code session log — no AI estimation.
Triggers on /caveman-stats. Output is injected by the mode-tracker hook;
the model itself does not compute the numbers.
---
This skill is delivered by `hooks/caveman-stats.js` (read by `hooks/caveman-mode-tracker.js` on `/caveman-stats`). The model does not need to do anything when this skill fires — the hook returns `decision: "block"` with the formatted stats as the reason. The user sees the numbers immediately.
-67
View File
@@ -1,67 +0,0 @@
---
name: caveman
description: >
Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman
while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra,
wenyan-lite, wenyan-full, wenyan-ultra.
Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens",
"be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.
---
Respond terse like smart caveman. All technical substance stay. Only fluff die.
## Persistence
ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode".
Default: **full**. Switch: `/caveman lite|full|ultra`.
## Rules
Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Technical terms exact. Code blocks unchanged. Errors quoted exact.
Pattern: `[thing] [action] [reason]. [next step].`
Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..."
Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:"
## Intensity
| Level | What change |
|-------|------------|
| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |
| **full** | Drop articles, fragments OK, short synonyms. Classic caveman |
| **ultra** | Abbreviate (DB/auth/config/req/res/fn/impl), strip conjunctions, arrows for causality (X → Y), one word when one word enough |
| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register |
| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) |
| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse |
Example — "Why React component re-render?"
- lite: "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`."
- full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`."
- ultra: "Inline obj prop → new ref → re-render. `useMemo`."
- wenyan-lite: "組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。"
- wenyan-full: "物出新參照,致重繪。useMemo .Wrap之。"
- wenyan-ultra: "新參照→重繪。useMemo Wrap。"
Example — "Explain database connection pooling."
- lite: "Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead."
- full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead."
- ultra: "Pool = reuse DB conn. Skip handshake → fast under load."
- wenyan-full: "池reuse open connection。不每req新開。skip handshake overhead。"
- wenyan-ultra: "池reuse conn。skip handshake → fast。"
## Auto-Clarity
Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done.
Example — destructive op:
> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.
> ```sql
> DROP TABLE users;
> ```
> Caveman resume. Verify backup exist first.
## Boundaries
Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end.
@@ -0,0 +1,23 @@
---
name: check-compiler-errors
description: Run compile and type-check commands and report failures
---
# Check compiler errors
## Trigger
Compile or type-check failures are blocking local validation or CI.
## Workflow
1. Run the repo's compile and type-check commands.
2. Summarize errors by file and type.
3. Fix the highest-confidence issues first.
4. Re-run checks until clean or blocked.
## Output
- Current compile and type-check status
- Error summary grouped by file and category
- Fixes applied and remaining blockers
+87
View File
@@ -0,0 +1,87 @@
---
name: code-review
description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"."
---
Two-axis review of the diff between `HEAD` and a fixed point the user supplies:
- **Standards**: does the code conform to this repo's documented coding standards?
- **Spec**: does the code faithfully implement the originating issue / spec?
Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings.
The issue tracker should have been provided to you. If `docs/agents/issue-tracker.md` is missing, tell the user to run `/setup-matt-pocock-skills`.
## Process
### 1. Pin the fixed point
Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it.
Capture the diff command once: `git diff <fixed-point>...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log <fixed-point>..HEAD --oneline`.
Before going further, confirm the fixed point resolves (`git rev-parse <fixed-point>`) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents.
### 2. Identify the spec source
Look for the originating spec, in this order:
1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in `docs/agents/issue-tracker.md`.
2. A path the user passed as an argument.
3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature.
4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available".
### 3. Identify the standards sources
Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`.
On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it:
- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell.
- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces.
Each smell reads *what it is* → *how to fix*; match it against the diff:
- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky.
- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both.
- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies.
- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that.
- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type.
- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share.
- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module.
- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason.
- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows.
- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object.
- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct.
- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition.
### 4. Spawn both sub-agents in parallel
**Standards sub-agent prompt** should include:
- The full diff command and commit list.
- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it).
- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words."
**Spec sub-agent prompt** should include:
- The diff command and commit list.
- The path or fetched contents of the spec.
- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words."
If the spec is missing, skip the Spec sub-agent and note this in the final report.
### 5. Aggregate
Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_).
End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent.
## Why two axes
A change can pass one axis and fail the other:
- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.**
- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.**
Reporting them separately stops one axis from masking the other.
@@ -0,0 +1,3 @@
interface:
display_name: "Code Review"
short_description: "Review a diff on standards and spec"
@@ -1,6 +1,6 @@
# Deepening
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**.
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**.
## Dependency categories
@@ -8,7 +8,7 @@ When assessing a candidate for deepening, classify its dependencies. The categor
### 1. In-process
Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed.
Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed.
### 2. Local-substitutable
@@ -31,7 +31,7 @@ Third-party services (Stripe, Twilio, etc.) you don't control. The deepened modu
## Testing strategy: replace, don't layer
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them.
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them.
- Write new tests at the deepened module's interface. The **interface is the test surface**.
- Tests assert on observable outcomes through the interface, not internal state.
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
@@ -1,8 +1,8 @@
# Interface Design
# Design It Twice
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best.
Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**.
Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**.
## Process
@@ -12,33 +12,33 @@ Before spawning sub-agents, write a user-facing explanation of the problem space
- The constraints any new interface would need to satisfy
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete
- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
### 2. Spawn sub-agents
Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module.
Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module.
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point."
- Agent 2: "Maximise flexibility — support many use cases and extension."
- Agent 3: "Optimise for the most common caller — make the default case trivial."
- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point."
- Agent 2: "Maximise flexibility: support many use cases and extension."
- Agent 3: "Optimise for the most common caller: make the default case trivial."
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
Each sub-agent outputs:
1. Interface (types, methods, params — plus invariants, ordering, error modes)
1. Interface (types, methods, params, plus invariants, ordering, error modes)
2. Usage example showing how callers use it
3. What the implementation hides behind the seam
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
5. Trade-offs — where leverage is high, where it's thin
5. Trade-offs: where leverage is high, where it's thin
### 3. Present and compare
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu.
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu.
+114
View File
@@ -0,0 +1,114 @@
---
name: codebase-design
description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
---
# Codebase Design
Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.
## Glossary
Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.
**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface).
**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.
**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).
**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests.
**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.
## Deep vs shallow
**Deep module** = small interface + lots of implementation:
```
┌─────────────────────┐
│ Small Interface │ ← Few methods, simple params
├─────────────────────┤
│ │
│ Deep Implementation│ ← Complex logic hidden
│ │
└─────────────────────┘
```
**Shallow module** = large interface + little implementation (avoid):
```
┌─────────────────────────────────┐
│ Large Interface │ ← Many methods, complex params
├─────────────────────────────────┤
│ Thin Implementation │ ← Just passes through
└─────────────────────────────────┘
```
When designing an interface, ask:
- Can I reduce the number of methods?
- Can I simplify the parameters?
- Can I hide more complexity inside?
## Principles
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
## Designing for testability
Good interfaces make testing natural:
1. **Accept dependencies, don't create them.**
```typescript
// Testable
function processOrder(order, paymentGateway) {}
// Hard to test
function processOrder(order) {
const gateway = new StripeGateway();
}
```
2. **Return results, don't produce side effects.**
```typescript
// Testable
function calculateDiscount(cart): Discount {}
// Hard to test
function applyDiscount(cart): void {
cart.total -= discount;
}
```
3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup.
## Relationships
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
- **Depth** is a property of a **Module**, measured against its **Interface**.
- A **Seam** is where a **Module**'s **Interface** lives.
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
## Rejected framings
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know.
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
## Going deeper
- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing.
- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement.
@@ -0,0 +1,3 @@
interface:
display_name: "Codebase Design"
short_description: "Vocabulary for deep-module design"
-111
View File
@@ -1,111 +0,0 @@
---
name: compress
description: >
Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
to save input tokens. Preserves all technical substance, code, URLs, and structure.
Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
Trigger: /caveman:compress FILEPATH or "compress memory file"
---
# Caveman Compress
## Purpose
Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
## Trigger
`/caveman:compress <filepath>` or when user asks to compress a memory file.
## Process
1. This SKILL.md lives alongside `scripts/` in the same directory. Find that directory.
2. Run:
cd <directory_containing_this_SKILL.md> && python3 -m scripts <absolute_filepath>
3. The CLI will:
- detect file type (no tokens)
- call Claude to compress
- validate output (no tokens)
- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
- retry up to 2 times
- if still failing after 2 retries: report error to user, leave original file untouched
4. Return result to user
## Compression Rules
### Remove
- Articles: a, an, the
- Filler: just, really, basically, actually, simply, essentially, generally
- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
- Hedging: "it might be worth", "you could consider", "it would be good to"
- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
- Connective fluff: "however", "furthermore", "additionally", "in addition"
### Preserve EXACTLY (never modify)
- Code blocks (fenced ``` and indented)
- Inline code (`backtick content`)
- URLs and links (full URLs, markdown links)
- File paths (`/src/components/...`, `./config.yaml`)
- Commands (`npm install`, `git commit`, `docker build`)
- Technical terms (library names, API names, protocols, algorithms)
- Proper nouns (project names, people, companies)
- Dates, version numbers, numeric values
- Environment variables (`$HOME`, `NODE_ENV`)
### Preserve Structure
- All markdown headings (keep exact heading text, compress body below)
- Bullet point hierarchy (keep nesting level)
- Numbered lists (keep numbering)
- Tables (compress cell text, keep structure)
- Frontmatter/YAML headers in markdown files
### Compress
- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
- Fragments OK: "Run tests before commit" not "You should always run tests before committing"
- Drop "you should", "make sure to", "remember to" — just state the action
- Merge redundant bullets that say the same thing differently
- Keep one example where multiple examples show the same pattern
CRITICAL RULE:
Anything inside ``` ... ``` must be copied EXACTLY.
Do not:
- remove comments
- remove spacing
- reorder lines
- shorten commands
- simplify anything
Inline code (`...`) must be preserved EXACTLY.
Do not modify anything inside backticks.
If file contains code blocks:
- Treat code blocks as read-only regions
- Only compress text outside them
- Do not merge sections around code
## Pattern
Original:
> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
Compressed:
> Run tests before push to main. Catch bugs early, prevent broken prod deploys.
Original:
> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
Compressed:
> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
## Boundaries
- ONLY compress natural language files (.md, .txt, .typ, .typst, .tex, extensionless)
- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
- If file has mixed content (prose + code), compress ONLY the prose sections
- If unsure whether something is code or prose, leave it unchanged
- Original file is backed up as FILE.original.md before overwriting
- Never compress FILE.original.md (skip it)
@@ -1,9 +0,0 @@
"""Caveman compress scripts.
This package provides tools to compress natural language markdown files
into caveman format to save input tokens.
"""
__all__ = ["cli", "compress", "detect", "validate"]
__version__ = "1.0.0"
@@ -1,3 +0,0 @@
from .cli import main
main()
@@ -1,78 +0,0 @@
#!/usr/bin/env python3
from pathlib import Path
import sys
# Support both direct execution and module import
try:
from .validate import validate
except ImportError:
sys.path.insert(0, str(Path(__file__).parent))
from validate import validate
try:
import tiktoken
_enc = tiktoken.get_encoding("o200k_base")
except ImportError:
_enc = None
def count_tokens(text):
if _enc is None:
return len(text.split()) # fallback: word count
return len(_enc.encode(text))
def benchmark_pair(orig_path: Path, comp_path: Path):
orig_text = orig_path.read_text()
comp_text = comp_path.read_text()
orig_tokens = count_tokens(orig_text)
comp_tokens = count_tokens(comp_text)
saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0
result = validate(orig_path, comp_path)
return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid)
def print_table(rows):
print("\n| File | Original | Compressed | Saved % | Valid |")
print("|------|----------|------------|---------|-------|")
for r in rows:
print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |")
def main():
# Direct file pair: python3 benchmark.py original.md compressed.md
if len(sys.argv) == 3:
orig = Path(sys.argv[1]).resolve()
comp = Path(sys.argv[2]).resolve()
if not orig.exists():
print(f"❌ Not found: {orig}")
sys.exit(1)
if not comp.exists():
print(f"❌ Not found: {comp}")
sys.exit(1)
print_table([benchmark_pair(orig, comp)])
return
# Glob mode: repo_root/tests/caveman-compress/
tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress"
if not tests_dir.exists():
print(f"❌ Tests dir not found: {tests_dir}")
sys.exit(1)
rows = []
for orig in sorted(tests_dir.glob("*.original.md")):
comp = orig.with_name(orig.stem.removesuffix(".original") + ".md")
if comp.exists():
rows.append(benchmark_pair(orig, comp))
if not rows:
print("No compressed file pairs found.")
return
print_table(rows)
if __name__ == "__main__":
main()
-85
View File
@@ -1,85 +0,0 @@
#!/usr/bin/env python3
"""
Caveman Compress CLI
Usage:
caveman <filepath>
"""
import sys
# Force UTF-8 on stdout/stderr before any code can print. Windows consoles
# default to cp1252 and crash on the ❌ glyphs in error/validation branches,
# masking the real error and leaving the user with a half-compressed file.
for _stream in (sys.stdout, sys.stderr):
reconfigure = getattr(_stream, "reconfigure", None)
if callable(reconfigure):
try:
reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
from pathlib import Path
from .compress import compress_file
from .detect import detect_file_type, should_compress
def print_usage():
print("Usage: caveman <filepath>")
def main():
if len(sys.argv) != 2:
print_usage()
sys.exit(1)
filepath = Path(sys.argv[1])
# Check file exists
if not filepath.exists():
print(f"❌ File not found: {filepath}")
sys.exit(1)
if not filepath.is_file():
print(f"❌ Not a file: {filepath}")
sys.exit(1)
filepath = filepath.resolve()
# Detect file type
file_type = detect_file_type(filepath)
print(f"Detected: {file_type}")
# Check if compressible
if not should_compress(filepath):
print("Skipping: file is not natural language (code/config)")
sys.exit(0)
print("Starting caveman compression...\n")
try:
success = compress_file(filepath)
if success:
print("\nCompression completed successfully")
backup_path = filepath.with_name(filepath.stem + ".original.md")
print(f"Compressed: {filepath}")
print(f"Original: {backup_path}")
sys.exit(0)
else:
print("\n❌ Compression failed after retries")
sys.exit(2)
except KeyboardInterrupt:
print("\nInterrupted by user")
sys.exit(130)
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
-254
View File
@@ -1,254 +0,0 @@
#!/usr/bin/env python3
"""
Caveman Memory Compression Orchestrator
Usage:
python scripts/compress.py <filepath>
"""
import os
import re
import subprocess
from pathlib import Path
from typing import List
OUTER_FENCE_REGEX = re.compile(
r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL
)
# Filenames and paths that almost certainly hold secrets or PII. Compressing
# them ships raw bytes to the Anthropic API — a third-party data boundary that
# developers on sensitive codebases cannot cross. detect.py already skips .env
# by extension, but credentials.md / secrets.txt / ~/.aws/credentials would
# slip through the natural-language filter. This is a hard refuse before read.
SENSITIVE_BASENAME_REGEX = re.compile(
r"(?ix)^("
r"\.env(\..+)?"
r"|\.netrc"
r"|credentials(\..+)?"
r"|secrets?(\..+)?"
r"|passwords?(\..+)?"
r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?"
r"|authorized_keys"
r"|known_hosts"
r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)"
r")$"
)
SENSITIVE_PATH_COMPONENTS = frozenset({".ssh", ".aws", ".gnupg", ".kube", ".docker"})
SENSITIVE_NAME_TOKENS = (
"secret", "credential", "password", "passwd",
"apikey", "accesskey", "token", "privatekey",
)
def is_sensitive_path(filepath: Path) -> bool:
"""Heuristic denylist for files that must never be shipped to a third-party API."""
name = filepath.name
if SENSITIVE_BASENAME_REGEX.match(name):
return True
lowered_parts = {p.lower() for p in filepath.parts}
if lowered_parts & SENSITIVE_PATH_COMPONENTS:
return True
# Normalize separators so "api-key" and "api_key" both match "apikey".
lower = re.sub(r"[_\-\s.]", "", name.lower())
return any(tok in lower for tok in SENSITIVE_NAME_TOKENS)
def strip_llm_wrapper(text: str) -> str:
"""Strip outer ```markdown ... ``` fence when it wraps the entire output."""
m = OUTER_FENCE_REGEX.match(text)
if m:
return m.group(2)
return text
from .detect import should_compress
from .validate import validate
MAX_RETRIES = 2
# ---------- Claude Calls ----------
def call_claude(prompt: str) -> str:
api_key = os.environ.get("ANTHROPIC_API_KEY")
if api_key:
try:
import anthropic
client = anthropic.Anthropic(api_key=api_key)
msg = client.messages.create(
model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"),
max_tokens=8192,
messages=[{"role": "user", "content": prompt}],
)
return strip_llm_wrapper(msg.content[0].text.strip())
except ImportError:
pass # anthropic not installed, fall back to CLI
# Fallback: use claude CLI (handles desktop auth)
try:
result = subprocess.run(
["claude", "--print"],
input=prompt,
text=True,
capture_output=True,
check=True,
)
return strip_llm_wrapper(result.stdout.strip())
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Claude call failed:\n{e.stderr}")
def build_compress_prompt(original: str) -> str:
return f"""
Compress this markdown into caveman format.
STRICT RULES:
- Do NOT modify anything inside ``` code blocks
- Do NOT modify anything inside inline backticks
- Preserve ALL URLs exactly
- Preserve ALL headings exactly
- Preserve file paths and commands
- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file.
Only compress natural language.
TEXT:
{original}
"""
def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str:
errors_str = "\n".join(f"- {e}" for e in errors)
return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found.
CRITICAL RULES:
- DO NOT recompress or rephrase the file
- ONLY fix the listed errors — leave everything else exactly as-is
- The ORIGINAL is provided as reference only (to restore missing content)
- Preserve caveman style in all untouched sections
ERRORS TO FIX:
{errors_str}
HOW TO FIX:
- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED
- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED
- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED
- Do not touch any section not mentioned in the errors
ORIGINAL (reference only):
{original}
COMPRESSED (fix this):
{compressed}
Return ONLY the fixed compressed file. No explanation.
"""
# ---------- Core Logic ----------
def compress_file(filepath: Path) -> bool:
# Resolve and validate path
filepath = filepath.resolve()
MAX_FILE_SIZE = 500_000 # 500KB
if not filepath.exists():
raise FileNotFoundError(f"File not found: {filepath}")
if filepath.stat().st_size > MAX_FILE_SIZE:
raise ValueError(f"File too large to compress safely (max 500KB): {filepath}")
# Refuse files that look like they contain secrets or PII. Compressing ships
# the raw bytes to the Anthropic API — a third-party boundary — so we fail
# loudly rather than silently exfiltrate credentials or keys. Override is
# intentional: the user must rename the file if the heuristic is wrong.
if is_sensitive_path(filepath):
raise ValueError(
f"Refusing to compress {filepath}: filename looks sensitive "
"(credentials, keys, secrets, or known private paths). "
"Compression sends file contents to the Anthropic API. "
"Rename the file if this is a false positive."
)
print(f"Processing: {filepath}")
if not should_compress(filepath):
print("Skipping (not natural language)")
return False
original_text = filepath.read_text(errors="ignore")
backup_path = filepath.with_name(filepath.stem + ".original.md")
if not original_text.strip():
print("❌ Refusing to compress: file is empty or whitespace-only.")
return False
# Check if backup already exists to prevent accidental overwriting
if backup_path.exists():
print(f"⚠️ Backup file already exists: {backup_path}")
print("The original backup may contain important content.")
print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.")
return False
# Step 1: Compress
print("Compressing with Claude...")
compressed = call_claude(build_compress_prompt(original_text))
if compressed is None or not compressed.strip():
print("❌ Compression aborted: Claude returned an empty response.")
print(" Original file is untouched (no backup created).")
return False
if compressed.strip() == original_text.strip():
print("❌ Compression aborted: output is identical to input.")
print(" Likely causes: Claude refused, returned the prompt verbatim, or the file is")
print(" already in caveman form. Original file is untouched (no backup created).")
return False
# Save original as backup, then verify the backup readback before
# touching the input file. If the filesystem dropped bytes (encoding,
# antivirus, disk full), unlink the bad backup and abort instead of
# leaving the user with a corrupt backup + compressed primary.
backup_path.write_text(original_text)
backup_readback = backup_path.read_text(errors="ignore")
if backup_readback != original_text:
print(f"❌ Backup write verification failed: {backup_path}")
print(" In-memory original differs from on-disk backup. Aborting before touching the input file.")
try:
backup_path.unlink()
except OSError:
pass
return False
filepath.write_text(compressed)
# Step 2: Validate + Retry
for attempt in range(MAX_RETRIES):
print(f"\nValidation attempt {attempt + 1}")
result = validate(backup_path, filepath)
if result.is_valid:
print("Validation passed")
break
print("❌ Validation failed:")
for err in result.errors:
print(f" - {err}")
if attempt == MAX_RETRIES - 1:
# Restore original on failure
filepath.write_text(original_text)
backup_path.unlink(missing_ok=True)
print("❌ Failed after retries — original restored")
return False
print("Fixing with Claude...")
compressed = call_claude(
build_fix_prompt(original_text, compressed, result.errors)
)
filepath.write_text(compressed)
return True
-121
View File
@@ -1,121 +0,0 @@
#!/usr/bin/env python3
"""Detect whether a file is natural language (compressible) or code/config (skip)."""
import json
import re
from pathlib import Path
# Extensions that are natural language and compressible
COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"}
# Extensions that are code/config and should be skipped
SKIP_EXTENSIONS = {
".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml",
".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml",
".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c",
".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua",
".dockerfile", ".makefile", ".csv", ".ini", ".cfg",
}
# Patterns that indicate a line is code
CODE_PATTERNS = [
re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"),
re.compile(r"^\s*(def |class |function |async function |export )"),
re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"),
re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets
re.compile(r"^\s*@\w+"), # decorators/annotations
re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value
re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal
]
def _is_code_line(line: str) -> bool:
"""Check if a line looks like code."""
return any(p.match(line) for p in CODE_PATTERNS)
def _is_json_content(text: str) -> bool:
"""Check if content is valid JSON."""
try:
json.loads(text)
return True
except (json.JSONDecodeError, ValueError):
return False
def _is_yaml_content(lines: list[str]) -> bool:
"""Heuristic: check if content looks like YAML."""
yaml_indicators = 0
for line in lines[:30]:
stripped = line.strip()
if stripped.startswith("---"):
yaml_indicators += 1
elif re.match(r"^\w[\w\s]*:\s", stripped):
yaml_indicators += 1
elif stripped.startswith("- ") and ":" in stripped:
yaml_indicators += 1
# If most non-empty lines look like YAML
non_empty = sum(1 for l in lines[:30] if l.strip())
return non_empty > 0 and yaml_indicators / non_empty > 0.6
def detect_file_type(filepath: Path) -> str:
"""Classify a file as 'natural_language', 'code', 'config', or 'unknown'.
Returns:
One of: 'natural_language', 'code', 'config', 'unknown'
"""
ext = filepath.suffix.lower()
# Extension-based classification
if ext in COMPRESSIBLE_EXTENSIONS:
return "natural_language"
if ext in SKIP_EXTENSIONS:
return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config"
# Extensionless files (like CLAUDE.md, TODO) — check content
if not ext:
try:
text = filepath.read_text(errors="ignore")
except (OSError, PermissionError):
return "unknown"
lines = text.splitlines()[:50]
if _is_json_content(text[:10000]):
return "config"
if _is_yaml_content(lines):
return "config"
code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l))
non_empty = sum(1 for l in lines if l.strip())
if non_empty > 0 and code_lines / non_empty > 0.4:
return "code"
return "natural_language"
return "unknown"
def should_compress(filepath: Path) -> bool:
"""Return True if the file is natural language and should be compressed."""
if not filepath.is_file():
return False
# Skip backup files
if filepath.name.endswith(".original.md"):
return False
return detect_file_type(filepath) == "natural_language"
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python detect.py <file1> [file2] ...")
sys.exit(1)
for path_str in sys.argv[1:]:
p = Path(path_str).resolve()
file_type = detect_file_type(p)
compress = should_compress(p)
print(f" {p.name:30s} type={file_type:20s} compress={compress}")
-213
View File
@@ -1,213 +0,0 @@
#!/usr/bin/env python3
import re
from collections import Counter
from pathlib import Path
URL_REGEX = re.compile(r"https?://[^\s)]+")
FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$")
HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE)
BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE)
# crude but effective path detection
# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match
PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+")
class ValidationResult:
def __init__(self):
self.is_valid = True
self.errors = []
self.warnings = []
def add_error(self, msg):
self.is_valid = False
self.errors.append(msg)
def add_warning(self, msg):
self.warnings.append(msg)
def read_file(path: Path) -> str:
return path.read_text(errors="ignore")
# ---------- Extractors ----------
def extract_headings(text):
return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)]
def extract_code_blocks(text):
"""Line-based fenced code block extractor.
Handles ``` and ~~~ fences with variable length (CommonMark: closing
fence must use same char and be at least as long as opening). Supports
nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick
content).
"""
blocks = []
lines = text.split("\n")
i = 0
n = len(lines)
while i < n:
m = FENCE_OPEN_REGEX.match(lines[i])
if not m:
i += 1
continue
fence_char = m.group(2)[0]
fence_len = len(m.group(2))
open_line = lines[i]
block_lines = [open_line]
i += 1
closed = False
while i < n:
close_m = FENCE_OPEN_REGEX.match(lines[i])
if (
close_m
and close_m.group(2)[0] == fence_char
and len(close_m.group(2)) >= fence_len
and close_m.group(3).strip() == ""
):
block_lines.append(lines[i])
closed = True
i += 1
break
block_lines.append(lines[i])
i += 1
if closed:
blocks.append("\n".join(block_lines))
# Unclosed fences are silently skipped — they indicate malformed markdown
# and including them would cause false-positive validation failures.
return blocks
def extract_urls(text):
return set(URL_REGEX.findall(text))
def extract_paths(text):
return set(PATH_REGEX.findall(text))
def count_bullets(text):
return len(BULLET_REGEX.findall(text))
def extract_inline_codes(text):
text_without_fences = re.sub(r"^```[\s\S]*?^```", "", text, flags=re.MULTILINE)
text_without_fences = re.sub(r"^~~~[\s\S]*?^~~~", "", text_without_fences, flags=re.MULTILINE)
return re.findall(r"`([^`]+)`", text_without_fences)
# ---------- Validators ----------
def validate_headings(orig, comp, result):
h1 = extract_headings(orig)
h2 = extract_headings(comp)
if len(h1) != len(h2):
result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}")
if h1 != h2:
result.add_warning("Heading text/order changed")
def validate_code_blocks(orig, comp, result):
c1 = extract_code_blocks(orig)
c2 = extract_code_blocks(comp)
if c1 != c2:
result.add_error("Code blocks not preserved exactly")
def validate_urls(orig, comp, result):
u1 = extract_urls(orig)
u2 = extract_urls(comp)
if u1 != u2:
result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}")
def validate_paths(orig, comp, result):
p1 = extract_paths(orig)
p2 = extract_paths(comp)
if p1 != p2:
result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}")
def validate_bullets(orig, comp, result):
b1 = count_bullets(orig)
b2 = count_bullets(comp)
if b1 == 0:
return
diff = abs(b1 - b2) / b1
if diff > 0.15:
result.add_warning(f"Bullet count changed too much: {b1} -> {b2}")
def validate_inline_codes(orig, comp, result):
c1 = Counter(extract_inline_codes(orig))
c2 = Counter(extract_inline_codes(comp))
if c1 != c2:
lost = set(c1.keys()) - set(c2.keys())
added = set(c2.keys()) - set(c1.keys())
for code, count in c1.items():
if code in c2 and c2[code] < count:
lost.add(f"{code} (lost {count - c2[code]} of {count} occurrences)")
if lost:
result.add_error(f"Inline code lost: {lost}")
if added:
result.add_warning(f"Inline code added: {added}")
# ---------- Main ----------
def validate(original_path: Path, compressed_path: Path) -> ValidationResult:
result = ValidationResult()
orig = read_file(original_path)
comp = read_file(compressed_path)
validate_headings(orig, comp, result)
validate_code_blocks(orig, comp, result)
validate_urls(orig, comp, result)
validate_paths(orig, comp, result)
validate_bullets(orig, comp, result)
validate_inline_codes(orig, comp, result)
return result
# ---------- CLI ----------
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python validate.py <original> <compressed>")
sys.exit(1)
orig = Path(sys.argv[1]).resolve()
comp = Path(sys.argv[2]).resolve()
res = validate(orig, comp)
print(f"\nValid: {res.is_valid}")
if res.errors:
print("\nErrors:")
for e in res.errors:
print(f" - {e}")
if res.warnings:
print("\nWarnings:")
for w in res.warnings:
print(f" - {w}")
+24
View File
@@ -0,0 +1,24 @@
---
name: continual-learning
description: Orchestrate continual learning by delegating transcript mining and AGENTS.md updates to `agents-memory-updater`.
disable-model-invocation: true
---
# Continual Learning
Keep `AGENTS.md` current by delegating the memory update flow to one subagent.
## Trigger
Use when the user asks to mine prior chats, maintain `AGENTS.md`, or run the continual-learning loop.
## Workflow
1. Call `agents-memory-updater`.
2. Return the updater result.
## Guardrails
- Keep the parent skill orchestration-only.
- Do not mine transcripts or edit files in the parent flow.
- Do not bypass the subagent.
+22
View File
@@ -0,0 +1,22 @@
---
name: deslop
description: Remove AI-generated code slop and clean up code style
---
# Remove AI code slop
Check the diff against main and remove AI-generated slop introduced in the branch.
## Focus Areas
- Extra comments that are unnecessary or inconsistent with local style
- Defensive checks or try/catch blocks that are abnormal for trusted code paths
- Casts to `any` used only to bypass type issues
- Deeply nested code that should be simplified with early returns
- Other patterns inconsistent with the file and surrounding codebase
## Guardrails
- Keep behavior unchanged unless fixing a clear bug.
- Prefer minimal, focused edits over broad rewrites.
- Keep the final summary concise (1-3 sentences).
@@ -1,26 +1,32 @@
---
name: diagnose
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression.
name: diagnosing-bugs
description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
---
# Diagnose
# Diagnosing Bugs
A discipline for hard bugs. Skip phases only when explicitly justified.
When exploring the codebase, use the project's domain glossary to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
## Phase 1 — Build a feedback loop
## Redact
**This is the skill.** Everything else is mechanical. If you have a fast, deterministic, agent-runnable pass/fail signal for the bug, you will find the cause — bisection, hypothesis-testing, and instrumentation all just consume that signal. If you don't have one, no amount of staring at code will save you.
This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `<REDACTED>` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal.
If the redacted output is not enough to diagnose the bug, say so and ask the user.
## Phase 1: Build a feedback loop
**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you.
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
### Ways to construct one — try them in roughly this order
### Ways to construct one, in roughly this order
1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e.
1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e.
2. **Curl / HTTP script** against a running dev server.
3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot.
4. **Headless browser script** (Playwright / Puppeteer) — drives the UI, asserts on DOM/console/network.
4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network.
5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation.
6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call.
7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode.
@@ -30,39 +36,56 @@ Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give
Build the right feedback loop, and the bug is 90% fixed.
### Iterate on the loop itself
### Tighten the loop
Treat the loop as a product. Once you have _a_ loop, ask:
Treat the loop as a product. Once you have _a_ loop, **tighten** it:
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
A 30-second flaky loop is barely better than no loop. A 2-second deterministic loop is a debugging superpower.
A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower.
### Non-deterministic bugs
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable.
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable.
### When you genuinely cannot build a loop
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
Do not proceed to Phase 2 until you have a loop you believe in.
### Completion criterion: a tight loop that goes red
## Phase 2 — Reproduce
Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is:
Run the loop. Watch the bug appear.
- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_.
- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above).
- [ ] **Fast**: seconds, not minutes.
- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`.
If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2.
## Phase 2: Reproduce + minimise
Run the loop. Watch it go red as the bug appears.
Confirm:
- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix.
- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix.
- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against).
- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it.
Do not proceed until you reproduce the bug.
### Minimise
## Phase 3 — Hypothesise
Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure.
Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5.
Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green.
Do not proceed until you have reproduced **and** minimised.
## Phase 3: Hypothesise
Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
@@ -70,11 +93,11 @@ Each hypothesis must be **falsifiable**: state the prediction it makes.
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it.
If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it.
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK.
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK.
## Phase 4 — Instrument
## Phase 4: Instrument
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
@@ -88,9 +111,9 @@ Tool preference:
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
## Phase 5 — Fix + regression test
## Phase 5: Fix + regression test
Write the regression test **before the fix** — but only if there is a **correct seam** for it.
Write the regression test **before the fix**, but only if there is a **correct seam** for it.
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
@@ -104,7 +127,7 @@ If a correct seam exists:
4. Watch it pass.
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
## Phase 6 — Cleanup + post-mortem
## Phase 6: Cleanup
Required before declaring done:
@@ -112,6 +135,4 @@ Required before declaring done:
- [ ] Regression test passes (or absence of seam is documented)
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns
**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started.
- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns
@@ -0,0 +1,3 @@
interface:
display_name: "Diagnosing Bugs"
short_description: "Diagnose hard bugs and regressions"
@@ -11,6 +11,9 @@
# capture VAR "<question>" → show question, read response into VAR
#
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
#
# `capture` prints its value back to the terminal, where the agent reads it,
# so capture observations, and leave signing in to the user as a `step`.
set -euo pipefail
@@ -2,7 +2,7 @@
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
Create the `docs/adr/` directory lazily — only when the first ADR is needed.
Create the `docs/adr/` directory lazily: only when the first ADR is needed.
## Template
@@ -12,15 +12,15 @@ Create the `docs/adr/` directory lazily — only when the first ADR is needed.
{1-3 sentences: what's the context, what did we decide, and why.}
```
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.
## Optional sections
Only include these when they add genuine value. Most ADRs won't need them.
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
- **Considered Options** — only when the rejected alternatives are worth remembering
- **Consequences** — only when non-obvious downstream effects need to be called out
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited
- **Considered Options**: only when the rejected alternatives are worth remembering
- **Consequences**: only when non-obvious downstream effects need to be called out
## Numbering
@@ -30,18 +30,18 @@ Scan `docs/adr/` for the highest existing number and increment by one.
All three of these must be true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
1. **Hard to reverse**: the cost of changing your mind later is meaningful
2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?"
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
### What qualifies
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.
@@ -10,7 +10,7 @@
## Language
**Order**:
{A concise description of the term}
{A one or two sentence description of the term}
_Avoid_: Purchase, transaction
**Invoice**:
@@ -20,31 +20,14 @@ _Avoid_: Bill, payment request
**Customer**:
A person or organization that places orders.
_Avoid_: Client, buyer, account
## Relationships
- An **Order** produces one or more **Invoices**
- An **Invoice** belongs to exactly one **Customer**
## Example dialogue
> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed."
## Flagged ambiguities
- "account" was used to mean both **Customer** and **User** — resolved: these are distinct concepts.
```
## Rules
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
- **Flag conflicts explicitly.** If a term is used ambiguously, call it out in "Flagged ambiguities" with a clear resolution.
- **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
- **Show relationships.** Use bold term names and express cardinality where obvious.
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.
- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
- **Write an example dialogue.** A conversation between a dev and a domain expert that demonstrates how the terms interact naturally and clarifies boundaries between related concepts.
## Single vs multi-context repos
@@ -57,9 +40,9 @@ _Avoid_: Client, buyer, account
## Contexts
- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders
- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments
- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping
- [Ordering](./src/ordering/CONTEXT.md): receives and tracks customer orders
- [Billing](./src/billing/CONTEXT.md): generates invoices and processes payments
- [Fulfillment](./src/fulfillment/CONTEXT.md): manages warehouse picking and shipping
## Relationships
+74
View File
@@ -0,0 +1,74 @@
---
name: domain-modeling
description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a CONTEXT.md, or recording or editing an ADR.
---
# Domain Modeling
Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)
## File structure
Most repos have a single context:
```
/
├── CONTEXT.md
├── docs/
│ └── adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
```
/
├── CONTEXT-MAP.md
├── docs/
│ └── adr/ ← system-wide decisions
├── src/
│ ├── ordering/
│ │ ├── CONTEXT.md
│ │ └── docs/adr/ ← context-specific decisions
│ └── billing/
│ ├── CONTEXT.md
│ └── docs/adr/
```
Create files lazily: only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
## During the session
### Challenge against the glossary
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?"
### Sharpen fuzzy language
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things."
### Discuss concrete scenarios
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
### Cross-reference with code
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?"
### Update CONTEXT.md inline
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up: capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
### Offer ADRs sparingly
Only offer to create an ADR when all three are true:
1. **Hard to reverse**: the cost of changing your mind later is meaningful
2. **Surprising without context**: a future reader will wonder "why did they do it this way?"
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
@@ -0,0 +1,3 @@
interface:
display_name: "Domain Modeling"
short_description: "Build and sharpen a domain model"
+2 -3
View File
@@ -24,9 +24,8 @@ The Skills CLI (`npx skills`) is the package manager for the open agent skills e
**Key commands:**
- `npx skills find [query]` - Search for skills interactively or by keyword
- `npx skills find [query] [--owner <owner>]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner
- `npx skills add <package>` - Install a skill from GitHub or other sources
- `npx skills check` - Check for skill updates
- `npx skills update` - Update all installed skills
**Browse skills at:** https://skills.sh/
@@ -54,7 +53,7 @@ For example, top skills for web development include:
If the leaderboard doesn't cover the user's need, run the find command:
```bash
npx skills find [query]
npx skills find [query] [--owner <owner>]
```
For example:
-1
View File
@@ -1 +0,0 @@
0.7.13
File diff suppressed because it is too large. Load diff
+3 -6
View File
@@ -1,10 +1,7 @@
---
name: grill-me
description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
description: A relentless interview to sharpen a plan or design.
disable-model-invocation: true
---
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time.
If a question can be answered by exploring the codebase, explore the codebase instead.
Call the Skill tool with "grilling".
@@ -0,0 +1,5 @@
interface:
display_name: "Grill Me"
short_description: "Sharpen a plan through interview"
policy:
allow_implicit_invocation: false
+3 -84
View File
@@ -1,88 +1,7 @@
---
name: grill-with-docs
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
disable-model-invocation: true
---
<what-to-do>
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time, waiting for feedback on each question before continuing.
If a question can be answered by exploring the codebase, explore the codebase instead.
</what-to-do>
<supporting-info>
## Domain awareness
During codebase exploration, also look for existing documentation:
### File structure
Most repos have a single context:
```
/
├── CONTEXT.md
├── docs/
│ └── adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
```
/
├── CONTEXT-MAP.md
├── docs/
│ └── adr/ ← system-wide decisions
├── src/
│ ├── ordering/
│ │ ├── CONTEXT.md
│ │ └── docs/adr/ ← context-specific decisions
│ └── billing/
│ ├── CONTEXT.md
│ └── docs/adr/
```
Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
## During the session
### Challenge against the glossary
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
### Sharpen fuzzy language
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
### Discuss concrete scenarios
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
### Cross-reference with code
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
### Update CONTEXT.md inline
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts.
### Offer ADRs sparingly
Only offer to create an ADR when all three are true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
</supporting-info>
Call the Skill tool twice, for "grilling" and "domain-modeling".
@@ -0,0 +1,5 @@
interface:
display_name: "Grill with Docs"
short_description: "Grill a design and write its docs"
policy:
allow_implicit_invocation: false
+28
View File
@@ -0,0 +1,28 @@
---
name: grilling
description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
---
Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it.
Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round.
Format a round like so:
```
❓ **Q1** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
➡️ <your recommended answer>
---
❓ **Q2** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
➡️ <your recommended answer>
```
Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one.
Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait.
The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding.
@@ -0,0 +1,3 @@
interface:
display_name: "Grilling"
short_description: "Stress-test thinking a round of questions at a time"
+134
View File
@@ -0,0 +1,134 @@
---
name: how
description: "Use for \"how does X work\", code walkthroughs before changing something, and placement / ownership / layering questions (\"where should this live\", \"which package owns this\", \"is this the right layer\"). Explains subsystem architecture, runtime flow, onboarding mental models. Can critique architecture. Use why for motivation."
---
# How
Explore the codebase to answer "how does X work?" questions. Produce clear architectural explanations at the level of a senior engineer onboarding onto a subsystem. Enough to build a working mental model, not annotated source code.
Two modes:
1. **Explain** (default). Explore the codebase and produce a clear explanation
2. **Critique.** Explain first, then spawn multiple models to independently identify architectural issues
## Explain Mode
### Step 1. Understand the Question and Assess Complexity
Parse what the user is asking about:
- "How does the rate limiter work?", a subsystem
- "How do we handle billing for on-demand usage?", a feature flow
- "How is the auth service structured?", an architectural overview
- "Walk me through what happens when a user submits a form", a runtime trace
Identify the scope. If ambiguous, state your best-guess interpretation before exploring. Don't ask. Let the user redirect if you're off.
**Assess complexity to decide the approach:**
- **Simple** (a single module, a small utility, a narrow question like "how does function X work"): skip explorer agents; the explainer explores and explains in a single pass. Go to Step 2b.
- **Complex** (a subsystem spanning multiple files/services, a cross-cutting feature, a full architectural overview): spawn parallel explorer agents first, then hand off to the explainer. Go to Step 2a.
When in doubt, lean simple. You can always spawn explorers if the explainer hits a wall.
### Step 2a. Explore (complex questions only)
Decompose the question into 2-4 parallel exploration angles, each a distinct slice of the subsystem so explorers don't duplicate work. Example split for "how does the rate limiter work?":
- Explorer 1: data model and state management
- Explorer 2: request path and enforcement
- Explorer 3: configuration and metrics infrastructure
The right decomposition depends on the question. Use your judgment. Narrow questions: 2 explorers is fine. Broad subsystems: up to 4.
Spawn all explorers in a single message:
- `subagent_type`: `generalPurpose`
- `model`: your configured how-explorer model (default `grok-4.6-fast-xhigh`)
- `readonly`: `true`
Each explorer gets the same base prompt from `references/explorer-prompt.md` plus a specific exploration angle naming its slice. Each explorer should:
- Start broad: Glob for relevant directories, Grep for key types/interfaces/class names
- Follow the thread: from an entry point, trace the call chain (callers, callees, data flow, type definitions)
- Read the actual code, don't guess from file names
- Stop when it can describe the full path from input to output (or trigger to effect) without hand-waving any step
- Note things that are surprising, non-obvious, or that a newcomer would get wrong
Each explorer returns structured findings: components found, flow traced, files read, anything non-obvious. Overlap between explorers is fine; the explainer reconciles.
Then proceed to Step 3.
### Step 2b. Direct Explain (simple questions)
Spawn a single Task subagent that explores and explains in one pass:
- `subagent_type`: `generalPurpose`
- `model`: your configured how-explainer model (default `claude-fable-5-thinking-max`)
- `readonly`: `true`
The agent does its own exploration (Glob, Grep, Read) and writes the explanation directly. Read `references/explainer-prompt.md` for the communication style and output format. Same structure, just no explorer findings as input.
Proceed to Step 4.
### Step 3. Synthesize (complex questions only)
Once all explorers return, spawn a single Task subagent to synthesize their findings into one coherent explanation:
- `subagent_type`: `generalPurpose`
- `model`: your configured how-explainer model (default `claude-fable-5-thinking-max`)
- `readonly`: `true`
The explainer gets all explorers' findings and writes the human-facing explanation (output format below). Read `references/explainer-prompt.md` for the full prompt template. The explainer reconciles overlapping findings, resolves contradictions, and weaves the slices into a unified picture.
### Step 4. Present
Present the explainer's output to the user. You may lightly edit for clarity or add context from the conversation, but don't substantially rewrite. The explainer's communication is the product.
### Output Format
Follow this structure, adapted to the question. Not every section is needed for every question.
**Overview.** 1-2 paragraphs. What it is, what it does, why it exists. Enough to decide whether to keep reading.
**Key Concepts.** The important types, services, or abstractions. Brief definition of each. Not exhaustive, just the ones needed to understand the rest.
**How It Works.** The core of the explanation. Walk through the flow: what triggers it, what happens step by step, where data goes, the decision points. Prose, not pseudocode. Reference specific files and functions so the reader can go look, but don't dump code blocks unless a snippet is genuinely necessary.
**Where Things Live.** A brief map of the relevant files/directories. Not every file, just the ones needed to start working in this area.
**Gotchas.** Non-obvious or surprising things that would trip someone up. Historical context that explains why something looks weird. Known sharp edges.
## Critique Mode
Triggered when the user asks for architectural issues, problems, or improvements, not just understanding.
### Step 1. Explain First
Run the full explain flow above (Steps 1-4). You must understand the architecture before critiquing it.
### Step 2. Spawn Critics
After the explanation is complete, spawn one architectural critic per model in your configured how-critics list (defaults `claude-fable-5-thinking-max`, `gpt-5.6-sol-max`, `grok-4.6-fast-xhigh`, `claude-opus-5-thinking-xhigh`), all in a single message.
For each critic:
- `subagent_type`: `generalPurpose`
- `model`: one model from the configured how-critics list. These are minimum reasoning levels. The lead should escalate any model when the architecture warrants deeper analysis.
- `readonly`: `true`
Read `references/critic-prompt.md` for the prompt template. Each critic gets:
1. The explanation from Step 1 (so they don't re-explore)
2. The relevant file paths (so they can read the actual code)
3. The architectural critique rubric from `references/critique-rubric.md`
### Step 3. Lead Judgment
Same framework as the interrogate skill. You're a pragmatic lead, not an aggregator.
Categorize findings:
- **Act on.** Architectural problems worth fixing now
- **Consider.** Real concerns, but the cost/benefit is unclear
- **Noted.** Valid observations, low priority
- **Dismissed.** Wrong, missing context, or style preference
Present the explanation first (from Step 1), then the critique verdict below it. The explanation should stand on its own; someone who just wants to understand the system shouldn't wade through critique.
@@ -0,0 +1,59 @@
# Critic Prompt Template
Build each critic subagent's prompt from this template. Fill in the placeholders.
---
You are reviewing the architecture of a codebase subsystem. An explanation of how it works has already been written. Read it to orient yourself, then read the actual code to form your own judgment.
## Architectural Explanation
{EXPLANATION}
## Relevant Files
{FILE_PATHS}
## Critique Rubric
{CRITIQUE_RUBRIC_CONTENTS}
## Instructions
Read the files listed above. Use the explanation as a map, but form your own opinions from the code itself. The explanation might miss things or frame them charitably.
Find architectural problems, not line-level bugs or style issues. Ask whether this subsystem is built well for what it needs to do and how it will need to evolve.
For each finding:
1. **Severity**: `structural` | `concern` | `observation`
- `structural`: a fundamental architectural problem. Wrong abstraction boundary, broken data model, coupling that will block future work
- `concern`: a real issue that makes the system harder to work with or reason about, but not fundamentally broken
- `observation`: worth noting. A tradeoff that might not age well, a pattern inconsistent with the rest of the codebase, technical debt
2. **Finding**: the architectural issue. Be specific. Name the components, the boundary, the coupling.
3. **Evidence**: concrete code that demonstrates the problem. Don't just assert that "this is too coupled". Show the dependency chain.
4. **Impact**: what the issue costs. Harder to test? Harder to change? Performance cliff at scale? Be concrete about the consequence.
## What to Avoid
- Line-level code review (not your job here)
- Suggesting rewrites without demonstrating a problem with the current approach
- "This could use more abstraction" without showing what the abstraction would actually solve
- Flagging intentional tradeoffs with clear benefits as issues
If the architecture is sound, say so. An empty critique is a valid outcome.
## Output
```
## Findings
### 1. [Severity] Short title
**Components**: Which parts of the system are involved
**Finding**: What's wrong architecturally
**Evidence**: Concrete code references
**Impact**: What this costs in practice
### 2. [Severity] Short title
...
```
@@ -0,0 +1,58 @@
# Architectural Critique Rubric
Review through whichever of these lenses are relevant. Not every lens applies to every subsystem.
## Abstraction Fit
Are the abstractions pulling their weight?
- Does each abstraction represent a real concept, or is it an indirection layer "in case we need it"?
- Are the boundaries in the right place? Do they separate things that change independently?
- Is there accidental coupling where components share implementation details they shouldn't need to know about?
- Is business logic entangled with framework wiring, or cleanly separated?
Over-abstraction is as much a problem as under-abstraction. A flat, simple design is fine when the domain is simple.
## Data Model
Do the data structures fit the actual usage patterns?
- Are the data models designed for how data is actually accessed, or for how it was conceptually modeled?
- Are there impedance mismatches, places where code constantly reshapes data because the model doesn't match the access pattern?
- Are types honest? Do they represent what data actually looks like at runtime, or claim more structure than exists?
## Boundary Discipline
Are system boundaries clean and well-placed?
- Is validation concentrated at entry points, or scattered through internal code?
- Are errors handled at boundaries and propagated cleanly, or caught and re-thrown at every layer?
- Does data cross boundaries in well-typed shapes, or as bags of optional fields?
- Could this subsystem be tested in isolation, or does it require the entire system to be running?
## Evolution Readiness
How well will this architecture handle likely changes?
- If the most probable next requirement landed tomorrow, how much would change? "One file" or "everything"?
- Are there hardcoded assumptions that would need to be relaxed?
- Is the design bolted-on (integrated as an afterthought) or integrated (looks like it was always part of the plan)?
- Are legacy paths preserved for compatibility that no one depends on?
Don't penalize for not handling hypothetical changes. Focus on changes plausible given the codebase's trajectory.
## Complexity vs. Value
Is the complexity budget spent wisely?
- Is complexity concentrated in the parts that need it (core logic, tricky invariants) or in accidental places (boilerplate, unnecessary indirection, configuration)?
- Are there simpler ways to achieve the same behavior?
- Does every component earn its existence, or are there vestigial pieces from an earlier design?
## Consistency
Does this subsystem follow the patterns established elsewhere in the codebase?
- Are similar problems solved the same way here as elsewhere, or does this area invent its own patterns?
- If the patterns differ, is there a good reason, or did it just evolve independently?
- Inconsistency isn't automatically bad. But unexplained inconsistency is a maintenance burden.
@@ -0,0 +1,55 @@
# Explainer Prompt Template
Build the explainer subagent's prompt from this template. Fill in the placeholders.
---
You are writing an architectural explanation for a senior engineer. Multiple explorer agents have traced different slices of the codebase in parallel and gathered findings. Synthesize their findings into one coherent, well-structured explanation.
## Original Question
> {QUESTION}
## Explorer Findings
{EXPLORER_FINDINGS_ALL}
## Instructions
The explorers each investigated a different angle of the same subsystem. Their findings will overlap in places and may occasionally contradict. Reconcile them. Merge overlapping descriptions, resolve contradictions by checking the code yourself, and weave the separate slices into a unified picture.
Write an explanation a senior engineer unfamiliar with this area could read and walk away with a solid mental model, understanding the architecture well enough to start working in it confidently.
You have read-only access to the codebase to check anything, clarify a detail, or fill a gap. Use Read, Grep, and Glob as needed. The explorers did the heavy lifting, so you shouldn't need to re-explore from scratch.
## Output Format
Use this structure, adapted to what makes sense for the question. Not every section is needed for every question.
### Overview
1-2 paragraphs. What is this thing, what does it do, why does it exist. Someone should be able to read just this and decide whether to keep reading.
### Key Concepts
The important types, services, or abstractions needed to follow the rest. Brief definitions, not exhaustive.
### How It Works
The core of the explanation, and the longest section. Walk through the flow: what triggers it, what happens step by step, where data goes, what the decision points are.
Use prose, not pseudocode. Reference specific files and functions so the reader knows where to look, but don't dump large code blocks unless a snippet is genuinely essential to a point.
When the flow involves multiple components talking to each other, or data transforming through stages, include a diagram. Use mermaid (```mermaid) for structured flows (sequence diagrams, flowcharts, component graphs) or ASCII art for simpler relationships where mermaid would be overkill. Use your judgment. A diagram should clarify, not decorate. If prose covers the flow, skip the diagram.
### Where Things Live
A brief file/directory map. Just the ones someone would need to start working here.
### Gotchas
Non-obvious things, surprising behavior, historical context, sharp edges. Skip this section if there's nothing worth calling out.
## Communication Style
- Use concrete language, not abstractions-about-abstractions
- Say "the `UserService` calls `AuthClient.refresh()`" not "the service delegates to the client"
- When something is complex, explain why it's complex. Don't just describe the complexity
- When something is simple, don't pad it out
- If there's a helpful analogy, use it; if there isn't, don't force one
- If the explorers flagged open questions or gaps, acknowledge them honestly rather than papering over them
@@ -0,0 +1,52 @@
# Explorer Prompt Template
Build each explorer subagent's prompt from this template. Fill in the placeholders.
---
You are exploring a codebase to understand how something works. Gather facts: trace code paths, read implementations, map components. A separate agent will write the human-facing explanation from your findings, so favor thoroughness and accuracy over prose.
Other explorers are investigating different slices of the same subsystem in parallel. Don't try to cover everything. Focus on your assigned angle and go deep.
## Question
> {QUESTION}
## Your Exploration Angle
{EXPLORATION_ANGLE}
## Exploration Instructions
Start by finding the relevant code. Use Glob to find directories and files, Grep to find key symbols, Read to understand the actual implementation. Don't guess from names. Read the code.
Follow this pattern:
1. **Find the entry point.** What triggers this behavior? A user action, an API call, a scheduled job? Find where it starts.
2. **Trace the flow.** Follow the call chain from the entry point. Read each function. Understand what data flows through and how it transforms.
3. **Map the key abstractions.** What types, interfaces, services, or classes are central? Read their definitions. Understand what they represent and why they exist.
4. **Find the boundaries.** Where does this subsystem interface with others? What goes in, what comes out?
5. **Look for the non-obvious.** Anything surprising? Anything that looks like a historical artifact? Anything a newcomer would misunderstand?
Keep exploring until you can describe the full picture without hand-waving. If you hit a part you can't trace, say so explicitly. "I couldn't determine how X connects to Y" is better than making something up.
## Output
Return your findings in this structure. Be factual and specific. Reference exact file paths, function names, type names, and line numbers where relevant.
### Components Found
The key types, services, classes, and abstractions. For each: name, file path, and a one-sentence description of what it does.
### Flow
The execution flow step by step. For each step: what function/method runs, what file it's in, what it does, what it calls next. Include the data that flows between steps.
### Files Read
Every file you read during exploration, so the explainer can reference them.
### Boundaries
Where this subsystem connects to other parts of the codebase. The inputs and outputs.
### Non-Obvious Things
Anything surprising, historically motivated, or easy to get wrong. Things that look like they should work one way but actually work another.
### Open Questions
Anything you couldn't fully trace or understand. Be honest about gaps.
@@ -0,0 +1,123 @@
# HTML Report Format
The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic.
## Scaffold
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Architecture review for {{repo name}}</title>
<script src="https://cdn.tailwindcss.com"></script>
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
mermaid.initialize({ startOnLoad: true, theme: "neutral", securityLevel: "loose" });
</script>
<style>
/* small custom layer for things Tailwind doesn't cover cleanly:
dashed seam lines, hand-drawn-feeling arrow heads, etc. */
.seam { stroke-dasharray: 4 4; }
.leak { stroke: #dc2626; }
.deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
</style>
</head>
<body class="bg-stone-50 text-slate-900 font-sans">
<main class="max-w-5xl mx-auto px-6 py-12 space-y-12">
<header>...</header>
<section id="candidates" class="space-y-10">...</section>
<section id="top-recommendation">...</section>
</main>
</body>
</html>
```
## Header
Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates.
## Candidate card
The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony.
Each candidate is one `<article>`:
- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline").
- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`).
- **Files**: monospaced list, `font-mono text-sm`.
- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below.
- **Problem**: one sentence. What hurts.
- **Solution**: one sentence. What changes.
- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers".
- **ADR callout** (if applicable): one line in an amber-tinted box.
No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram.
## Diagram patterns
Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point.
### Mermaid graph (the workhorse for dependencies / call flow)
Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1."
```html
<div class="rounded-lg border border-slate-200 bg-white p-4">
<pre class="mermaid">
flowchart LR
A[OrderHandler] --> B[OrderValidator]
B --> C[OrderRepo]
C -.leak.-> D[PricingClient]
classDef leak stroke:#dc2626,stroke-width:2px;
class C,D leak
</pre>
</div>
```
### Hand-built boxes-and-arrows (when Mermaid's layout fights you)
Modules as `<div>`s with borders and labels. Arrows as inline SVG `<line>` or `<path>` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight.
### Cross-section (good for layered shallowness)
Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility.
### Mass diagram (good for "interface as wide as implementation")
Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep).
### Call-graph collapse
Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it.
## Style guidance
- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate).
- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings.
- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling.
- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI.
- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering.
## Top recommendation section
One larger card. Candidate name, one sentence on why, anchor link to its card. That's it.
## Tone
Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift.
**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality.
**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module).
**Phrasings that fit the style:**
- "Order intake module is shallow: interface nearly matches the implementation."
- "Pricing leaks across the seam."
- "Deepen: one interface, one place to test."
- "Two adapters justify the seam: HTTP in prod, in-memory in tests."
**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place.
No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one.
@@ -1,53 +0,0 @@
# Language
Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
## Terms
**Module**
Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice.
_Avoid_: unit, component, service.
**Interface**
Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics.
_Avoid_: API, signature (too narrow — those refer only to the type-level surface).
**Implementation**
What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
**Depth**
Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation.
**Seam** _(from Michael Feathers)_
A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it.
_Avoid_: boundary (overloaded with DDD's bounded context).
**Adapter**
A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
**Leverage**
What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests.
**Locality**
What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere.
## Principles
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep.
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
## Relationships
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
- **Depth** is a property of a **Module**, measured against its **Interface**.
- A **Seam** is where a **Module**'s **Interface** lives.
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
## Rejected framings
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
@@ -1,71 +1,71 @@
---
name: improve-codebase-architecture
description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.
description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
disable-model-invocation: true
---
# Improve Codebase Architecture
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
## Glossary
This command is _informed_ by the project's domain model and built on a shared design vocabulary:
Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md).
- **Module** — anything with an interface and an implementation (function, class, package, slice).
- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature.
- **Implementation** — the code inside.
- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation.
- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.")
- **Adapter** — a concrete thing satisfying an interface at a seam.
- **Leverage** — what callers get from depth.
- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place.
Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list):
- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
- **The interface is the test surface.**
- **One adapter = hypothetical seam. Two adapters = real seam.**
This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate.
- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary."
- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
## Process
### 1. Explore
Read the project's domain glossary and any ADRs in the area you're touching first.
**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look:
Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below.
- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net.
Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first.
Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction:
- Where does understanding one concept require bouncing between many small modules?
- Where are modules **shallow** — interface nearly as complex as the implementation?
- Where are modules **shallow**, with an interface nearly as complex as the implementation?
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
- Where do tightly-coupled modules leak across their seams?
- Which parts of the codebase are untested, or hard to test through their current interface?
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
### 2. Present candidates
### 2. Present candidates as an HTML report
Present a numbered list of deepening opportunities. For each candidate:
Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `<tmpdir>/architecture-review-<timestamp>.html` so each run gets a fresh file. Open it for the user (`xdg-open <path>` on Linux, `open <path>` on macOS, `start <path>` on Windows) and tell them the absolute path.
- **Files** — which files/modules are involved
- **Problem** — why the current architecture is causing friction
- **Solution** — plain English description of what would change
- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve
The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual.
**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
For each candidate, render a card with:
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
- **Files**: which files/modules are involved
- **Problem**: why the current architecture is causing friction
- **Solution**: plain English description of what would change
- **Benefits**: explained in terms of locality and leverage, and how tests would improve
- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening
- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge
Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?"
End the report with a **Top recommendation** section: which candidate you'd tackle first and why.
**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service."
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance.
Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?"
### 3. Grilling loop
Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Side effects happen inline as decisions crystallize:
Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go:
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist.
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. Create the file lazily if it doesn't exist.
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md).
- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md).
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones.
- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern.
@@ -0,0 +1,5 @@
interface:
display_name: "Improve Codebase Architecture"
short_description: "Find and grill architecture improvements"
policy:
allow_implicit_invocation: false
-1
View File
@@ -1 +0,0 @@
/Users/johannes/.local/share/mise/installs/node/25.6.0/lib/node_modules/oh-my-mermaid/skills
-41
View File
@@ -1,41 +0,0 @@
---
name: ponytail-audit
description: >
Whole-repo audit for over-engineering. Like ponytail-review, but scans the
entire codebase instead of a diff: a ranked list of what to delete, simplify,
or replace with stdlib/native equivalents. Use when the user says "audit this
codebase", "audit for over-engineering", "what can I delete from this repo",
"find bloat", "ponytail-audit", or "/ponytail-audit". One-shot report, does
not apply fixes.
---
ponytail-review, repo-wide. Scan the whole tree instead of a diff. Rank
findings biggest cut first.
## Tags
Same as ponytail-review:
- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing.
- `stdlib:` hand-rolled thing the standard library ships. Name the function.
- `native:` dependency or code doing what the platform already does. Name the feature.
- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller.
- `shrink:` same logic, fewer lines. Show the shorter form.
## Hunt
Deps the stdlib or platform already ships, single-implementation interfaces,
factories with one product, wrappers that only delegate, files exporting one
thing, dead flags and config, hand-rolled stdlib.
## Output
One line per finding, ranked: `<tag> <what to cut>. <replacement>. [path]`.
End with `net: -<N> lines, -<M> deps possible.` Nothing to cut: `Lean already. Ship.`
## Boundaries
Scope: over-engineering and complexity only. Correctness bugs, security holes,
and performance are explicitly out of scope. Route them to a normal review
pass. Lists findings, applies nothing. One-shot.
"stop ponytail-audit" or "normal mode" to revert.
-44
View File
@@ -1,44 +0,0 @@
---
name: ponytail-debt
description: >
Harvest every `ponytail:` comment in the codebase into a debt ledger, so the
deliberate shortcuts and deferrals ponytail leaves behind get tracked instead
of rotting into "later means never". Use when the user says "ponytail debt",
"/ponytail-debt", "what did ponytail defer", "list the shortcuts", "ponytail
ledger", or "what did we mark to do later". One-shot report, changes nothing.
---
Every deliberate ponytail shortcut is marked with a `ponytail:` comment naming
its ceiling and upgrade path. This collects them into one ledger so a deferral
can't quietly become permanent.
## Scan
Grep the repo for comment markers, skipping `node_modules`, `.git`, and build
output:
`grep -rnE '(#|//) ?ponytail:' .` (add other comment prefixes if your stack uses them)
Each hit is one ledger row. The comment prefix keeps prose that merely mentions
the convention out of the ledger.
## Output
One row per marker, grouped by file:
`<file>:<line>, <what was simplified>. ceiling: <the limit named>. upgrade: <the trigger to revisit>.`
The convention is `ponytail: <ceiling>, <upgrade path>`, so pull the ceiling
and the trigger straight from the comment. Want an owner per row too? add
`git blame -L<line>,<line>`.
Flag the rot risk: any `ponytail:` comment that names no upgrade path or
trigger gets a `no-trigger` tag, those are the ones that silently rot.
End with `<N> markers, <M> with no trigger.` Nothing found: `No ponytail: debt. Clean ledger.`
## Boundaries
Reads and reports only, changes nothing. To persist it, ask and it writes the
ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. "stop ponytail-debt" or
"normal mode" to revert.
-50
View File
@@ -1,50 +0,0 @@
---
name: ponytail-gain
description: >
Show ponytail's measured impact as a compact scoreboard: less code, less
cost, more speed, from the benchmark medians. One-shot display, not a
persistent mode, and not a per-repo number. Trigger: /ponytail-gain,
"ponytail gain", "what does ponytail save", "show ponytail impact",
"ponytail scoreboard".
---
# Ponytail Gain
Display this scoreboard when invoked. One-shot: do NOT change mode, write flag
files, or persist anything.
The figures are the published benchmark medians (5 everyday tasks: email
validator, debounce, CSV sum, countdown timer, rate limiter; three models:
Haiku, Sonnet, Opus). They are measured, not computed from the current repo.
Source: `benchmarks/` and the README.
## Scoreboard
Render plain ASCII bars. The bar length shows the measured range; the label
carries the exact figure:
```
ponytail gain benchmark median · 5 tasks · 3 models
Lines of code no-skill ████████████████████ 100%
ponytail ██▌················· 6–20% ▼ 80–94%
Cost no-skill ████████████████████ 100%
ponytail █████▌·············· 23–53% ▼ 47–77%
Speed ponytail ▸ 3–6× faster
This repo: /ponytail-debt (shortcuts you deferred)
/ponytail-audit (what's still cuttable)
```
## Honesty boundary
These are benchmark medians, not this repo. NEVER print a per-repo savings
number ("you saved X lines/tokens here"): the unbuilt version was never
written, so there is no real baseline to subtract from in a live repo. The
only real per-repo figures come from `/ponytail-debt` (a counted ledger), and
this card points there instead of inventing one.
## Boundaries
One-shot display. Edits nothing, changes no mode.
"stop ponytail" or "normal mode": revert.
-69
View File
@@ -1,69 +0,0 @@
---
name: ponytail-help
description: >
Quick-reference card for all ponytail modes, skills, and commands.
One-shot display, not a persistent mode. Trigger: /ponytail-help,
"ponytail help", "what ponytail commands", "how do I use ponytail".
---
# Ponytail Help
Display this reference card when invoked. One-shot, do NOT change mode,
write flag files, or persist anything.
## Levels
| Level | Trigger | What change |
|-------|---------|-------------|
| **Lite** | `/ponytail lite` | Build what's asked, name the lazier alternative in one line. |
| **Full** | `/ponytail` | The ladder enforced: YAGNI → stdlib → native → one line → minimum. Default. |
| **Ultra** | `/ponytail ultra` | YAGNI extremist. Deletion before addition. Challenges requirements before building. |
Level sticks until changed or session end.
## Skills
| Skill | Trigger | What it does |
|-------|---------|--------------|
| **ponytail** | `/ponytail` | Lazy mode itself. Simplest solution that works. |
| **ponytail-review** | `/ponytail-review` | Over-engineering review: `L42: yagni: factory, one product. Inline.` |
| **ponytail-gain** | `/ponytail-gain` | Measured-impact scoreboard: less code, less cost, more speed. |
| **ponytail-help** | `/ponytail-help` | This card. |
Codex uses `@ponytail`, `@ponytail-review`, and `@ponytail-help`; Claude Code
and OpenCode use the slash-command forms above (OpenCode ships `/ponytail` and
`/ponytail-review`).
## Deactivate
Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`.
`/ponytail off` also works.
## Configure Default Mode
Default mode = `full`, auto-active every session. Change it:
**Environment variable** (highest priority):
```bash
export PONYTAIL_DEFAULT_MODE=ultra
```
**Config file** (`~/.config/ponytail/config.json`, Windows: `%APPDATA%\ponytail\config.json`):
```json
{ "defaultMode": "lite" }
```
Set `"off"` to disable auto-activation on session start, activate manually
with `/ponytail` when wanted.
Resolution: env var > config file > `full`.
## Update
Enable auto-update once: open `/plugin`, go to Marketplaces, pick ponytail, Enable auto-update. Claude Code then pulls new versions at startup (run `/reload-plugins` when it prompts). Manual refresh: `/plugin marketplace update ponytail` then `/reload-plugins`.
If `/plugin` is not recognized, your Claude Code is out of date. Update it (`npm install -g @anthropic-ai/claude-code@latest`, or `brew upgrade claude-code`) and restart. Other hosts use their own update flow.
## More
Full docs + examples: https://github.com/DietrichGebert/ponytail
-57
View File
@@ -1,57 +0,0 @@
---
name: ponytail-review
description: >
Code review focused exclusively on over-engineering. Finds what to delete:
reinvented standard library, unneeded dependencies, speculative abstractions,
dead flexibility. One line per finding: location, what to cut, what replaces
it. Use when the user says "review for over-engineering", "what can we
delete", "is this over-engineered", "simplify review", or invokes
/ponytail-review. Complements correctness-focused review, this one only
hunts complexity.
---
Review diffs for unnecessary complexity. One line per finding: location, what
to cut, what replaces it. The diff's best outcome is getting shorter.
## Format
`L<line>: <tag> <what>. <replacement>.`, or `<file>:L<line>: ...` for
multi-file diffs.
Tags:
- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing.
- `stdlib:` hand-rolled thing the standard library ships. Name the function.
- `native:` dependency or code doing what the platform already does. Name the feature.
- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller.
- `shrink:` same logic, fewer lines. Show the shorter form.
## Examples
❌ "This EmailValidator class might be more complex than necessary, have you
considered whether all these validation rules are needed at this stage?"
✅ `L12-38: stdlib: 27-line validator class. "@" in email, 1 line, real validation is the confirmation mail.`
✅ `L4: native: moment.js imported for one format call. Intl.DateTimeFormat, 0 deps.`
✅ `repo.py:L88: yagni: AbstractRepository with one implementation. Inline it until a second one exists.`
✅ `L52-71: delete: retry wrapper around an idempotent local call. Nothing replaces it.`
✅ `L30-44: shrink: manual loop builds dict. dict(zip(keys, values)), 1 line.`
## Scoring
End with the only metric that matters: `net: -<N> lines possible.`
If there is nothing to cut, say `Lean already. Ship.` and stop.
## Boundaries
Scope: over-engineering and complexity only. Correctness bugs, security holes,
and performance are explicitly out of scope. Route them to a normal review
pass, not this one. A single smoke test or `assert`-based
self-check is the ponytail minimum, not bloat, never flag it for deletion.
Does not apply the fixes, only lists them.
"stop ponytail-review" or "normal mode": revert to verbose review style.
-117
View File
@@ -1,117 +0,0 @@
---
name: ponytail
description: >
Forces the laziest solution that actually works, simplest, shortest, most
minimal. Channels a senior dev who has seen everything: question whether the
task needs to exist at all (YAGNI), reach for the standard library before
custom code, native platform features before dependencies, one line before
fifty. Supports intensity levels: lite, full (default), ultra. Use whenever
the user says "ponytail", "be lazy", "lazy mode", "simplest solution",
"minimal solution", "yagni", "do less", or "shortest path", and whenever
they complain about over-engineering, bloat, boilerplate, or unnecessary
dependencies.
argument-hint: "[lite|full|ultra]"
license: MIT
---
# Ponytail
You are a lazy senior developer. Lazy means efficient, not careless. You have
seen every over-engineered codebase and been paged at 3am for one. The best
code is the code never written.
## Persistence
ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if
unsure. Off only: "stop ponytail" / "normal mode". Default: **full**.
Switch: `/ponytail lite|full|ultra`.
## The ladder
Stop at the first rung that holds:
1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI)
2. **Already in this codebase?** A helper, util, type, or pattern that already lives here → reuse it. Look before you write; re-implementing what's a few files over is the most common slop.
3. **Stdlib does it?** Use it.
4. **Native platform feature covers it?** `<input type="date">` over a picker lib, CSS over JS, DB constraint over app code.
5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do.
6. **Can it be one line?** One line.
7. **Only then:** the minimum code that works.
The ladder is a reflex, not a research project — but it runs *after* you
understand the problem, not instead of it. Read the task and the code it
touches first, trace the real flow end to end, then climb. Two rungs work →
take the higher one and move on. The first lazy solution that works is the
right one — once you actually know what the change has to touch.
**Bug fix = root cause, not symptom.** A report names a symptom. Before you
edit, grep every caller of the function you're about to touch. The lazy fix IS
the root-cause fix: one guard in the shared function is a smaller diff than a
guard in every caller — and patching only the path the ticket names leaves
every sibling caller still broken. Fix it once, where all callers route through.
## Rules
- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes.
- No boilerplate, no scaffolding "for later", later can scaffold for itself.
- Deletion over addition. Boring over clever, clever is what someone decodes at 3am.
- Fewest files possible. Shortest working diff wins — but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default.
- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm.
- Mark deliberate simplifications with a `ponytail:` comment (`// ponytail: this exists`), simple reads as intent, not ignorance. Shortcut with a known ceiling (global lock, O(n²) scan, naive heuristic)? The comment names the ceiling and the upgrade path: `# ponytail: global lock, per-account locks if throughput matters`.
## Output
Code first. Then at most three short lines: what was skipped, when to add it.
No essays, no feature tours, no design notes. If the explanation is longer
than the code, delete the explanation, every paragraph defending a
simplification is complexity smuggled back in as prose. Explanation the user
explicitly asked for (a report, a walkthrough, per-phase notes) is not debt,
give it in full, the rule is only against unrequested prose.
Pattern: `[code] → skipped: [X], add when [Y].`
## Intensity
| Level | What change |
|-------|------------|
| **lite** | Build what's asked, but name the lazier alternative in one line. User picks. |
| **full** | The ladder enforced. Stdlib and native first. Shortest diff, shortest explanation. Default. |
| **ultra** | YAGNI extremist. Deletion before addition. Ship the one-liner and challenge the rest of the requirement in the same breath. |
Example: "Add a cache for these API responses."
- lite: "Done, cache added. FYI: `functools.lru_cache` covers this in one line if you'd rather not own a cache class."
- full: "`@lru_cache(maxsize=1000)` on the fetch function. Skipped custom cache class, add when lru_cache measurably falls short."
- ultra: "No cache until a profiler says so. When it does: `@lru_cache`. A hand-rolled TTL cache class is a bug farm with a hit rate."
## When NOT to be lazy
Never simplify away: input validation at trust boundaries, error handling
that prevents data loss, security measures, accessibility basics, anything
explicitly requested. User insists on the full version → build it, no
re-arguing.
Never lazy about understanding the problem. The ladder shortens the
solution, never the reading. Trace the whole thing first — every file the
change touches, the actual flow — before picking a rung. Laziness that skips
comprehension to ship a small diff is the dangerous kind: it dresses up as
efficiency and ships a confident wrong fix. Read fully, then be lazy.
Hardware is never the ideal on paper: a real clock drifts, a real sensor
reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not
just less code, the physical world needs tuning a minimal model can't see.
Lazy code without its check is unfinished. Non-trivial logic (a branch, a
loop, a parser, a money/security path) leaves ONE runnable check behind, the
smallest thing that fails if the logic breaks: an `assert`-based
`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no
fixtures, no per-function suites unless asked. Trivial one-liners need no
test, YAGNI applies to tests too.
## Boundaries
Ponytail governs what you build, not how you talk (pair with Caveman for
terse prose). "stop ponytail" / "normal mode": revert. Level persists until
changed or session end.
The shortest path to done is the right path.
+67
View File
@@ -0,0 +1,67 @@
# Logic Prototype
A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases.
Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's.
## When this is the right shape
- "I'm not sure if this state machine handles the edge case where X then Y."
- "Does this data model actually let me represent the case where..."
- "I want to feel out what the API should look like before writing it."
- Anything where someone wants to **press buttons and watch state change**.
If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md).
## Process
### 1. State the question
Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK.
### 2. Isolate the logic in a portable module
Put the actual logic (the bit that's answering the question) in a single `<script>` block written as a small, pure module that could be lifted out and dropped into the real codebase later. The page around it is throwaway; this module isn't.
The right shape depends on the question:
- **A pure reducer**: `(state, action) => state`. Good when actions are discrete events and state is a single value.
- **A state machine**: explicit states and transitions. Good when "which actions are even legal right now" is part of the question.
- **A small set of pure functions** over a plain data type. Good when there's no implicit current state, just transformations.
- **A class or module with a clear method surface** when the logic genuinely owns ongoing internal state.
Pick whichever shape best fits the question being asked, *not* whichever is easiest to wire to a page. Keep it pure: no DOM, no `document`, no button handlers reaching inside it. The page calls into it; nothing flows the other direction. This is what makes the prototype useful past its own lifetime: once the question's answered, the validated reducer / machine / function set lifts into the real module on its own.
### 3. Build the shareable HTML file
One file, plain HTML/CSS/JS: no framework, no bundler, no server, everything inline so it opens by double-click and survives being emailed around. Anyone should be able to run it by opening it.
Write it for a non-developer. Every label is in **domain language**, not code: buttons and state read like the business, not the reducer. Explain in plain words what's happening.
Lay it out with a clean hierarchy, top to bottom:
1. **Title and one-line explanation** of what this demo lets you explore (the question from step 1).
2. **Current state**: the full relevant state, rendered as a readable panel (labelled fields, not a raw JSON dump), re-rendered after every click so the change is visible. Where it helps a non-developer follow, call out what just changed.
3. **Free-play buttons**: one button per action, always available, so anyone can poke at the model in any order. Each click dispatches its action and re-renders the state.
4. **Guided walkthroughs**: a set of **scenarios**, one per tab. Each tab holds a short plain-language description of the scenario (the situation it sets up and what to watch for) and underneath it, the ordered **buttons to press** for that scenario. Each step is a real button: clicking it performs that action and moves to the next step. Starting a walkthrough resets to a known initial state so the scenario runs the same way every time.
Choose scenarios that demonstrate the awkward cases, the ones hard to reason about on paper: the happy path, a tricky edge case, an attempt at something that should be illegal.
Keep it beautiful but restrained: clean typography, generous spacing, one accent colour. No animations, no gimmicks: nothing that competes with the state and the buttons.
### 4. Hand it over
Send them the file, or open it for them. They'll click through the walkthroughs and free-play whenever they get to it; the interesting moments are when they say "wait, that shouldn't be possible" or "huh, I assumed X would be different"; those are the bugs in the _idea_, which is the whole point. If they want new actions or a new scenario, add them. Prototypes evolve.
### 5. Capture the answer and the prototype
Once the prototype has answered its question, capture the answer, then capture the prototype the way the [SKILL](SKILL.md) describes. The logic-specific mapping: the validated reducer / machine / function set lifts into the real module (the decision, absorbed); the HTML shell rides along to the throwaway branch that keeps the prototype as a primary source, and being one self-contained file, it stays trivially re-runnable there.
## Anti-patterns
- **Don't add tests.** A prototype that needs tests is no longer a prototype.
- **Don't wire it to the real database.** Use in-memory state unless the question is specifically about persistence.
- **Don't generalise.** No "what if we wanted to support X later." The prototype answers one question.
- **Don't blur the logic and the page together.** If the pure module references the DOM, `document`, or button handlers, it's no longer liftable. Keep the page as a thin shell over a pure module.
- **Don't reach for a framework, bundler, or server.** One file the recipient double-clicks; a React app or a dev server defeats "shareable".
- **Don't ship the HTML shell into production.** The page is optimised for being clicked through by hand. The logic module behind it is the bit worth keeping.
+26
View File
@@ -0,0 +1,26 @@
---
name: prototype
description: Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.
---
# Prototype
A prototype is **throwaway code that answers a question**. The question decides the shape.
## Pick a branch
Identify which question is being answered, using the user's prompt, the surrounding code, or by asking if the user is around:
- **"Does this logic / state model feel right?"** → [LOGIC.md](LOGIC.md). Build a single shareable HTML file (free-play buttons plus tabbed guided walkthroughs) that pushes the state machine through cases that are hard to reason about on paper, and that a non-developer can drive.
- **"What should this look like?"** → [UI.md](UI.md). Generate several radically different UI variations on a single route, switchable via a URL search param and a floating bottom bar.
The two branches produce very different artifacts, so getting this wrong wastes the whole prototype. If the question is genuinely ambiguous and the user isn't reachable, default to whichever branch better matches the surrounding code (a backend module → logic; a page or component → UI) and state the assumption at the top of the prototype.
## Rules that apply to both
1. **Throwaway from day one, and clearly marked as such.** Locate the prototype code close to where it will actually be used (next to the module or page it's prototyping for) so context is obvious, but name it so a casual reader can see it's a prototype, not production. For throwaway UI routes, obey whatever routing convention the project already uses; don't invent a new top-level structure.
2. **Trivial to run.** A UI prototype starts from one command in the project's task runner: `pnpm <name>`, `python <path>`, `bun <path>`, etc. A logic demo is a single HTML file the user double-clicks. Either way, no thinking required to start it.
3. **No persistence by default.** State lives in memory. Persistence is the thing the prototype is _checking_, not something it should depend on. If the question explicitly involves a database, hit a scratch DB or a local file with a clear "PROTOTYPE, wipe me" name.
4. **Skip the polish.** No tests, no error handling beyond what makes the prototype _runnable_, no abstractions. The point is to learn something fast.
5. **Surface the state.** After every action (logic) or on every variant switch (UI), print or render the full relevant state so the user can see what changed.
6. **Capture it when done.** Fold any validated decision into the real code, then capture the prototype itself as a **primary source**: commit it to a throwaway branch, out of main, and leave a context pointer to that branch on the implementation issue. Capture the answer too (the verdict and the question it settled) in the issue or a commit. The main branch keeps only the validated decision.
+112
View File
@@ -0,0 +1,112 @@
# UI Prototype
Generate **several radically different UI variations** on a single route, switchable from a floating bottom bar. The user flips between variants in the browser, picks one (or steals bits from each), then throws the rest away.
If the question is about logic/state rather than what something looks like, this is the wrong branch. Use [LOGIC.md](LOGIC.md).
## When this is the right shape
- "What should this page look like?"
- "I want to see a few options for this dashboard before committing."
- "Try a different layout for the settings screen."
- Any time the user would otherwise spend a day picking between three vague mockups in their head.
## Two sub-shapes: strongly prefer sub-shape A
A UI prototype is much easier to judge when it's **butting up against the rest of the app**: real header, real sidebar, real data, real density. A throwaway route on its own is a vacuum: every variant looks fine in isolation. Default to sub-shape A whenever there's a plausible existing page to host the variants. Only reach for sub-shape B if the prototype genuinely has no nearby home.
### Sub-shape A: adjustment to an existing page (preferred)
The route already exists. Variants are rendered **on the same route**, gated by a `?variant=` URL search param. The existing data fetching, params, and auth all stay. Only the rendering swaps. This is the default; pick it unless there's a specific reason not to.
If the prototype is for something that doesn't yet have a page but *would naturally live inside one* (a new section of the dashboard, a new card on the settings screen, a new step in an existing flow), it's still sub-shape A. Mount the variants inside the host page.
### Sub-shape B: a new page (last resort)
Only use this when the thing being prototyped genuinely has no existing page to live inside (e.g. an entirely new top-level surface, or a flow that can't be embedded anywhere sensible).
Create a **throwaway route** following whatever routing convention the project already uses. Don't invent a new top-level structure. Name it so it's obviously a prototype (e.g. include the word `prototype` in the path or filename). Same `?variant=` pattern.
Before committing to sub-shape B, sanity-check: is there really no existing page this could be embedded in? An empty route hides design problems that a populated one would expose.
In both sub-shapes the floating bottom bar is identical.
## Process
### 1. State the question and pick N
Default to **3 variants**. More than 5 stops being radically different and starts being noise, so cap there.
Write down the plan in one line, in the prototype's location or a top-of-file comment:
> "Three variants of the settings page, switchable via `?variant=`, on the existing `/settings` route."
This works whether the user is here to push back or not.
### 2. Generate radically different variants
Draft each variant. Hold each one to:
- The page's purpose and the data it has access to.
- The project's component library / styling system (TailwindCSS, shadcn, MUI, plain CSS, whatever).
- A clear exported component name, e.g. `VariantA`, `VariantB`, `VariantC`.
Variants must be **structurally different**: different layout, different information hierarchy, different primary affordance, not just different colours. Three slightly-tweaked card grids isn't a UI prototype, it's wallpaper. If two drafts come out too similar, redo one with explicit "do not use a card grid" guidance.
### 3. Wire them together
Create a single switcher component on the route:
```tsx
// pseudo-code, adapt to the project's framework
const variant = searchParams.get('variant') ?? 'A';
return (
<>
{variant === 'A' && <VariantA {...data} />}
{variant === 'B' && <VariantB {...data} />}
{variant === 'C' && <VariantC {...data} />}
<PrototypeSwitcher variants={['A','B','C']} current={variant} />
</>
);
```
For sub-shape A (existing page): keep all the existing data fetching above the switcher; only the rendered subtree changes per variant.
For sub-shape B (new page): the throwaway route under `/prototype/<name>` mounts the same switcher.
### 4. Build the floating switcher
A small fixed-position bar at the bottom-centre of the screen with three pieces:
- **Left arrow**: cycles to the previous variant (wraps around).
- **Variant label**: shows the current variant key and, if the variant exports a name, that name too. e.g. `B (Sidebar layout)`.
- **Right arrow**: cycles forward (wraps around).
Behaviour:
- Clicking an arrow updates the URL search param (use the framework's router, e.g. `router.replace` on Next, `navigate` on React Router, etc) so the variant is shareable and reload-stable.
- Keyboard: `←` and `→` arrow keys also cycle. Don't intercept arrow keys when an `<input>`, `<textarea>`, or `[contenteditable]` is focused.
- Visually distinct from the page (e.g. high-contrast pill, subtle shadow) so it's obviously not part of the design being evaluated.
- Hidden in production builds: gate on `process.env.NODE_ENV !== 'production'` or an equivalent check, so a stray prototype merge can't ship the bar to users.
Put the switcher in a single shared component so both sub-shapes can reuse it. Locate it wherever shared UI lives in the project.
### 5. Hand it over
Surface the URL (and the `?variant=` keys). The user will flip through whenever they get to it. The interesting feedback is usually **"I want the header from B with the sidebar from C"**, which is the actual design they want.
### 6. Capture the answer and clean up
Once a variant has won, capture the answer (which variant and why), then capture the prototype the way the [SKILL](SKILL.md) describes. Fold the winner into the real code and move the rest onto the throwaway branch, not into main:
- **Sub-shape A**: fold the winner into the existing page; drop the losing variants and the switcher from main.
- **Sub-shape B**: promote the winning variant to a real route; drop the throwaway route and the switcher from main.
The full set of variants is the primary source, so it lands on the throwaway branch, not the bin, since variant components and the switcher left in the main branch rot fast and confuse the next reader.
## Anti-patterns
- **Variants that differ only in colour or copy.** That's a tweak, not a prototype. Real variants disagree about structure.
- **Sharing too much code between variants.** A shared `<Header>` is fine; a shared `<Layout>` defeats the point. Each variant should be free to throw out the layout.
- **Wiring variants to real mutations.** Read-only prototypes are fine. If a variant needs to mutate, point it at a stub: the question is "what should this look like", not "does the backend work".
- **Promoting the prototype directly to production.** The variant code was written under prototype constraints (no tests, minimal error handling). Rewrite it properly when you fold it in.
@@ -0,0 +1,3 @@
interface:
display_name: "Prototype"
short_description: "Prototype to answer a design question"
+12
View File
@@ -0,0 +1,12 @@
---
name: research
description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent.
---
Spin up a **background agent** to do the research, so you keep working while it reads.
Its job:
1. Investigate the question against **primary sources** (official docs, source code, specs, first-party APIs), not a secondary write-up of them. Follow every claim back to the source that owns it.
2. Write the findings to a single Markdown file, citing each claim's source.
3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where.
@@ -0,0 +1,3 @@
interface:
display_name: "Research"
short_description: "Research from high-trust sources"
@@ -0,0 +1,14 @@
---
name: resolving-merge-conflicts
description: "Use when you need to resolve an in-progress git merge/rebase conflict."
---
1. **See the current state** of the merge/rebase. Check git history, and the conflicting files.
2. **Find the primary sources** for each conflict. Understand deeply why each change was made, and what the original intent was. Read the commit messages, check the PRs, check original issues/tickets.
3. **Resolve each hunk.** Preserve both intents where possible. Where incompatible, pick the one matching the merge's stated goal and note the trade-off. Do **not** invent new behaviour. Always resolve; never `--abort`.
4. Discover the project's **automated checks** and run them, typically typecheck, then tests, then format. Fix anything the merge broke.
5. **Finish the merge/rebase.** Stage everything and commit. If rebasing, continue the rebase process until all commits are rebased.
@@ -0,0 +1,3 @@
interface:
display_name: "Resolving Merge Conflicts"
short_description: "Resolve merge and rebase conflicts"
+27 -92
View File
@@ -1,109 +1,44 @@
---
name: tdd
description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions "red-green-refactor", wants integration tests, or asks for test-first development.
description: "Use only when the user explicitly asks for TDD, a failing test, or a regression test, OR when the bug has an obvious cheap local test target. Skip when the test path is unclear, expensive, integration-heavy, or not requested."
disable-model-invocation: true
---
# Test-Driven Development
# TDD Bug Fix
## Philosophy
When fixing a bug with a clear, cheap test path, make the broken behavior executable before changing production code. The goal is a focused regression test that fails before the fix and passes after it.
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
## Anti-Pattern: Horizontal Slices
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
This produces **crap tests**:
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
- You outrun your headlights, committing to test structure before understanding the implementation
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.
```
WRONG (horizontal):
RED: test1, test2, test3, test4, test5
GREEN: impl1, impl2, impl3, impl4, impl5
RIGHT (vertical):
RED→GREEN: test1→impl1
RED→GREEN: test2→impl2
RED→GREEN: test3→impl3
...
```
Do not force a test when it would be impractical. If the available test would require broad harness setup, brittle mocks, slow end-to-end infrastructure, production-only state, vague reproduction steps, or large unrelated fixture churn, skip adding a new test and use the closest useful verification instead.
## Workflow
### 1. Planning
1. **Understand the bug.** Identify the intended behavior, current behavior, affected path, and smallest observable reproduction.
2. **Choose the narrowest executable check.** Prefer the closest unit, component, integration, or regression test already used for that codepath. If no practical test path is obvious, do not create one from scratch just to satisfy the workflow.
3. **Write the failing test first.** Add the smallest focused test that would have caught the bug. The test should encode intended behavior, not mirror the current implementation.
4. **Run the new test before fixing.** Confirm it fails for the intended reason. If it passes or fails for an unrelated reason, correct the test or reproduction before editing the implementation.
5. **Fix the bug.** Make the smallest production change that satisfies the intended behavior while preserving nearby contracts.
6. **Rerun the regression test.** Confirm the test now passes.
7. **Run nearby validation.** Run relevant adjacent tests, type checks, lint, or scenario checks when the change has broader risk.
When exploring the codebase, use the project's domain glossary so that test names and interface vocabulary match the project's language, and respect ADRs in the area you're touching.
## If a Failing Test Is Impractical
Before writing any code:
Do not silently skip the regression step. Before fixing, explicitly explain why a failing test is impossible or not worth the cost, then choose the closest executable regression check available. Examples include a targeted script, manual reproduction command, browser automation, snapshot comparison, log assertion, or focused integration check.
- [ ] Confirm with user what interface changes are needed
- [ ] Confirm with user which behaviors to test (prioritize)
- [ ] Identify opportunities for [deep modules](deep-modules.md) (small interface, deep implementation)
- [ ] Design interfaces for [testability](interface-design.md)
- [ ] List the behaviors to test (not implementation steps)
- [ ] Get user approval on the plan
Prefer no new test over a bad test. A bad test is one that mostly tests mocks, encodes current implementation details, depends on timing or unrelated global state, needs expensive infrastructure for a small fix, or would be deleted immediately after proving the fix.
Ask: "What should the public interface look like? Which behaviors are most important to test?"
## Guardrails
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
- Do not change tests merely to match a wrong implementation.
- Do not weaken existing assertions unless the expected behavior has genuinely changed and the reason is clear.
- Keep the regression test focused on the bug; avoid broad fixture churn or unrelated coverage expansion.
- Do not add tests when the practical signal is weak; use manual or scripted verification and say why.
- If the bug is flaky, make the test deterministic where possible and document the signal being locked down.
- If the bug exposes a broader class of failures, first land the focused regression path, then consider additional sibling coverage.
### 2. Tracer Bullet
## Final Response
Write ONE test that confirms ONE thing about the system:
Report the evidence, not just the outcome:
```
RED: Write test for first behavior → test fails
GREEN: Write minimal code to pass → test passes
```
This is your tracer bullet - proves the path works end-to-end.
### 3. Incremental Loop
For each remaining behavior:
```
RED: Write next test → fails
GREEN: Minimal code to pass → passes
```
Rules:
- One test at a time
- Only enough code to pass current test
- Don't anticipate future tests
- Keep tests focused on observable behavior
### 4. Refactor
After all tests pass, look for [refactor candidates](refactoring.md):
- [ ] Extract duplication
- [ ] Deepen modules (move complexity behind simple interfaces)
- [ ] Apply SOLID principles where natural
- [ ] Consider what new code reveals about existing code
- [ ] Run tests after each refactor step
**Never refactor while RED.** Get to GREEN first.
## Checklist Per Cycle
```
[ ] Test describes behavior, not implementation
[ ] Test uses public interface only
[ ] Test would survive internal refactor
[ ] Code is minimal for this test
[ ] No speculative features added
```
- Name the failing-before test or executable check and the failure it produced.
- Name the passing-after test run and any nearby validation performed.
- If failing-before evidence could not be demonstrated, state why and describe the closest regression check used instead.
-33
View File
@@ -1,33 +0,0 @@
# Deep Modules
From "A Philosophy of Software Design":
**Deep module** = small interface + lots of implementation
```
┌─────────────────────┐
│ Small Interface │ ← Few methods, simple params
├─────────────────────┤
│ │
│ │
│ Deep Implementation│ ← Complex logic hidden
│ │
│ │
└─────────────────────┘
```
**Shallow module** = large interface + little implementation (avoid)
```
┌─────────────────────────────────┐
│ Large Interface │ ← Many methods, complex params
├─────────────────────────────────┤
│ Thin Implementation │ ← Just passes through
└─────────────────────────────────┘
```
When designing interfaces, ask:
- Can I reduce the number of methods?
- Can I simplify the parameters?
- Can I hide more complexity inside?
-31
View File
@@ -1,31 +0,0 @@
# Interface Design for Testability
Good interfaces make testing natural:
1. **Accept dependencies, don't create them**
```typescript
// Testable
function processOrder(order, paymentGateway) {}
// Hard to test
function processOrder(order) {
const gateway = new StripeGateway();
}
```
2. **Return results, don't produce side effects**
```typescript
// Testable
function calculateDiscount(cart): Discount {}
// Hard to test
function applyDiscount(cart): void {
cart.total -= discount;
}
```
3. **Small surface area**
- Fewer methods = fewer tests needed
- Fewer params = simpler test setup
-59
View File
@@ -1,59 +0,0 @@
# When to Mock
Mock at **system boundaries** only:
- External APIs (payment, email, etc.)
- Databases (sometimes - prefer test DB)
- Time/randomness
- File system (sometimes)
Don't mock:
- Your own classes/modules
- Internal collaborators
- Anything you control
## Designing for Mockability
At system boundaries, design interfaces that are easy to mock:
**1. Use dependency injection**
Pass external dependencies in rather than creating them internally:
```typescript
// Easy to mock
function processPayment(order, paymentClient) {
return paymentClient.charge(order.total);
}
// Hard to mock
function processPayment(order) {
const client = new StripeClient(process.env.STRIPE_KEY);
return client.charge(order.total);
}
```
**2. Prefer SDK-style interfaces over generic fetchers**
Create specific functions for each external operation instead of one generic function with conditional logic:
```typescript
// GOOD: Each function is independently mockable
const api = {
getUser: (id) => fetch(`/users/${id}`),
getOrders: (userId) => fetch(`/users/${userId}/orders`),
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
};
// BAD: Mocking requires conditional logic inside the mock
const api = {
fetch: (endpoint, options) => fetch(endpoint, options),
};
```
The SDK approach means:
- Each mock returns one specific shape
- No conditional logic in test setup
- Easier to see which endpoints a test exercises
- Type safety per endpoint
-10
View File
@@ -1,10 +0,0 @@
# Refactor Candidates
After TDD cycle, look for:
- **Duplication** → Extract function/class
- **Long methods** → Break into private helpers (keep tests on public interface)
- **Shallow modules** → Combine or deepen
- **Feature envy** → Move logic to where data lives
- **Primitive obsession** → Introduce value objects
- **Existing code** the new code reveals as problematic
-61
View File
@@ -1,61 +0,0 @@
# Good and Bad Tests
## Good Tests
**Integration-style**: Test through real interfaces, not mocks of internal parts.
```typescript
// GOOD: Tests observable behavior
test("user can checkout with valid cart", async () => {
const cart = createCart();
cart.add(product);
const result = await checkout(cart, paymentMethod);
expect(result.status).toBe("confirmed");
});
```
Characteristics:
- Tests behavior users/callers care about
- Uses public API only
- Survives internal refactors
- Describes WHAT, not HOW
- One logical assertion per test
## Bad Tests
**Implementation-detail tests**: Coupled to internal structure.
```typescript
// BAD: Tests implementation details
test("checkout calls paymentService.process", async () => {
const mockPayment = jest.mock(paymentService);
await checkout(cart, payment);
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
});
```
Red flags:
- Mocking internal collaborators
- Testing private methods
- Asserting on call counts/order
- Test breaks when refactoring without behavior change
- Test name describes HOW not WHAT
- Verifying through external means instead of interface
```typescript
// BAD: Bypasses interface to verify
test("createUser saves to database", async () => {
await createUser({ name: "Alice" });
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
expect(row).toBeDefined();
});
// GOOD: Verifies through interface
test("createUser makes user retrievable", async () => {
const user = await createUser({ name: "Alice" });
const retrieved = await getUser(user.id);
expect(retrieved.name).toBe("Alice");
});
```
+21
View File
@@ -0,0 +1,21 @@
---
name: teach
description: "Explain a body of work plainly so a person actually understands it. Runs the `how` and `why` skills and weaves what they find into one clear explanation. Use for 'teach me this', 'help me really understand X', 'explain this change or subsystem to me'."
disable-model-invocation: true
---
# Teach
**You explain what a thing is, how it works, and why it's built that way, in one plain account at the person's pace. The goal is that they understand it, not that you change anything.** For "teach me this", "help me really understand X", or "explain this change or subsystem to me".
Teach sits on top of `how` and `why`. Get your bearings on what the work is and what it touches, then run `how` for how it works and `why` for why it's that way. Those are real skill invocations that do their own digging. Blend what they find into one plain explanation, lead with what matters to the person, and go deeper when they ask. Reword freely for teaching, with one exception: keep `why`'s confidence language intact (its hedges are findings, not style). Let those skills do the investigation. Don't redo it by hand.
1. Decide the few things they should walk away understanding. Choose them from why they're asking (about to change it, reviewing it, debugging it, new to it) and what they already know, both read from the conversation, not quizzed out of them. Skip what they plainly already know. Put the depth where their question is.
2. Let `how` and `why` do the work, don't redo it. Read the code yourself to get oriented, then run `how` for how it works and `why` for why. Run them in parallel and combine the results. Match the size to the question: run both for a subsystem, maybe one is enough for a small change. Keep `why` narrow by default since its full sweep is slow: put the narrowing in the ask itself (a scoped question, git plus a source or two) so `why` records the skipped categories per its own contract, and widen it only when the reasons are the point.
3. Start with a plain definition. Name the thing and say what it is in general terms, the way a senior engineer would say it out loud, with its common name if it has one. Then tie it to the case in front of you ("in X, we use this to ...") and build from there: how it works, the deeper reasons, the edge cases. Explain how it works, don't just name it. For each part, explain the idea so it clicks: the problem it solves and how it actually works. Walk through what happens as the person does the thing (opens a long chat, scrolls up) when that is what makes it land. Listing functions and constants is reference, not teaching. Don't print framing labels ("the one idea to hold onto", "the thing to walk away with", "the key insight", "at its core", "TL;DR"). Give the smallest complete answer first, a sentence or two, not a dense paragraph, then stop. Add layers when they ask. Never a wall of text.
4. Keep it a conversation, not a lecture or a performance. Offer to go deeper or move on, and follow their lead. No quizzes. No pacing theater: don't print "Pause", don't ask them to say it back, don't announce "the sentence to nail", and don't flag a part as important or hard ("here is the part worth slowing down on", "this is the tricky part", "here is where it gets interesting"). Just say it. When you would pause, stop and let them respond. Running one-shot with no live human, deliver it cleanly and put any offer to go deeper at the end.
5. Show, don't only tell, and build the picture up diagram by diagram. Open the diff, the code, or the debugger when that is the fastest way to land it. Draw when a picture lands faster than words. For anything with three or more moving parts, do not draw one diagram with all of them at once. Draw a short series instead, where each diagram redraws the last and adds a single part, so the reader watches the system assemble. That series is not a wall. It is the opposite of one, since each step is small and adds exactly one idea. A single all-at-once diagram, especially one saved for the end, is a reference, not teaching. Concretely, to teach a flow from A to B to C, draw it three times. First A to B. Then redraw and add C. Then redraw and add the return edge or the next piece. Three small growing diagrams beat one crowded diagram. Match the medium to the idea, and use both kinds when both help. A mermaid diagram fits a flow or structure where the labels carry the meaning. When the idea is spatial, like layout, overlap, scroll position, or a before and after, reach for the image-generation tool and draw it marker-on-whiteboard style with a few short labels, since image models garble long text. Generate that picture, don't settle for describing it in words. The build-up rule holds for generated images too. A single simple point needs no figure. A visual earns its place by teaching, not decorating.
Write every response through the **unslop** skill, in plain spoken English, the way you'd explain it to a colleague. Be tight, not terse: cut filler and hedging, keep the part that makes it click. Padding is the enemy, not ideas. Don't list functions and constants like a changelog. State the concrete mechanism, not a metaphor, a framing, or a preview of what is coming. This is the target density: "Virtualization runs in two parts, one for rendering and one for loading from disk. When an item scrolls out past the buffer, both its DOM node and its in-memory data are evicted." Normal sentence case, not all-lowercase. No em dashes. Prefer periods over commas. Keep each sentence to one or two commas. If clauses pile up, split them into separate sentences. Give each concept one name and keep it, since switching between synonyms for the same thing (bubble, message, row) makes the reader re-derive that they are the same. Avoid mirror sentences ("A without B, or B without A") and tidy closers ("the rest follows", "it all falls out"). The words in these steps are directions to you, not labels to print. Don't echo the scaffolding as headers or stock phrases.
**Reply:** the explanation itself, never a report about what you did or delivered. Lead with the main point, then the plain account of what it is, how it works, and why, and the threads worth chasing with `how` or `why`.
+130
View File
@@ -0,0 +1,130 @@
---
name: technical-writing
description: "Layered technical-writing standard: Diátaxis structure, Google developer style sentences, STE instruction rules, Global English syntax. Use for /technical-writing or when writing or reviewing docs, RFCs, readmes, PR descriptions, or commit messages."
disable-model-invocation: true
---
# Technical writing
The goal is writing a tired engineer understands on the first read. Four layers get you there, one question each: what kind of document is this, how do sentences address the reader, how much does each sentence carry, and can any sentence be read two ways. Apply all four.
Three rules sit above the layers:
- **Cut every word that does no work.** If the sentence survives without a word, the word goes. "In order to" is "to". "It is important to note that" is nothing.
- **Use the short, everyday word.** "Use", not "utilize". "Help", not "facilitate". "Do", not "perform". A long word has to buy its length with precision.
- **When a rule makes a sentence worse, fix the sentence another way or leave it alone.** The rules serve the reader. A sentence that follows every rule and sounds like a machine wrote it has failed.
The codebase is the word list. Write the real symbol, file, flag, or command name, not a synonym or a description of it.
Don't invent jargon. Use the words a developer would say out loud: "move", "delete", "a budget that only decreases", not "evacuate", "ratchet", or "endgame". A named pattern is fine when the doc says what it means the first time. Add new offenders to `unslop`'s abstract-metaphor rule with their replacement.
## Vary the rhythm
The layers decide what a document says and how much each sentence carries. A doc can obey all of them and still read machine-written: every sentence clipped short, no view anywhere, nothing specific.
- Mix sentence lengths on purpose. Short sentences land a point. Longer ones that take their time carry a fact with its condition or consequence.
- One thought per sentence does not mean one length per sentence. Split the sentence that carries two thoughts. Keep the long sentence that carries one.
- Have a view where the mode allows it. Explanation weighs trade-offs, so say what you make of them instead of listing pros and cons. Reference stays dry.
- Be specific over sterile. Not "schema changes can cause issues" but "a column rename fails the build".
## Pick the mode first (Diátaxis)
One document, one mode. Two questions pick it: does the content inform action (doing) or understanding (thinking), and does it serve learning or work?
- Action + learning: **tutorial**.
- Action + work: **how-to**.
- Understanding + work: **reference**.
- Understanding + learning: **explanation**.
Use the compass on a whole document or on one sentence. Reach for it whenever you feel unsure what you are writing. Gut feel is often wrong here.
**Tutorial: learning by doing.** You are the teacher. The learner's success is your job, not theirs. Open by saying what the learner will build, not what they will "learn". Every step produces a visible result, early and often. Tell them what they should see: the expected output, the prompt change, the log line. Cut explanation to one clause and a link. Teaching pauses break the lesson. Stay concrete. Write as "we", in commands: "First, do x. Now, do y."
**How-to: steps to a goal.** Solve a problem a person has, not an operation the machine can perform. Assume competence. Skip teaching. Action only: no digressions, no background, no completeness for its own sake. Link those instead. Allow forks and judgment: "If you want x, do y." Name the guide by the task: "How to calibrate the radar array", not "Radar array calibration".
**Reference: facts for lookup.** Describe. Only describe. No instruction, no persuasion, no opinion. Be dry, complete, and sure: state facts, options, limits, and errors with no hedging. Mirror the structure of the thing described, so code and docs can be navigated together. Put material where readers expect it. Generate from code where possible, so it stays true.
**Explanation: understanding and why.** One bounded topic, readable away from the product. Each title should tolerate an implicit "About..." in front. Anchor on a real why question. Give context: design decisions, history, constraints, alternatives. Opinion is allowed here and nowhere else.
Don't mix modes: no reference tables inside a tutorial, no tutorial hand-holding inside reference, no arguing inside a how-to. Split and link instead.
Source: diataxis.fr, fetched 2026-07-18.
## Write sentences to the reader (Google developer style)
- Talk to the reader as "you", in the present tense. "Will" only for things that genuinely happen later.
- Say who does what: "the compiler checks", not "is checked". Passive is fine only when the actor is unknown or beside the point.
- Write instructions as commands: "Click Submit." State facts plainly. Never "should be done".
- Put the condition before the instruction: "To delete the document, click Delete." The reader skips what does not apply.
- Put the common case first. Exceptions after.
- Sound like a knowledgeable friend. No buzzwords, no figurative language, no "please" in instructions, and never "simply", "easy", or "quickly" in a procedure. If it were simple, the reader would not be here.
- Don't pre-announce ("we will soon support...") and don't start consecutive sentences with the same phrase.
- Read the awkward sentence aloud. If it stays awkward, rewrite it.
- Link with words that say where the link goes: the page title or a short description. Never "click here". Prefer a sentence of context on the page over a link off it.
- Headings carry the point, not just the topic ("Pick the mode first", not "Modes"). Sentence case. A task heading is a bare verb phrase ("Create an instance"). A concept heading is a noun phrase. One h1 per page, no skipped levels.
- Numbered lists for sequences, bullets for everything else. Introduce a list with a complete sentence. Keep items parallel.
- Code goes in code font. UI elements go in bold. Use serial commas. Drop "etc." and say up front that a list is partial.
Source: developers.google.com/style, fetched 2026-07-18.
## Make statements load one at a time (STE rules)
- One instruction per sentence. One thought per sentence everywhere else.
- Split instructions longer than about 20 words and other sentences longer than about 25.
- Put the warning or condition before the step it guards: "If hot oil touches your skin, injuries can occur."
- Keep "the" and "a": "Remove backup file" reads two ways. "Remove the backup file" reads one.
- Give each word one meaning and one job, then keep it. If "check" means inspect, don't also use it for restrain.
- Pick one word per action and stick to it: "start", not "start" here and "initiate" there.
- Write procedures as direct commands, never as narration and never in the passive: "Install the component", not "the component must be installed".
- Avoid "-ing" words where you can. They take too many grammatical jobs and breed misreadings.
Source: asd-ste100.org (Issue 9, 2025), fetched 2026-07-18. The numbered rules and dictionary live in the spec PDF. The principles above are the transferable core.
## Leave no sentence open to two readings (Global English)
- Keep words like "only" and "not" next to the word they change: "only fails on growth" and "fails only on growth" say different things.
- Break up long noun strings: "the proto import budget check script" becomes "the script that checks the proto-import budget".
- Make every "it", "they", and "this" point at one obvious thing. Repeat the noun when in doubt. Never use "this" or "which" to point at a whole clause.
- Don't drop verbs: "Phase 1 moves the converters and Phase 2 the runtime" leaves Phase 2 without one. Give it one.
- Keep the small words that show structure. "Ensure that the switch is off" keeps "that" because it makes the sentence parse one way. Never trade clarity for word count.
- Repeat the article in a series when it prevents a misread: "the client and the host", not "the client and host", when they are two things.
- Say which parts "and" or "or" joins when a sentence can group two ways. "Both...and", "either...or", and "if...then" are free disambiguators.
- Use periods, not semicolons. Replace an em dash with a new sentence.
- Make text in parentheses a full grammatical unit or its own sentence. Never form plurals with "(s)".
- No slashes: write "a, b, or both" instead of "a/b" or "and/or".
- Call each thing by one name, everywhere. A doc that says "the gate", "the ratchet", and "the budget check" for one thing teaches three things. Rewording an unchanged sentence between edits costs the same way: don't churn what didn't change.
- Skip idioms, colloquialisms, Latin abbreviations, and metaphors. A non-native reader, a translator, and an agent all parse plain constructions best.
Source: Kohl, The Global English Style Guide (SAS Press). Guideline text fetched from the Internet Archive and the SAS sample chapter, 2026-07-18.
## Voice and repo specifics
- Apply the **unslop** skill to every doc this skill touches. That skill owns the slop-pattern catalog: AI vocabulary, filler, hedging, formatting tells.
- PR descriptions and commit messages are writing too. Every layer except Diátaxis applies to them.
- Product UI strings are not documentation. Use your product's copy guidelines for those.
- Indent code snippets with tabs. Write real paths and real symbols. Make every count or tree claim true at the commit that lands it, and include the command that regenerates it.
## Worked example
Before:
> Configuration of the proto import ratchet budget script parameters is performed via budget.json. Note that it's important to remember that running with --write, which updates the committed budget to reflect the current count, should only be done when lowering it. If exceeded, CI fails.
After:
> `budget.mjs` reads the committed budget from `budget.json` and counts the files that import protos. If the count exceeds the budget, CI fails. Run `budget.mjs --write` only to lower the budget.
The fixes, by layer: "configuration is performed" becomes "`budget.mjs` reads", so someone does something (Google). "Ratchet" goes away. The script's real filename does the naming (jargon rule). The five-noun string breaks up into plain clauses (Global English). The hedge "note that it's important to remember" is deleted (cut every word that does no work). The failure condition moves ahead of the step it explains (STE). The buried "should only be done when lowering" becomes a command with "only" next to its verb (STE). "If exceeded" gets a subject: the count (Global English).
## Review checklist
Apply to any prose this skill covers. Item 1 applies only to document sets:
1. Is each file one Diátaxis mode, with links where modes meet?
2. Is every instruction written as a command, with its condition in front?
3. Does any sentence carry two instructions or two thoughts? Split it.
4. Can any word be cut without losing meaning? Cut it.
5. Is "only" next to the word it changes? Does every "it" point at one thing? Does every clause keep its verb?
6. Does each thing have exactly one name across the docs?
7. Would a developer say these words out loud? Replace invented metaphors and fancy synonyms with the plain word or the real symbol name.
8. Are all symbols, paths, and counts real at this commit, with the commands that regenerate the counts?
@@ -0,0 +1,192 @@
---
name: thermo-nuclear-code-quality-review
description: Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a thermo-nuclear code quality review, thermonuclear review, deep code quality audit, or especially harsh maintainability review.
disable-model-invocation: true
---
# Thermo-Nuclear Code Quality Review
Use this skill for an unusually strict review focused on implementation quality, maintainability, abstraction quality, and codebase health.
Above all, this skill should push the reviewer to be **ambitious** about code structure. Do not merely identify local cleanup opportunities. Actively search for "code judo" moves: restructurings that preserve behavior while making the implementation dramatically simpler, smaller, more direct, and more elegant.
## Core Prompt
Start from this baseline:
> Perform a deep code quality audit of the current branch's changes.
> Rethink how to structure / implement the changes to meaningfully improve code quality without impacting behavior.
> Work to improve abstractions, modularity, reduce Spaghetti code, improve succinctness and legibility.
> Be ambitious, if there is a clear path to improving the implementation that involves restructuring some of the codebase, go for it.
> Be extremely thorough and rigorous. Measure twice, cut once.
## Non-Negotiable Additional Standards
Apply the baseline prompt above, plus these explicit review rules:
0. **Be ambitious about structural simplification.**
- Do not stop at "this could be a bit cleaner."
- Look for opportunities to reframe the change so that whole branches, helpers, modes, conditionals, or layers disappear entirely.
- Prefer the solution that makes the code feel inevitable in hindsight.
- Assume there is often a "code judo" move available: a re-organization that uses the existing architecture more effectively and makes the change dramatically simpler and more elegant.
- If you see a path to delete complexity rather than rearrange it, push hard for that path.
1. **Do not let a PR push a file from under 1k lines to over 1k lines without a very strong reason.**
- Treat this as a strong code-quality smell by default.
- Prefer extracting helpers, subcomponents, modules, or local abstractions instead of letting a file sprawl past 1000 lines.
- If the diff crosses that threshold, explicitly ask whether the code should be decomposed first.
- Only waive this if there is a compelling structural reason and the resulting file is still clearly organized.
2. **Do not allow random spaghetti growth in existing code.**
- Be highly suspicious of new ad-hoc conditionals, scattered special cases, or one-off branches inserted into unrelated flows.
- If a change adds "weird if statements in random places", treat that as a design problem, not a stylistic nit.
- Prefer pushing the logic into a dedicated abstraction, helper, state machine, policy object, or separate module instead of tangling an existing path.
- Call out changes that make the surrounding code harder to reason about, even if they technically work.
3. **Bias toward cleaning the design, not just accepting working code.**
- If behavior can stay the same while the structure becomes meaningfully cleaner, push for the cleaner version.
- Do not rubber-stamp "it works" implementations that leave the codebase messier.
- Strongly prefer simplifications that remove moving pieces altogether over refactors that merely spread the same complexity around.
4. **Prefer direct, boring, maintainable code over hacky or magical code.**
- Treat brittle, ad-hoc, or "magic" behavior as a code-quality problem.
- Be skeptical of generic mechanisms that hide simple data-shape assumptions.
- Flag thin abstractions, identity wrappers, or pass-through helpers that add indirection without buying clarity.
5. **Push hard on type and boundary cleanliness when they affect maintainability.**
- Question unnecessary optionality, `unknown`, `any`, or cast-heavy code when a clearer type boundary could exist.
- Prefer explicit typed models or shared contracts over loosely-shaped ad-hoc objects.
- If a branch relies on silent fallback to paper over an unclear invariant, ask whether the boundary should be made explicit instead.
6. **Keep logic in the canonical layer and reuse existing helpers.**
- Call out feature logic leaking into shared paths or implementation details leaking through APIs.
- Prefer existing canonical utilities/helpers over bespoke one-offs.
- Push code toward the right package, service, or module instead of normalizing architectural drift.
7. **Treat unnecessary sequential orchestration and non-atomic updates as design smells when the cleaner structure is obvious.**
- If independent work is serialized for no good reason, ask whether the flow should run in parallel instead.
- If related updates can leave state half-applied, push for a more atomic structure.
- Do not over-index on micro-optimizations, but do flag avoidable orchestration complexity that makes the implementation more brittle.
## Primary Review Questions
For every meaningful change, ask:
- Is there a "code judo" move that would make this dramatically simpler?
- Can this change be reframed so fewer concepts, branches, or helper layers are needed?
- Does this improve or worsen the local architecture?
- Did the diff add branching complexity where a better abstraction should exist?
- Did a previously cohesive module become more coupled, more stateful, or harder to scan?
- Is this logic living in the right file and layer?
- Did this change enlarge a file or component past a healthy size boundary?
- Are there repeated conditionals that signal a missing model or missing helper?
- Is the implementation direct and legible, or does it rely on special cases and incidental control flow?
- Is this abstraction actually earning its keep, or is it just a wrapper?
- Did the diff introduce casts, optionality, or ad-hoc object shapes that obscure the real invariant?
- Is this logic living in the canonical layer, or did the diff leak details across a boundary?
- Is this orchestration more sequential or less atomic than it needs to be?
## What to Flag Aggressively
Escalate findings when you see:
- A complicated implementation where a cleaner reframing could delete whole categories of complexity.
- Refactors that move code around but fail to reduce the number of concepts a reader must hold in their head.
- A file crossing 1000 lines due to the PR, especially if the new code could be split out.
- New conditionals bolted onto unrelated code paths.
- One-off booleans, nullable modes, or flags that complicate existing control flow.
- Feature-specific logic leaking into general-purpose modules.
- Generic "magic" handling that hides simple structure and makes the code harder to reason about.
- Thin wrappers or identity abstractions that add indirection without simplifying anything.
- Unnecessary casts, `any`, `unknown`, or optional params that muddy the real contract.
- Copy-pasted logic instead of extracted helpers.
- Narrow edge-case handling implemented in the middle of an already busy function.
- Refactors that technically pass tests but make the code less modular or less readable.
- "Temporary" branching that is likely to become permanent debt.
- Bespoke helpers where the codebase already has a canonical utility for the job.
- Logic added in the wrong layer/package when it should live somewhere more central.
- Sequential async flow where obviously independent work could stay simpler and clearer with parallel execution.
- Partial-update logic that leaves state less atomic than necessary.
## Preferred Remedies
When you identify a code-quality problem, prefer suggestions like:
- Delete a whole layer of indirection rather than polishing it.
- Reframe the state model so conditionals disappear instead of getting centralized.
- Change the ownership boundary so the feature becomes a natural extension of an existing abstraction.
- Turn special-case logic into a simpler default flow with fewer exceptions.
- Extract a helper or pure function.
- Split a large file into smaller focused modules.
- Move feature-specific logic behind a dedicated abstraction.
- Replace condition chains with a typed model or explicit dispatcher.
- Separate orchestration from business logic.
- Collapse duplicate branches into a single clearer flow.
- Delete wrappers that do not meaningfully clarify the API.
- Reuse the existing canonical helper instead of introducing a near-duplicate.
- Make type boundaries more explicit so the control flow gets simpler.
- Move the logic to the package/module/layer that already owns the concept.
- Parallelize independent work when that also simplifies the orchestration.
- Restructure related updates into a more atomic flow when partial state would be harder to reason about.
Do not be satisfied with "maybe rename this" feedback when the real issue is structural.
Do not be satisfied with a merely cleaner version of the same messy idea if there is a plausible path to a much simpler idea.
## Review Tone
Be direct, serious, and demanding about quality.
Do not be rude, but do not soften major maintainability issues into mild suggestions.
If the code is making the codebase messier, say so clearly.
If the implementation missed an opportunity for a dramatic simplification, say that clearly too.
Good phrases:
- `this pushes the file past 1k lines. can we decompose this first?`
- `this adds another special-case branch into an already busy flow. can we move this behind its own abstraction?`
- `this works, but it makes the surrounding code more spaghetti. let's keep the behavior and restructure the implementation.`
- `this feels like feature logic leaking into a shared path. can we isolate it?`
- `this abstraction seems unnecessary. can we just keep the direct flow?`
- `why does this need a cast / optional here? can we make the boundary more explicit instead?`
- `this looks like a bespoke helper for something we already have elsewhere. can we reuse the canonical one?`
- `i think there's a code-judo move here that makes this much simpler. can we reframe this so these branches disappear?`
- `this refactor moves complexity around, but doesn't really delete it. is there a way to make the model itself simpler?`
## Output Expectations
Prioritize findings in this order:
1. Structural code-quality regressions
2. Missed opportunities for dramatic simplification / code-judo restructuring
3. Spaghetti / branching complexity increases
4. Boundary / abstraction / type-contract problems that make the code harder to reason about
5. File-size and decomposition concerns
6. Modularity and abstraction issues
7. Legibility and maintainability concerns
Do not flood the review with low-value nits if there are larger structural issues.
Prefer a smaller number of high-conviction comments over a long list of cosmetic notes.
## Approval Bar
Do not approve merely because behavior seems correct.
The bar for approval is:
- no clear structural regression
- no obvious missed opportunity to make the implementation dramatically simpler when such a path is visible
- no unjustified file-size explosion
- no obvious spaghetti-growth from special-case branching
- no obviously hacky or magical abstraction that makes the code harder to reason about
- no unnecessary wrapper/cast/optionality churn obscuring the real design
- no clear architecture-boundary leak or avoidable canonical-helper duplication
- no missed opportunity for an obvious decomposition that would materially improve maintainability
Treat these as presumptive blockers unless the author can justify them clearly:
- the PR preserves a lot of incidental complexity when there is a plausible code-judo move that would delete it
- the PR pushes a file from below 1000 lines to above 1000 lines
- the PR adds ad-hoc branching that makes an existing flow more tangled
- the PR solves a local problem by scattering feature checks across shared code
- the PR adds an unnecessary abstraction, wrapper, or cast-heavy contract that makes the design more indirect
- the PR duplicates an existing helper or puts logic in the wrong layer when there is a clear canonical home
If those conditions are not met, leave explicit, actionable feedback and push for a cleaner decomposition.
@@ -0,0 +1,51 @@
---
name: thermo-nuclear-review
description: Comprehensive security and correctness audit of a branch's changes. Use for thermo nuclear, thermonuclear, or deep review requests, or branch/PR diff audits focused on bugs, breaking changes, security issues, devex regressions, and feature-gate leaks.
disable-model-invocation: true
---
# Thermo Nuclear Review
Use this skill for a comprehensive security and correctness audit of a checked-out branch.
## Prompt
You are a security expert performing a comprehensive review of a checked out branch. Audit this branch and its changes extremely thoroughly for bugs, changes that break existing features/functionality, and security vulnerabilities. Be EXTREMELY thorough, rigorous, careful, ambitious, and attentive. NOTHING can slip through.
# Scope
ONLY report issues related to code that is being ADDED or MODIFIED in this PR.
Focus on changes in the diff.
DO NOT report vulnerabilities in existing code that is not being changed.
# Guidelines
## Breaking Functionality Guidelines
This is a complex codebase, with many cross-package/module dependencies. Often simple code changes in one place have subtle interactions that break functionality elsewhere. You MUST be extremely thorough in tracing through possible side effects of the changes.
## Breaking Devex Guidelines
It can be easy to break developers' ability to run / build the code locally. You MUST catch changes that will impact users' developer experience. Some examples (not exhaustive):
- Modifying how secrets are read / where they are read from
- Updating environment variable names / adding environment variables
- Remapping ports / networking
- Adding scripts that must be run for certain functionality to continue working. Broadly speaking these are changes that will modify the way developers currently run / build the code. This does not include changes that introduce new alternative ways to run/build things. Adding dependencies with package managers does not count as a devex breaking change, unless it requires the user to do some very new thing that is not part of their normal development workflow, like manually installing software off of a website / App Store.
## Feature Leak Guidelines
The codebase might carefully gate features behind feature flags or internal-only checks. You MUST NOT allow any features that are meant to be behind a feature gate leak. These leaks are often subtle. Be VERY careful and thorough.
## Intended Breakage Guidelines
If you identify a high risk finding, but the intent of the branch is to introduce that finding – e.g. break some functionality, remove a feature flag, remove a safeguard – AND the scope of the change is well constrained, you SHOULD NOT waste the author's time by reporting the issue to them. However, if you believe it is likely that they are not aware of the full implications of their change, or you are worried that they are under-weighting the negative impacts (extreme example: a developer pushes a PR titled "Delete the database"), or you are worried that the change is actually malicious, you should still report the finding.
## Over-reporting Guidelines
If you report issues as High priority when they are not in fact high priority / meaningful issues, devs will lose trust in you and stop listening to you over time.
NEVER misreport the priority / importance of issues. Be extremely thorough in tracing issues end-to-end to gain complete, and total confidence before reporting.
# Final Response
IF you have medium-to-high priority / risk findings, and there is a PR for this branch, then check the PR/MR discussion using gh/glab cli to see if there are comments from BugBot or others present.
If so, take their findings into account. If they found issues you missed, evaluate them to determine if they are valid and include them in your report. If they found some of the same issues you did, see if there is anything from their findings that are worth incorporating into your response.
Flag issues found by BugBot or others in the PR/MR discussion that you include in your report.
# Critical Rules
- NEVER present issues with unfinished research. E.g. Never say something like, "The client has issue X, but if handled in the backend then this is ok." if you have access to the backend code and can check for yourself.
- You MUST wait to check the PR/MR discussion until AFTER you have performed your audit. This way you have fresh eyes while you review.
- Be EXTREMELY thorough, rigorous, careful, ambitious, and attentive. NOTHING can slip through.
+21
View File
@@ -0,0 +1,21 @@
---
name: thermos
description: "Launch both thermo-nuclear review subagents in parallel, then synthesize their findings. Use for thermos, double thermo review, or combined bug/security and code-quality branch audits."
disable-model-invocation: true
---
# Thermos
Run the two thermo review passes as async background subagents in parallel, then synthesize their results.
## Workflow
1. Determine the review scope from the user request, PR, current branch, or relevant changed files.
2. Gather the diff and any file/context excerpts needed for reviewers to evaluate the change without guessing.
3. Launch both subagents in the same message with `run_in_background: true`:
- `subagent_type: "thermo-nuclear-review-subagent"` for bugs, breakages, security, devex regressions, feature-flag leaks, and other branch-audit risks.
- `subagent_type: "thermo-nuclear-code-quality-review-subagent"` for maintainability, structure, file-size growth, spaghetti, abstractions, and codebase-health risks.
4. Pass each subagent the same scoped diff/file context and ask it to return prioritized findings with file references and evidence.
5. After both finish, synthesize the results with findings first, deduplicated across reviewers. Weight overlapping findings more heavily, resolve disagreements with your own judgment, and keep summaries brief.
If individual background summaries are already visible to the user, do not restate them wholesale. Surface the unified verdict, the highest-signal findings, and any remaining uncertainty.
-81
View File
@@ -1,81 +0,0 @@
---
name: to-issues
description: Break a plan, spec, or PRD into independently-grabbable issues on the project issue tracker using tracer-bullet vertical slices. Use when user wants to convert a plan into issues, create implementation tickets, or break down work into issues.
---
# To Issues
Break a plan into independently-grabbable issues using vertical slices (tracer bullets).
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
## Process
### 1. Gather context
Work from whatever is already in the conversation context. If the user passes an issue reference (issue number, URL, or path) as an argument, fetch it from the issue tracker and read its full body and comments.
### 2. Explore the codebase (optional)
If you have not already explored the codebase, do so to understand the current state of the code. Issue titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching.
### 3. Draft vertical slices
Break the plan into **tracer bullet** issues. Each issue is a thin vertical slice that cuts through ALL integration layers end-to-end, NOT a horizontal slice of one layer.
Slices may be 'HITL' or 'AFK'. HITL slices require human interaction, such as an architectural decision or a design review. AFK slices can be implemented and merged without human interaction. Prefer AFK over HITL where possible.
<vertical-slice-rules>
- Each slice delivers a narrow but COMPLETE path through every layer (schema, API, UI, tests)
- A completed slice is demoable or verifiable on its own
- Prefer many thin slices over few thick ones
</vertical-slice-rules>
### 4. Quiz the user
Present the proposed breakdown as a numbered list. For each slice, show:
- **Title**: short descriptive name
- **Type**: HITL / AFK
- **Blocked by**: which other slices (if any) must complete first
- **User stories covered**: which user stories this addresses (if the source material has them)
Ask the user:
- Does the granularity feel right? (too coarse / too fine)
- Are the dependency relationships correct?
- Should any slices be merged or split further?
- Are the correct slices marked as HITL and AFK?
Iterate until the user approves the breakdown.
### 5. Publish the issues to the issue tracker
For each approved slice, publish a new issue to the issue tracker. Use the issue body template below. Apply the `needs-triage` triage label so each issue enters the normal triage flow.
Publish issues in dependency order (blockers first) so you can reference real issue identifiers in the "Blocked by" field.
<issue-template>
## Parent
A reference to the parent issue on the issue tracker (if the source was an existing issue, otherwise omit this section).
## What to build
A concise description of this vertical slice. Describe the end-to-end behavior, not layer-by-layer implementation.
## Acceptance criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3
## Blocked by
- A reference to the blocking ticket (if any)
Or "None - can start immediately" if no blockers.
</issue-template>
Do NOT close or modify any parent issue.
-74
View File
@@ -1,74 +0,0 @@
---
name: to-prd
description: Turn the current conversation context into a PRD and publish it to the project issue tracker. Use when user wants to create a PRD from the current context.
---
This skill takes the current conversation context and codebase understanding and produces a PRD. Do NOT interview the user — just synthesize what you already know.
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
## Process
1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the PRD, and respect any ADRs in the area you're touching.
2. Sketch out the major modules you will need to build or modify to complete the implementation. Actively look for opportunities to extract deep modules that can be tested in isolation.
A deep module (as opposed to a shallow module) is one which encapsulates a lot of functionality in a simple, testable interface which rarely changes.
Check with the user that these modules match their expectations. Check with the user which modules they want tests written for.
3. Write the PRD using the template below, then publish it to the project issue tracker. Apply the `needs-triage` triage label so it enters the normal triage flow.
<prd-template>
## Problem Statement
The problem that the user is facing, from the user's perspective.
## Solution
The solution to the problem, from the user's perspective.
## User Stories
A LONG, numbered list of user stories. Each user story should be in the format of:
1. As an <actor>, I want a <feature>, so that <benefit>
<user-story-example>
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
</user-story-example>
This list of user stories should be extremely extensive and cover all aspects of the feature.
## Implementation Decisions
A list of implementation decisions that were made. This can include:
- The modules that will be built/modified
- The interfaces of those modules that will be modified
- Technical clarifications from the developer
- Architectural decisions
- Schema changes
- API contracts
- Specific interactions
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
## Testing Decisions
A list of testing decisions that were made. Include:
- A description of what makes a good test (only test external behavior, not implementation details)
- Which modules will be tested
- Prior art for the tests (i.e. similar types of tests in the codebase)
## Out of Scope
A description of the things that are out of scope for this PRD.
## Further Notes
Any further notes about the feature.
</prd-template>
+34 -22
View File
@@ -7,7 +7,7 @@ description: Generate idiomatic Typst (.typ) code, edit and troubleshoot Typst d
## Overview
This skill helps agents generate, edit, and reason about Typst documents. It provides quick‑start examples, detailed workflows, and links to the full Typst documentation (guides, tutorials, reference).
This skill helps agents generate, edit, and reason about Typst documents. It provides quick‑start examples, detailed workflows, and links to the Typst documentation (overview, guides, tutorials, reference).
## Minimal document example
@@ -38,21 +38,33 @@ This is a paragraph in Typst.
## Workflows
- **Creating a new Typst project**: Use the "Minimal document example" above as a starting point. Skim the tutorial for the basics ([docs/tutorial/writing-in-typst.md](docs/tutorial/writing-in-typst.md)), then create the `.typ` file(s). After each `.typ` edit, follow the post-edit formatting checks below when `typstyle` is available.
- **Editing existing content**: Locate the target text and apply changes; confirm syntax against the reference when needed ([docs/reference/](docs/reference/)). After each modified `.typ` file, follow the post-edit formatting checks below.
- **Formatting & Styling**: Consult the styling guide ([docs/reference/styling.md](docs/reference/styling.md)) for `set rule`, `show rule`, and custom themes.
- **Creating a new Typst project**: Use the "Minimal document example" above as a starting point. Skim the tutorial for the basics ([docs/tutorial/1-writing.md](docs/tutorial/1-writing.md)), then create the `.typ` file(s). After each `.typ` edit, follow the post-edit formatting checks below when `typstyle` is available.
- **Editing existing content**: Locate the target text and apply changes; confirm syntax against the reference when needed ([docs/reference/index.md](docs/reference/index.md)). After each modified `.typ` file, follow the post-edit formatting checks below.
- **Formatting & Styling**: Consult the styling guide ([docs/reference/language/styling.md](docs/reference/language/styling.md)) for `set rule`, `show rule`, selectors, and transformations.
## Documentation
- **Syntax & foundations**: `docs/reference/syntax.md`
- **Styling & show/set rules**: `docs/reference/styling.md`
- **Scripting & runtime behavior**: `docs/reference/scripting.md`
- **Page setup & tables**: `docs/guides/page-setup.md` and `docs/guides/tables.md`
- **Task-oriented authoring help**: `docs/tutorial/writing-in-typst.md`, `docs/guides/*.md`, and `docs/reference/**/*.md`
- **Orientation**: `docs/overview.md` for a high-level introduction, `docs/reference/index.md` for the reference structure, and `docs/tutorial/index.md` for the tutorial sequence.
- **Tutorial**: `docs/tutorial/1-writing.md` for basic markup, functions, labels, citations, and math; `docs/tutorial/2-formatting.md` for set rules, page setup, headings, and text formatting; `docs/tutorial/3-advanced.md` for templates, show rules, and more complex styling; `docs/tutorial/4-template.md` for reusable templates and packages.
- **Language syntax**: `docs/reference/language/syntax.md` for markup/math/code modes, comments, escapes, and identifiers.
- **Language scripting**: `docs/reference/language/scripting.md` for expressions, code/content blocks, bindings, conditionals, loops, fields, methods, modules, packages, and operators.
- **Language styling**: `docs/reference/language/styling.md` for set rules, show rules, selectors, and transformations.
- **Language context**: `docs/reference/language/context.md` for style context, location context, nested contexts, and compiler iterations.
- **Foundations**: `docs/reference/library/foundations.md` for basic types/functions, `std`, `sys.version`, and `sys.inputs`.
- **Document model**: `docs/reference/library/model.md` for headings, figures, bibliography, citations, references, numbering, outlines, lists, tables, and document structure.
- **Layout**: `docs/reference/library/layout.md` for arranging elements on the page: page, block, box, grid, columns, alignment, spacing, transforms, and measurement.
- **Text**: `docs/reference/library/text.md` for text styling and the `text` function.
- **Math**: `docs/reference/library/math.md` for math syntax, symbols, equations, alignment, fonts, accessibility, and math functions.
- **Drawing and media**: `docs/reference/library/visualize.md` for shapes, image/graphics primitives, color, gradients, strokes, and visual accessibility.
- **Introspection**: `docs/reference/library/introspection.md` for counters, state, locations, `query`, and document-aware generated content.
- **Data loading**: `docs/reference/library/data-loading.md` for loading and encoding external data such as CSV, JSON, TOML, YAML, XML, CBOR, and raw files.
- **Symbols and emoji**: `docs/reference/library/sym.md` for named symbols and shorthands; `docs/reference/library/emoji.md` for emoji.
- **Export formats**: `docs/reference/export/pdf.md` for PDF standards and PDF-specific features; `docs/reference/export/html.md` for HTML export and typed HTML; `docs/reference/export/bundle.md` for multi-output bundles and assets; `docs/reference/export/svg.md` and `docs/reference/export/png.md` for image exports.
- **Guides**: `docs/guides/page-setup.md` for pages, margins, headers, footers, numbering, and columns; `docs/guides/tables.md` for semantic tables and table styling; `docs/guides/accessibility.md` for semantic structure, alt text, language, PDF accessibility, and export considerations; `docs/guides/for-latex-users.md` for LaTeX-to-Typst translation.
## Detailed instructions
1. **PRIORITY: Trust local documentation**. Your internal training data regarding Typst may be outdated or hallucinated. Always verify function names, parameters, and syntax against the local `docs/` folder before generating code.
1. **PRIORITY: Trust local documentation**. Your internal training data regarding Typst may be outdated or hallucinated. Always verify function names, parameters, and syntax against the local Typst 0.15.0 `docs/` folder before generating code.
2. **Read the relevant documentation** using local file search and open tools on the paths above.
3. **Use local docs for syntax and reference questions**. Verify syntax, function names, parameters, and reference behavior from the bundled docs. Run a minimal Typst probe only when runtime or evaluation behavior remains unclear after checking the docs.
4. **Generate or modify the `.typ` source** according to the user's request.
@@ -63,9 +75,9 @@ This is a paragraph in Typst.
### Probing uncertain behavior
- Use a probe when the bundled docs do not settle runtime or evaluation behavior.
- Model the case with Typst scripting as described in [docs/reference/scripting.md](docs/reference/scripting.md).
- When a probe is necessary, prefer a fileless probe through stdin instead of creating scratch `.typ` files. Expose the value with `metadata(...) <probe>` and read it with `typst query - "<probe>" --field value --one`. See [docs/reference/introspection/query.md](docs/reference/introspection/query.md) and [docs/reference/introspection/metadata.md](docs/reference/introspection/metadata.md).
- Example: `printf '#metadata(1 + 2) <probe>\n' | typst query - "<probe>" --field value --one`
- Model the case with Typst scripting as described in [docs/reference/language/scripting.md](docs/reference/language/scripting.md).
- When a probe is necessary, prefer a fileless expression probe with `typst eval` instead of creating scratch `.typ` files. See [docs/reference/library/foundations.md](docs/reference/library/foundations.md) for system values and [docs/reference/library/introspection.md](docs/reference/library/introspection.md) for contextual document queries.
- Example: `typst eval '1 + 2'`
### Post-edit formatting checks
@@ -79,16 +91,16 @@ This is a paragraph in Typst.
### Critical distinctions
- **Arrays**: `(item1, item2)` (parentheses). See [docs/reference/foundations/array.md](docs/reference/foundations/array.md).
- **Dictionaries**: `(key: value, key2: value2)` (parentheses with colons). See [docs/reference/foundations/dictionary.md](docs/reference/foundations/dictionary.md).
- **Content blocks**: `[markup content]` (square brackets). See [docs/reference/foundations/content.md](docs/reference/foundations/content.md).
- **Arrays**: `(item1, item2)` (parentheses). See [docs/reference/library/foundations.md](docs/reference/library/foundations.md).
- **Dictionaries**: `(key: value, key2: value2)` (parentheses with colons). See [docs/reference/library/foundations.md](docs/reference/library/foundations.md).
- **Content blocks**: `[markup content]` (square brackets). See [docs/reference/language/scripting.md](docs/reference/language/scripting.md).
- **NO tuples**: Typst only has arrays.
### Hash usage (markup vs code)
- Use `#` to start a code expression inside markup or content blocks; it disambiguates code from text. This is required for content-producing function calls and field access in markup: `#figure[...]`, `#image("file.png")`, `text(...)[#numbering(...)]`.
- Do not use `#` inside code contexts (argument lists, code blocks, show-rule bodies). Example: `#figure(image("file.png"))` (no `#` before `image`).
- Reference: [docs/reference/scripting.md](docs/reference/scripting.md), [docs/tutorial/writing-in-typst.md](docs/tutorial/writing-in-typst.md)
- Reference: [docs/reference/language/scripting.md](docs/reference/language/scripting.md), [docs/tutorial/1-writing.md](docs/tutorial/1-writing.md)
```typst
// Incorrect (missing # inside content block)
@@ -130,16 +142,16 @@ text(...)[(#numbering(...))]
## Advanced features
- **Custom themes**: See [docs/reference/styling.md](docs/reference/styling.md) for theme creation.
- **Scripting**: Use Typst's scripting capabilities ([docs/reference/scripting.md](docs/reference/scripting.md)) for automatic generation.
- **Math and visualisation**: Reference [docs/reference/math/](docs/reference/math/) and [docs/reference/visualize/](docs/reference/visualize/) for formulas and diagrams.
- **Reusable styling**: See [docs/reference/language/styling.md](docs/reference/language/styling.md) for set rules, show rules, and styling scoped by code or content blocks.
- **Scripting**: Use Typst's scripting capabilities ([docs/reference/language/scripting.md](docs/reference/language/scripting.md)) for automatic generation.
- **Math and visualisation**: Reference [docs/reference/library/math.md](docs/reference/library/math.md) and [docs/reference/library/visualize.md](docs/reference/library/visualize.md) for formulas and diagrams.
### For large projects
When working on large projects, consider organizing the project across multiple files.
- Use `#include "file.typ"` to split into multiple files
- Relevant documentation: [docs/reference/foundations/module.md](docs/reference/foundations/module.md)
- Relevant documentation: [docs/reference/language/scripting.md](docs/reference/language/scripting.md)
## Troubleshooting
@@ -152,7 +164,7 @@ If you see "unknown font family" warnings, remove the font specification to use
If import fails with "package not found":
- Verify exact package name and version on Typst Universe.
- Check for typos in `@preview/package:version` syntax.
- Check for typos in `@preview/package:version` syntax. See [docs/reference/language/scripting.md](docs/reference/language/scripting.md) for package import syntax and [docs/guides/for-latex-users.md](docs/guides/for-latex-users.md) for Typst Universe examples.
### Compilation errors
@@ -1,64 +1,110 @@
# 0.1.0
## Breaking changes
# Breaking changes
- When using the CLI, you now have to use subcommands:
- `typst compile file.typ` or `typst c file.typ` to create a PDF
- `typst watch file.typ` or `typst w file.typ` to compile and watch
- `typst fonts` to list all fonts
- Manual counters now start at zero. Read the "How to step" section [here](/docs/reference/introspection/counter/) for more details
- The [bibliography styles](/docs/reference/model/bibliography/#parameters-style) `"author-date"` and `"author-title"` were renamed to `"chicago-author-date"` and `"chicago-author-title"`
## Figure improvements
- Manual counters now start at zero. Read the "How to step" section here
for more details
- Figures now automatically detect their content and adapt their behavior. Figures containing tables, for instance, are automatically prefixed with "Table X" and have a separate counter
- The figure's supplement (e.g. "Figure" or "Table") can now be customized
- In addition, figures can now be completely customized because the show rule gives access to the automatically resolved kind, supplement, and counter
- The bibliography styles `{"author-date"}` and `{"author-title"}` were
renamed to `{"chicago-author-date"}` and `{"chicago-author-title"}`
## Bibliography improvements
# Figure improvements
- Figures now automatically detect their content and adapt their
behavior. Figures containing tables, for instance, are automatically
prefixed with "Table X" and have a separate counter
- The figure's supplement (e.g. "Figure" or "Table") can now be
customized
- In addition, figures can now be completely customized because the show
rule gives access to the automatically resolved kind, supplement, and
counter
# Bibliography improvements
- The `bibliography` now also accepts multiple bibliography paths (as an
array)
- Parsing of BibLaTeX files is now more permissive (accepts non-numeric
edition, pages, volumes, dates, and Jabref-style comments; fixed
abbreviation parsing)
- The [`bibliography`](/docs/reference/model/bibliography/) now also accepts multiple bibliography paths (as an array)
- Parsing of BibLaTeX files is now more permissive (accepts non-numeric edition, pages, volumes, dates, and Jabref-style comments; fixed abbreviation parsing)
- Labels and references can now include `:` and `.` except at the end
- Fixed APA bibliography ordering
## Drawing additions
# Drawing additions
- Added [`polygon`](/docs/reference/visualize/polygon/) function for drawing polygons
- Added support for clipping in [boxes](/docs/reference/layout/box/#parameters-clip) and [blocks](/docs/reference/layout/block/#parameters-clip)
- Added `polygon` function for drawing polygons
## Command line interface
- Added support for clipping in boxes and blocks
# Command line interface
- Now returns with non-zero status code if there is an error
- Now watches the root directory instead of the current one
- Now puts the PDF file next to input file by default
- Now accepts more kinds of input files (e.g. `/dev/stdin`)
- Added `--open` flag to directly open the PDF
## Miscellaneous improvements
# Miscellaneous improvements
- Added `yaml` function to load data from YAML files
- Added [`yaml`](/docs/reference/data-loading/yaml/) function to load data from YAML files
- Added basic i18n for a few more languages (IT, RU, ZH, FR, PT)
- Added numbering support for Hebrew
- Added support for [integers](/docs/reference/foundations/int/) with base 2, 8, and 16
- Added symbols for double bracket and laplace operator
- The [`link`](/docs/reference/model/link/) function now accepts [labels](/docs/reference/foundations/label/)
- The link syntax now allows more characters
- Improved justification of Japanese and Chinese text
- Calculation functions behave more consistently w.r.t to non-real results
- Replaced deprecated angle brackets
- Reduced maximum function call depth from 256 to 64
- Fixed [`first-line-indent`](/docs/reference/model/par/#parameters-first-line-indent) being not applied when a paragraph starts with styled text
- Fixed extraneous spacing in unary operators in equations
- Fixed block spacing, e.g. in `block(above: 1cm, below: 1cm, ..)`
- Fixed styling of text operators in math
- Fixed invalid parsing of language tag in raw block with a single backtick
- Fixed bugs with displaying counters and state
- Fixed crash related to page counter
- Fixed crash when [`symbol`](/docs/reference/foundations/symbol/) function was called without arguments
- Fixed crash in bibliography generation
- Fixed access to label of certain content elements
- Fixed line number in error message for CSV parsing
- Fixed invalid autocompletion after certain markup elements
## Contributors
- Added numbering support for Hebrew
- Added support for integers with base 2, 8, and 16
- Added symbols for double bracket and laplace operator
- The `link` function now accepts labels
- The link syntax now allows more characters
- Improved justification of Japanese and Chinese text
- Calculation functions behave more consistently w.r.t to non-real
results
- Replaced deprecated angle brackets
- Reduced maximum function call depth from 256 to 64
- Fixed `first-line-indent` being not applied when a paragraph starts
with styled text
- Fixed extraneous spacing in unary operators in equations
- Fixed block spacing, e.g. in `{block(above: 1cm, below: 1cm, ..)}`
- Fixed styling of text operators in math
- Fixed invalid parsing of language tag in raw block with a single
backtick
- Fixed bugs with displaying counters and state
- Fixed crash related to page counter
- Fixed crash when `symbol` function was called without arguments
- Fixed crash in bibliography generation
- Fixed access to label of certain content elements
- Fixed line number in error message for CSV parsing
- Fixed invalid autocompletion after certain markup elements
@@ -1,110 +1,201 @@
# 0.10.0
# Bibliography management
## Bibliography management
- Added support for citation collapsing (e.g. `[[1]-[3]]` instead of
`[[1], [2], [3]]`) if requested by a CSL style
- Fixed bug where an additional space would appear after a group of
citations
- Added support for citation collapsing (e.g. `[1]-[3]` instead of `[1], [2], [3]`) if requested by a CSL style
- Fixed bug where an additional space would appear after a group of citations
- Fixed link show rules for links in the bibliography
- Fixed show-set rules on citations
- Fixed bibliography-related crashes that happened on some systems
- Corrected name of the GB/T 7714 family of styles from 7114 to 7714
- Fixed missing title in some bibliography styles
- Fixed printing of volumes in some styles
- Fixed delimiter order for contributors in some styles (e.g. APA)
- Fixed behavior of alphanumeric style
- Fixed multiple bugs with GB/T 7714 style
- Fixed escaping in Hayagriva values
- Fixed crashes with empty dates in Hayagriva files
- Fixed bug with spacing around math blocks
- Fixed title case formatting after verbatim text and apostrophes
- Page ranges in `.bib` files can now be arbitrary strings
- Multi-line values in `.bib` files are now parsed correctly
- Entry keys in `.bib` files now allow more characters
- Fixed error message for empty dates in `.bib` files
- Added support for years of lengths other than 4 without leading zeros in `.bib` files
- More LaTeX commands (e.g. for quotes) are now respected in `.bib` files
## Visualization
- Added support for years of lengths other than 4 without leading zeros
in `.bib` files
- More LaTeX commands (e.g. for quotes) are now respected in `.bib`
files
# Visualization
- Added support for patterns as fills and strokes
- The `alpha` parameter of the `components` function on colors is now a
named parameter **(Breaking change)**
- Added support for the Oklch color space
- Added support for [patterns](/docs/reference/visualize/tiling/) as fills and strokes
- The `alpha` parameter of the [`components`](/docs/reference/visualize/color/#definitions-components) function on colors is now a named parameter **(Breaking change)**
- Added support for the [Oklch](/docs/reference/visualize/color/#definitions-oklch) color space
- Improved conversions between colors in different color spaces
- Removed restrictions on [Oklab](/docs/reference/visualize/color/#definitions-oklab) chroma component
- Fixed [clipping](/docs/reference/layout/block/#parameters-clip) on blocks and boxes without a stroke
- Fixed bug with [gradients](/docs/reference/visualize/gradient/) on math
- Removed restrictions on Oklab chroma component
- Fixed clipping on blocks and boxes without a stroke
- Fixed bug with gradients on math
- Fixed bug with gradient rotation on text
- Fixed bug with gradient colors in PDF
- Fixed relative base of Oklab chroma ratios
- Fixed Oklab color negation
## Text and Layout
# Text and Layout
- CJK text can now be emphasized with the `*` and `_` syntax even when
there are no spaces
- CJK text can now be emphasized with the `*` and `_` syntax even when there are no spaces
- Added basic i18n for Greek and Estonian
- Improved default [figure caption separator](/docs/reference/model/figure/#definitions-caption-separator) for Chinese, French, and Russian
- Changed default [figure supplement](/docs/reference/model/figure/#parameters-supplement) for Russian to short form
- Fixed [CJK-Latin-spacing](/docs/reference/text/text/#parameters-cjk-latin-spacing) before line breaks and in [`locate`](/docs/reference/introspection/locate/) calls
- Improved default figure caption separator for Chinese, French, and
Russian
- Changed default figure supplement for Russian to short form
- Fixed CJK-Latin-spacing before line breaks and in `locate` calls
- Fixed line breaking at the end of links
## Math
# Math
- Added [`mid`](/docs/reference/math/lr/#functions-mid) function for scaling a delimiter up to the height of the surrounding [`lr`](/docs/reference/math/lr/#functions-lr) group
- The [`op`](/docs/reference/math/op/) function can now take any content, not just strings
- Improved documentation for [math alignment](/docs/reference/math/#alignment)
- Fixed swallowing of trailing comma when a symbol is used in a function-like way (e.g. `pi(a,b,)`)
- Added `mid` function for scaling a delimiter up to the height of the
surrounding `lr` group
## Scripting
- The `op` function can now take any content, not just strings
- Any non-identifier dictionary key is now interpreted as an expression: For instance, `((key): value)` will create a dictionary with a dynamic key
- The [`stroke`](/docs/reference/visualize/stroke/) type now has a constructor that converts a value to a stroke or creates one from its parts
- Added constructor for [`arguments`](/docs/reference/foundations/arguments/) type
- Added [`calc.div-euclid`](/docs/reference/foundations/calc/#functions-div-euclid) and [`calc.rem-euclid`](/docs/reference/foundations/calc/#functions-rem-euclid) functions
- Fixed equality of [`arguments`](/docs/reference/foundations/arguments/)
- Fixed [`repr`](/docs/reference/foundations/repr/)of [`cmyk`](/docs/reference/visualize/color/#definitions-cmyk) colors
- Fixed crashes with provided elements like figure captions, outline entries, and footnote entries
- Improved documentation for math alignment
## Tooling and Diagnostics
- Fixed swallowing of trailing comma when a symbol is used in a
function-like way (e.g. `pi(a,b,)`)
# Scripting
- Any non-identifier dictionary key is now interpreted as an expression:
For instance, `{((key): value)}` will create a dictionary with a
dynamic key
- The `stroke` type now has a constructor that converts a value to a
stroke or creates one from its parts
- Added constructor for `arguments` type
- Added `calc.div-euclid` and `calc.rem-euclid` functions
- Fixed equality of `arguments`
- Fixed `repr` of `cmyk` colors
- Fixed crashes with provided elements like figure captions, outline
entries, and footnote entries
# Tooling and Diagnostics
- Show rules that match on their own output now produce an appropriate
error message instead of a crash (this is a first step, in the future
they will just work)
- Too highly or infinitely nested layouts now produce error messages
instead of crashes
- Show rules that match on their own output now produce an appropriate error message instead of a crash (this is a first step, in the future they will just work)
- Too highly or infinitely nested layouts now produce error messages instead of crashes
- Added hints for invalid identifiers
- Added hint when trying to use a manually constructed footnote or outline entry
- Added hint when trying to use a manually constructed footnote or
outline entry
- Added missing details to autocompletions for types
- Improved error message when passing a named argument where a positional one is expected
- Improved error message when passing a named argument where a
positional one is expected
- Jump from click now works on raw blocks
## Export
# Export
- PDF compilation output is now again fully byte-by-byte reproducible if
the document's `date` is set manually
- PDF compilation output is now again fully byte-by-byte reproducible if the document's [`date`](/docs/reference/model/document/#parameters-date) is set manually
- Fixed color export in SVG
- Fixed PDF metadata encoding of multiple [authors](/docs/reference/model/document/#parameters-author)
## Command line interface
- Fixed PDF metadata encoding of multiple authors
# Command line interface
- Fixed a major bug where `typst watch` would confuse files and fail to
pick up updates
- Fetching of the release metadata in `typst update` now respects
proxies
- Fixed a major bug where `typst watch` would confuse files and fail to pick up updates
- Fetching of the release metadata in `typst update` now respects proxies
- Fixed bug with `--open` flag on Windows when the path contains a space
- The `TYPST_FONT_PATHS` environment variable can now contain multiple paths (separated by `;` on Windows and `:` elsewhere)
- Updated embedded New Computer Modern fonts to version 4.7
- The watching process doesn't stop anymore when the main file contains invalid UTF-8
## Miscellaneous Improvements
- The `TYPST_FONT_PATHS` environment variable can now contain multiple
paths (separated by `;` on Windows and `:` elsewhere)
- Updated embedded New Computer Modern fonts to version 4.7
- The watching process doesn't stop anymore when the main file contains
invalid UTF-8
# Miscellaneous Improvements
- Parallelized image encoding in PDF export
- Improved the internal representation of content for improved performance
- Improved the internal representation of content for improved
performance
- Optimized introspection (query, counter, etc.) performance
- The [document title](/docs/reference/model/document/#parameters-title) can now be arbitrary content instead of just a string
- The [`number-align`](/docs/reference/model/enum/#parameters-number-align) parameter on numbered lists now also accepts vertical alignments
- Fixed selectors on [quote](/docs/reference/model/quote/) elements
- Fixed parsing of `#return` expression in markup
- The document title can now be arbitrary content instead of just a
string
- The `number-align` parameter on numbered lists now also accepts
vertical alignments
- Fixed selectors on quote elements
- Fixed parsing of `[#return]` expression in markup
- Fixed bug where inline equations were displayed in equation outlines
- Fixed potential CRLF issue in [`raw`](/docs/reference/text/raw/) blocks
- Fixed potential CRLF issue in `raw` blocks
- Fixed a bug where Chinese numbering couldn't exceed the number 255
## Development
# Development
- Merged `typst` and `typst-library` and extracted `typst-pdf`, `typst-svg`, and `typst-render` into separate crates
- The Nix flake now includes the git revision when running `typst --version`
- Merged `typst` and `typst-library` and extracted `typst-pdf`,
`typst-svg`, and `typst-render` into separate crates
## Contributors
- The Nix flake now includes the git revision when running
`typst --version`
@@ -1,203 +1,424 @@
# 0.11.0
# Tables
## Tables
- Tables are now *much* more flexible, read the new Table Guide to get
started
- Added `table.cell` element for per-cell configuration
- Cells can now span multiple columns or rows
- The stroke of individual cells can now be customized
- The `align` and `inset` arguments of the table function now also take
`{(x, y) => ..}` functions
- Added `table.hline` and `table.vline` for convenient line
customization
- Added `table.header` element for table headers that repeat on every
page
- Added `table.footer` element for table footers that repeat on every
page
- All the new table functionality is also available for grids
- Tables are now _much_ more flexible, read the new [Table Guide](/docs/guides/tables/) to get started
- Added [`table.cell`](/docs/reference/model/table/#definitions-cell) element for per-cell configuration
- Cells can now span multiple [columns](/docs/reference/model/table/#definitions-cell-colspan) or [rows](/docs/reference/model/table/#definitions-cell-rowspan)
- The [stroke](/docs/reference/model/table/#definitions-cell-stroke) of individual cells can now be customized
- The [`align`](/docs/reference/model/table/#parameters-align) and [`inset`](/docs/reference/model/table/#parameters-inset) arguments of the table function now also take `(x, y) => ..` functions
- Added [`table.hline`](/docs/reference/model/table/#definitions-hline) and [`table.vline`](/docs/reference/model/table/#definitions-vline) for convenient line customization
- Added [`table.header`](/docs/reference/model/table/#definitions-header) element for table headers that repeat on every page
- Added [`table.footer`](/docs/reference/model/table/#definitions-footer) element for table footers that repeat on every page
- All the new table functionality is also available for [grids](/docs/reference/layout/grid/)
- Fixed gutter-related bugs
_Thanks to @PgBiel for his work on tables!_
*Thanks to <https://github.com/PgBiel> for his work on tables!*
## Templates
# Templates
- You can now use template packages to get started with new projects. Click _Start from template_ on the web app's dashboard and choose your preferred template or run the `typst init <template>` command in the CLI. You can [browse the available templates here](https://typst.app/universe/search/?kind=templates).
- Switching templates after the fact has become easier. You can just import a styling function from a different template package.
- Package authors can now submit their own templates to the [package repository](https://github.com/typst/packages). Share a template for a paper, your institution, or an original work to help the community get a head start on their projects.
- Templates and packages are now organized by category and discipline. Filter packages by either taxonomy in the _Start from template_ wizard. If you are a package author, take a look at the new documentation for [categories](https://github.com/typst/packages/blob/main/docs/CATEGORIES.md) and [disciplines](https://github.com/typst/packages/blob/main/docs/DISCIPLINES.md).
- You can now use template packages to get started with new projects.
Click *Start from template* on the web app's dashboard and choose your
preferred template or run the `typst init <template>` command in
the CLI. You can [browse the available templates
here](https://typst.app/universe/search/?kind=templates).
## Context
- Switching templates after the fact has become easier. You can just
import a styling function from a different template package.
- Added _context expressions:_ Read the chapter on [context](/docs/reference/context/) to get started
- With context, you can access settable properties, e.g. `context text.lang` to access the language set via `set text(lang: "..")`
- The following existing functions have been made contextual: [`query`](/docs/reference/introspection/query/), [`locate`](/docs/reference/introspection/locate/), [`measure`](/docs/reference/layout/measure/), [`counter.display`](/docs/reference/introspection/counter/#definitions-display), [`counter.at`](/docs/reference/introspection/counter/#definitions-at), [`counter.final`](/docs/reference/introspection/counter/#definitions-final), [`state.at`](/docs/reference/introspection/state/#definitions-at), and [`state.final`](/docs/reference/introspection/state/#definitions-final)
- Added contextual methods [`counter.get`](/docs/reference/introspection/counter/#definitions-get) and [`state.get`](/docs/reference/introspection/state/#definitions-get) to retrieve the value of a counter or state in the current context
- Added contextual function [`here`](/docs/reference/introspection/here/) to retrieve the [location](/docs/reference/introspection/location/) of the current context
- The [`locate`](/docs/reference/introspection/locate/) function now returns the location of a selector's unique match. Its old behavior has been replaced by context expressions and only remains temporarily available for compatibility.
- The [`counter.at`](/docs/reference/introspection/counter/#definitions-at) and [`state.at`](/docs/reference/introspection/state/#definitions-at) methods are now more flexible: They directly accept any kind of [locatable](/docs/reference/introspection/location/#locatable) selector with a unique match (e.g. a label) instead of just locations
- When context is available, [`counter.display`](/docs/reference/introspection/counter/#definitions-display) now directly returns the result of applying the numbering instead of yielding opaque content. It should not be used anymore without context. (Deprecation planned)
- The `state.display` function should not be used anymore, use [`state.get`](/docs/reference/introspection/state/#definitions-get) instead (Deprecation planned)
- The `location` argument of [`query`](/docs/reference/introspection/query/), [`counter.final`](/docs/reference/introspection/counter/#definitions-final), and [`state.final`](/docs/reference/introspection/state/#definitions-final) should not be used anymore (Deprecation planned)
- The `styles` argument of the `measure` function should not be used anymore (Deprecation planned)
- The `style` function should not be used anymore, use context instead (Deprecation planned)
- The correct context is now also provided in various other places where it is available, e.g. in show rules, layout callbacks, and numbering functions in the outline
- Package authors can now submit their own templates to the [package
repository](https://github.com/typst/packages). Share a template for a
paper, your institution, or an original work to help the community get
a head start on their projects.
## Styling
- Templates and packages are now organized by category and discipline.
Filter packages by either taxonomy in the *Start from template*
wizard. If you are a package author, take a look at the new
documentation for
[categories](https://github.com/typst/packages/blob/main/docs/CATEGORIES.md)
and
[disciplines](https://github.com/typst/packages/blob/main/docs/DISCIPLINES.md).
# Context
- Added *context expressions:* Read the chapter on context to get
started
- With context, you can access settable properties, e.g.
`{context text.lang}` to access the language set via
`{set text(lang: "..")}`
- The following existing functions have been made contextual: `query`,
`locate`, `measure`, `counter.display`, `counter.at`, `counter.final`,
`state.at`, and `state.final`
- Added contextual methods `counter.get` and `state.get` to retrieve the
value of a counter or state in the current context
- Added contextual function `here` to retrieve the location of the
current context
- The `locate` function now returns the location of a selector's unique
match. Its old behavior has been replaced by context expressions and
only remains temporarily available for compatibility.
- The `counter.at` and `state.at` methods are now more flexible: They
directly accept any kind of locatable selector with a unique match
(e.g. a label) instead of just locations
- When context is available, `counter.display` now directly returns the
result of applying the numbering instead of yielding opaque content.
It should not be used anymore without context. (Deprecation planned)
- The `state.display` function should not be used anymore, use
`state.get` instead (Deprecation planned)
- The `location` argument of `query`, `counter.final`, and `state.final`
should not be used anymore (Deprecation planned)
- The `styles` argument of the `measure` function should not be used
anymore (Deprecation planned)
- The `style` function should not be used anymore, use context instead
(Deprecation planned)
- The correct context is now also provided in various other places where
it is available, e.g. in show rules, layout callbacks, and numbering
functions in the outline
# Styling
- Fixed priority of multiple show-set rules: They now apply in the same
order as normal set rules would
- Show-set rules on the same element (e.g.
`{show heading.where(level: 1): set heading(numbering: "1.")}`) now
work properly
- Setting properties on an element within a transformational show rule
(e.g. `{show heading: it => { set heading(..); it }}`) is **not**
supported anymore (previously it also only worked sometimes); use
show-set rules instead **(Breaking change)**
- Text show rules that match their own output now work properly (e.g. ``
`show "cmd": `cmd````)
- The elements passed to show rules and returned by queries now contain
all fields of their respective element functions rather than just
specific ones
- All settable properties can now be used in where selectors
- And and or selectors can now be used with show rules
- Errors within show rules and context expressions are now ignored in
all but the last introspection iteration, in line with the behavior of
the old `locate`
- Fixed priority of multiple [show-set rules](/docs/reference/styling/#show-rules): They now apply in the same order as normal set rules would
- Show-set rules on the same element (e.g. `show heading.where(level: 1): set heading(numbering: "1.")`) now work properly
- Setting properties on an element within a transformational show rule (e.g. `show heading: it => \{ set heading(..); it \}`) is **not** supported anymore (previously it also only worked sometimes); use show-set rules instead **(Breaking change)**
- Text show rules that match their own output now work properly (e.g. `show "cmd": `cmd``)
- The elements passed to show rules and returned by queries now contain all fields of their respective element functions rather than just specific ones
- All settable properties can now be used in [where](/docs/reference/foundations/function/#definitions-where) selectors
- [And](/docs/reference/foundations/selector/#definitions-and) and [or](/docs/reference/foundations/selector/#definitions-or) selectors can now be used with show rules
- Errors within show rules and context expressions are now ignored in all but the last introspection iteration, in line with the behavior of the old [`locate`](/docs/reference/introspection/locate/)
- Fixed a bug where document set rules were allowed after content
## Layout
# Layout
- Added `reflow` argument to `rotate` and `scale` which lets them affect
the layout
- Fixed a bug where floating placement or floating figures could end up
out of order
- Added `reflow` argument to [`rotate`](/docs/reference/layout/rotate/) and [`scale`](/docs/reference/layout/scale/) which lets them affect the layout
- Fixed a bug where [floating placement](/docs/reference/layout/place/#parameters-float) or [floating figures](/docs/reference/model/figure/#parameters-placement) could end up out of order
- Fixed overlap of text and figure for full-page floating figures
- Fixed various cases where the [`hide`](/docs/reference/layout/hide/) function didn't hide its contents properly
- Fixed usage of [`h`](/docs/reference/layout/h/) and [`v`](/docs/reference/layout/v/) in [stacks](/docs/reference/layout/stack/)
- Invisible content like a counter update will no longer force a visible block for just itself
- Fixed a bug with horizontal spacing followed by invisible content (like a counter update) directly at the start of a paragraph
## Text
- Fixed various cases where the `hide` function didn't hide its contents
properly
- Fixed usage of `h` and `v` in stacks
- Invisible content like a counter update will no longer force a visible
block for just itself
- Fixed a bug with horizontal spacing followed by invisible content
(like a counter update) directly at the start of a paragraph
# Text
- Added `stroke` property for text
- Added [`stroke`](/docs/reference/text/text/#parameters-stroke) property for text
- Added basic i18n for Serbian and Catalan
- Added support for contemporary Japanese [numbering](/docs/reference/model/numbering/) method
- Added support for contemporary Japanese numbering method
- Added patches for various wrong metadata in specific fonts
- The [text direction](/docs/reference/text/text/#parameters-dir) can now be overridden within a paragraph
- Fixed Danish [smart quotes](/docs/reference/text/smartquote/)
- The text direction can now be overridden within a paragraph
- Fixed Danish smart quotes
- Fixed font fallback next to a line break
- Fixed width adjustment of JIS-style Japanese punctuation
- Fixed Finnish translation of "Listing"
- Fixed Z-ordering of multiple text decorations (underlines, etc.)
- Fixed a bug due to which text [features](/docs/reference/text/text/#parameters-features) could not be overridden in consecutive set rules
## Model
- Fixed a bug due to which text features could not be overridden in
consecutive set rules
- Added [`depth`](/docs/reference/model/heading/#parameters-depth) and [`offset`](/docs/reference/model/heading/#parameters-offset) arguments to heading to increase or decrease the heading level for a bunch of content; the heading syntax now sets `depth` rather than `level` **(Breaking change)**
- List [markers](/docs/reference/model/list/#parameters-marker) now cycle by default
- The [`quote`](/docs/reference/model/quote/) function now more robustly selects the correct quotes based on language and nesting
- Fixed indent bugs related to the default show rule of [terms](/docs/reference/model/terms/)
# Model
## Math
- Added `depth` and `offset` arguments to heading to increase or
decrease the heading level for a bunch of content; the heading syntax
now sets `depth` rather than `level` **(Breaking change)**
- List markers now cycle by default
- The `quote` function now more robustly selects the correct quotes
based on language and nesting
- Fixed indent bugs related to the default show rule of terms
# Math
- Inline equations now automatically linebreak at appropriate places
- Added [`number-align`](/docs/reference/math/equation/#parameters-number-align) argument to equations
- Added support for adjusting the [`size`](/docs/reference/math/accent/#parameters-size) of accents relative to their base
- Added `number-align` argument to equations
- Added support for adjusting the `size` of accents relative to their
base
- Improved positioning of accents
- [Primes](/docs/reference/math/primes/) are now always attached as [scripts](/docs/reference/math/attach/#functions-scripts) by default
- Exposed [`math.primes`](/docs/reference/math/primes/) element which backs the `$f'$` syntax in math
- Math mode is not affected by [`strong`](/docs/reference/model/strong/) and [`emph`](/docs/reference/model/emph/) anymore
- Fixed [`attach`](/docs/reference/math/attach/#functions-attach) under [fractions](/docs/reference/math/frac/)
- Fixed that [`math.class`](/docs/reference/math/class/) did not affect smart limit placement
- Fixed weak spacing in [`lr`](/docs/reference/math/lr/#functions-lr) groups
- Primes are now always attached as scripts by default
- Exposed `math.primes` element which backs the `[$f'$]` syntax in math
- Math mode is not affected by `strong` and `emph` anymore
- Fixed `attach` under fractions
- Fixed that `math.class` did not affect smart limit placement
- Fixed weak spacing in `lr` groups
- Fixed layout of large operators for Cambria Math font
- Fixed math styling of Hebrew symbol codepoints
## Symbols
# Symbols
- Added `gradient` as an alias for `nabla`
- Added `partial` as an alias for `diff`, `diff` will be deprecated in the future
- Added `colon.double`, `gt.approx`, `gt.napprox`, `lt.approx`, and `lt.napprox`
- Added `partial` as an alias for `diff`, `diff` will be deprecated in
the future
- Added `colon.double`, `gt.approx`, `gt.napprox`, `lt.approx`, and
`lt.napprox`
- Added `arrow.r.tilde` and `arrow.l.tilde`
- Added `tilde.dot`
- Added `forces` and `forces.not`
- Added `space.nobreak.narrow`
- Added `lrm` (Left-to-Right Mark) and `rlm` (Right-to-Left Mark)
- Fixed `star.stroked` symbol (which previously had the wrong codepoint)
## Scripting
# Scripting
- Arrays can now be compared lexicographically
- Added contextual method [`to-absolute`](/docs/reference/layout/length/#definitions-to-absolute) to lengths
- Added [`calc.root`](/docs/reference/foundations/calc/#functions-root)
- Added [`int.signum`](/docs/reference/foundations/int/#definitions-signum) and [`float.signum`](/docs/reference/foundations/float/#definitions-signum) methods
- Added [`float.is-nan`](/docs/reference/foundations/float/#definitions-is-nan) and [`float.is-infinite`](/docs/reference/foundations/float/#definitions-is-infinite) methods
- Added [`int.bit-not`](/docs/reference/foundations/int/#definitions-bit-not), [`int.bit-and`](/docs/reference/foundations/int/#definitions-bit-and), [`int.bit-or`](/docs/reference/foundations/int/#definitions-bit-or), [`int.bit-xor`](/docs/reference/foundations/int/#definitions-bit-xor), [`int.bit-lshift`](/docs/reference/foundations/int/#definitions-bit-lshift), and [`int.bit-rshift`](/docs/reference/foundations/int/#definitions-bit-rshift) methods
- Added [`array.chunks`](/docs/reference/foundations/array/#definitions-chunks) method
- A module can now be converted to a dictionary with the [dictionary constructor](/docs/reference/foundations/dictionary/#constructor) to access its contents dynamically
- Added [`row-type`](/docs/reference/data-loading/csv/#parameters-row-type) argument to `csv` function to configure how rows will be represented
- [XML parsing](/docs/reference/data-loading/xml/) now allows DTDs (document type definitions)
- Improved formatting of negative numbers with [`str`](/docs/reference/foundations/str/) and [`repr`](/docs/reference/foundations/repr/)
- For loops can now iterate over [bytes](/docs/reference/foundations/bytes/)
- Added contextual method `to-absolute` to lengths
- Added `calc.root`
- Added `int.signum` and `float.signum` methods
- Added `float.is-nan` and `float.is-infinite` methods
- Added `int.bit-not`, `int.bit-and`, `int.bit-or`, `int.bit-xor`,
`int.bit-lshift`, and `int.bit-rshift` methods
- Added `array.chunks` method
- A module can now be converted to a dictionary with the dictionary
constructor to access its contents dynamically
- Added `row-type` argument to `csv` function to configure how rows will
be represented
- XML parsing now allows DTDs (document type definitions)
- Improved formatting of negative numbers with `str` and `repr`
- For loops can now iterate over bytes
- Fixed a bug with pattern matching in for loops
- Fixed a bug with labels not being part of [`.fields()`](/docs/reference/foundations/content/#definitions-fields) dictionaries
- Fixed a bug where unnamed argument sinks wouldn't capture excess arguments
- Fixed a bug with labels not being part of `{.fields()}` dictionaries
- Fixed a bug where unnamed argument sinks wouldn't capture excess
arguments
- Fixed typo in `repr` output of strokes
## Syntax
# Syntax
- Added support for nested destructuring patterns
- Special spaces (like thin or non-breaking spaces) are now parsed
literally instead of being collapsed into normal spaces **(Breaking
change)**
- Korean text can now use emphasis syntax without adding spaces
**(Breaking change)**
- The token `context` is now a keyword and cannot be used as an
identifier anymore **(Breaking change)**
- Nested line comments aren't allowed anymore in block comments
**(Breaking change)**
- Added support for nested [destructuring patterns](/docs/reference/scripting/#bindings)
- Special spaces (like thin or non-breaking spaces) are now parsed literally instead of being collapsed into normal spaces **(Breaking change)**
- Korean text can now use emphasis syntax without adding spaces **(Breaking change)**
- The token [`context`](/docs/reference/context/) is now a keyword and cannot be used as an identifier anymore **(Breaking change)**
- Nested line comments aren't allowed anymore in block comments **(Breaking change)**
- Fixed a bug where `x.)` would be treated as a field access
- Text elements can now span across curly braces in markup
- Fixed silently wrong parsing when function name is parenthesized
- Fixed various bugs with parsing of destructuring patterns, arrays, and dictionaries
## Tooling & Diagnostics
- Fixed various bugs with parsing of destructuring patterns, arrays, and
dictionaries
# Tooling & Diagnostics
- Click-to-jump now works properly within `raw` text
- Click-to-jump now works properly within [`raw`](/docs/reference/text/raw/) text
- Added suggestion for accessing a field if a method doesn't exist
- Improved hint for calling a function stored in a dictionary
- Improved errors for mutable accessor functions on arrays and dictionaries
- Fixed error message when calling constructor of type that doesn't have one
- Fixed confusing error message with nested dictionaries for strokes on different sides
- Fixed autocompletion for multiple packages with the same name from different namespaces
## Visualization
- Improved errors for mutable accessor functions on arrays and
dictionaries
- Fixed error message when calling constructor of type that doesn't have
one
- Fixed confusing error message with nested dictionaries for strokes on
different sides
- Fixed autocompletion for multiple packages with the same name from
different namespaces
# Visualization
- The `image` function doesn't upscale images beyond their natural size
anymore
- The `image` function now respects rotation stored in EXIF metadata
- The [`image`](/docs/reference/visualize/image/) function doesn't upscale images beyond their natural size anymore
- The [`image`](/docs/reference/visualize/image/) function now respects rotation stored in EXIF metadata
- Added support for SVG filters
- Added alpha component to [`luma`](/docs/reference/visualize/color/#definitions-luma) colors
- Added [`color.transparentize`](/docs/reference/visualize/color/#definitions-transparentize) and [`color.opacify`](/docs/reference/visualize/color/#definitions-opacify) methods
- Improved [`color.negate`](/docs/reference/visualize/color/#definitions-negate) function
- Added [`stroke`](/docs/reference/text/highlight/#parameters-stroke) and [`radius`](/docs/reference/text/highlight/#parameters-radius) arguments to `highlight` function
- Changed default [`highlight`](/docs/reference/text/highlight/) color to be transparent
- Added alpha component to `luma` colors
- Added `color.transparentize` and `color.opacify` methods
- Improved `color.negate` function
- Added `stroke` and `radius` arguments to `highlight` function
- Changed default `highlight` color to be transparent
- CMYK to RGB conversion is now color-managed
- Fixed crash with gradients in Oklch color space
- Fixed color-mixing for hue-based spaces
- Fixed bugs with color conversion
- SVG sizes are not rounded anymore, preventing slightly wrong aspect ratios
- SVG sizes are not rounded anymore, preventing slightly wrong aspect
ratios
- Fixed a few other SVG-related bugs
- [`color.components`](/docs/reference/visualize/color/#definitions-components) doesn't round anything anymore
## Export
- `color.components` doesn't round anything anymore
# Export
- PDFs now contain named destinations for headings derived from their
labels
- The internal PDF structure was changed to make it easier for external
tools to extract or modify individual pages, avoiding a bug with Typst
PDFs in Apple Preview
- PDFs produced by Typst should now be byte-by-byte reproducible when
`{set document(date: none)}` is set
- PDFs now contain named destinations for headings derived from their labels
- The internal PDF structure was changed to make it easier for external tools to extract or modify individual pages, avoiding a bug with Typst PDFs in Apple Preview
- PDFs produced by Typst should now be byte-by-byte reproducible when `set document(date: none)` is set
- Added missing flag to PDF annotation
- Fixed multiple bugs with gradients in PDF export
- Fixed a bug with patterns in PDF export
- Fixed a bug with embedding of grayscale images in PDF export
- Fixed a bug with To-Unicode mapping of CFF fonts in PDF export
- Fixed a bug with the generation of the PDF outline
- Fixed a sorting bug in PDF export leading to non-reproducible output
- Fixed a bug with transparent text in PNG export
- Exported SVG files now include units in their top-level `width` and `height`
## Command line interface
- Exported SVG files now include units in their top-level `width` and
`height`
# Command line interface
- Added support for passing inputs via a CLI flag
- Added support for passing [inputs](/docs/reference/foundations/sys/) via a CLI flag
- When passing the filename `-`, Typst will now read input from stdin
- Now uses the system-native TLS implementation for network fetching which should be generally more robust
- Watch mode will now properly detect when a previously missing file is created
- Now uses the system-native TLS implementation for network fetching
which should be generally more robust
- Watch mode will now properly detect when a previously missing file is
created
- Added `--color` flag to configure whether to print colored output
- Fixed user agent with which packages are downloaded
- Updated bundled fonts to the newest versions
## Development
# Development
- Added `--vendor-openssl` to CLI to configure whether to link OpenSSL
statically instead of dynamically (not applicable to Windows and Apple
platforms)
- Added `--vendor-openssl` to CLI to configure whether to link OpenSSL statically instead of dynamically (not applicable to Windows and Apple platforms)
- Removed old tracing (and its verbosity) flag from the CLI
- Added new `--timings` flag which supersedes the old flamegraph profiling in the CLI
- Added minimal CLI to `typst-docs` crate for extracting the language and standard library documentation as JSON
- The `typst_pdf::export` function's `ident` argument switched from `Option` to `Smart`. It should only be set to `Smart::Custom` if you can provide a stable identifier (like the web app can). The CLI sets `Smart::Auto`.
## Contributors
- Added new `--timings` flag which supersedes the old flamegraph
profiling in the CLI
- Added minimal CLI to `typst-docs` crate for extracting the language
and standard library documentation as JSON
- The `typst_pdf::export` function's `ident` argument switched from
`Option` to `Smart`. It should only be set to `Smart::Custom` if you
can provide a stable identifier (like the web app can). The CLI sets
`Smart::Auto`.
@@ -1,55 +1,84 @@
# 0.11.1
# Security
## Security
- Fixed a vulnerability where image files at known paths could be
embedded into the PDF even if they were outside of the project
directory
- Fixed a vulnerability where image files at known paths could be embedded into the PDF even if they were outside of the project directory
## Bibliography
# Bibliography
- Fixed et-al handling in subsequent citations
- Fixed suppression of title for citations and bibliography references with no author
- Fixed suppression of title for citations and bibliography references
with no author
- Fixed handling of initials in citation styles without a delimiter
- Fixed bug with citations in footnotes
## Text and Layout
# Text and Layout
- Fixed interaction of `first-line-indent` and `outline`
- Fixed interaction of [`first-line-indent`](/docs/reference/model/par/#parameters-first-line-indent) and [`outline`](/docs/reference/model/outline/)
- Fixed compression of CJK punctuation marks at line start and end
- Fixed handling of [rectangles](/docs/reference/visualize/rect/) with negative dimensions
- Fixed layout of [`path`](/docs/reference/visualize/path/) in explicitly sized container
- Fixed broken [`raw`](/docs/reference/text/raw/) text in right-to-left paragraphs
- Fixed handling of rectangles with negative dimensions
- Fixed layout of `path` in explicitly sized container
- Fixed broken `raw` text in right-to-left paragraphs
- Fixed tab rendering in `raw` text with language `typ` or `typc`
- Fixed highlighting of multi-line `raw` text enclosed by single backticks
- Fixed highlighting of multi-line `raw` text enclosed by single
backticks
- Fixed indentation of overflowing lines in `raw` blocks
- Fixed extra space when `raw` text ends with a backtick
## Math
# Math
- Fixed broken equations in right-to-left paragraphs
- Fixed missing blackboard bold letters
- Fixed broken [equations](/docs/reference/math/equation/) in right-to-left paragraphs
- Fixed missing [blackboard bold](/docs/reference/math/variants/#functions-bb) letters
- Fixed error on empty arguments in 2D math argument list
- Fixed stretching via [`mid`](/docs/reference/math/lr/#functions-mid) for various characters
- Fixed that alignment points in equations were affected by `set align(..)`
## Export
- Fixed stretching via `mid` for various characters
- Fixed [smart quotes](/docs/reference/text/smartquote/) in PDF outline
- Fixed [patterns](/docs/reference/visualize/tiling/) with spacing in PDF
- Fixed wrong PDF page labels when [page numbering](/docs/reference/layout/page/#parameters-numbering) was disabled after being previously enabled
- Fixed that alignment points in equations were affected by
`{set align(..)}`
## Scripting
# Export
- Fixed overflow for large numbers in external data files (by converting to floats instead)
- Fixed [`str.trim(regex, at: end)`](/docs/reference/foundations/str/#definitions-trim) when the whole string is matched
- Fixed smart quotes in PDF outline
## Miscellaneous
- Fixed patterns with spacing in PDF
- Fixed wrong PDF page labels when page numbering was disabled after
being previously enabled
# Scripting
- Fixed overflow for large numbers in external data files (by converting
to floats instead)
- Fixed `{str.trim(regex, at: end)}` when the whole string is matched
# Miscellaneous
- Fixed deformed strokes for specific shapes and thicknesses
- Fixed newline handling in code mode: There can now be comments within chained method calls and between an `if` branch and the `else` keyword
- Fixed inefficiency with incremental reparsing
- Fixed autocompletions for relative file imports
- Fixed crash in autocompletion handler
- Fixed a bug where the path and entrypoint printed by `typst init` were not properly escaped
- Fixed various documentation errors
## Contributors
- Fixed newline handling in code mode: There can now be comments within
chained method calls and between an `if` branch and the `else` keyword
- Fixed inefficiency with incremental reparsing
- Fixed autocompletions for relative file imports
- Fixed crash in autocompletion handler
- Fixed a bug where the path and entrypoint printed by `typst init` were
not properly escaped
- Fixed various documentation errors
@@ -1,274 +1,629 @@
# 0.12.0
# Highlights
## Highlights
- Added support for multi-column floating placement and figures
- Added support for automatic line numbering (often used in academic
papers)
- Typst's layout engine is now multithreaded. Typical speedups are 2-3x
for larger documents. The multithreading operates on page break
boundaries, so explicit page breaks are necessary for it to kick in.
- Paragraph justification was optimized with a new two-pass algorithm.
Speedups are larger for shorter paragraphs and go up to 6x.
- Highly reduced PDF file sizes due to better font subsetting (thanks to
<https://github.com/LaurenzV>)
- Added support for multi-column floating [placement](/docs/reference/layout/place/#parameters-scope) and [figures](/docs/reference/model/figure/#parameters-scope)
- Added support for automatic [line numbering](/docs/reference/model/par/#definitions-line) (often used in academic papers)
- Typst's layout engine is now multithreaded. Typical speedups are 2-3x for larger documents. The multithreading operates on page break boundaries, so explicit page breaks are necessary for it to kick in.
- Paragraph justification was optimized with a new two-pass algorithm. Speedups are larger for shorter paragraphs and go up to 6x.
- Highly reduced PDF file sizes due to better font subsetting (thanks to [@LaurenzV](https://github.com/LaurenzV))
- Emoji are now exported properly in PDF
- Added initial support for PDF/A. For now, only the PDF/A-2b profile is supported, but more is planned for the future.
- Added various options for configuring the CLI's environment (fonts, package paths, etc.)
- Added initial support for PDF/A. For now, only the PDF/A-2b profile is
supported, but more is planned for the future.
- Added various options for configuring the CLI's environment (fonts,
package paths, etc.)
- Text show rules now match across multiple text elements
- Block-level equations can now optionally break over multiple pages
- Fixed a bug where some fonts would not print correctly on professional printers
- Fixed a long-standing bug which could cause headings to be orphaned at the bottom of the page
## Layout
- Fixed a bug where some fonts would not print correctly on professional
printers
- Fixed a long-standing bug which could cause headings to be orphaned at
the bottom of the page
# Layout
- Added support for multi-column floating placement and figures via
`place.scope` and `figure.scope`. Two-column documents should now
prefer `{set page(columns: 2)}` over `{show: column.with(2)}` (see the
Page Setup Guide).
- Added support for automatic line numbering (often used in academic
papers)
- Added `par.spacing` property for configuring paragraph spacing. This
should now be used instead of `{show par: set block(spacing: ..)}`
**(Breaking change)**
- Block-level elements like lists, grids, and stacks now show themselves
as blocks and are thus affected by all block properties (e.g.
`stroke`) rather than just `spacing` **(Breaking change)**
- Added `block.sticky` property which prevents a page break after a
block
- Added `place.flush` function which forces all floating figures to be
placed before any further content
- Added `skew` function
- Added `{auto}` option for `page.header` and `page.footer` which
results in an automatic header/footer based on the numbering (which
was previously inaccessible after a change)
- Added `gap` and `justify` parameters to `repeat` function
- Added `width` and `height` parameters to the `measure` function to
define the space in which the content should be measured. Especially
useful in combination with `layout`.
- The height of a `block`, `image`, `rect`, `square`, `ellipse`, or
`circle` can now be specified in fractional units
- The `scale` function now supports absolute lengths for `x`, `y`,
`factor`. This way an element of unknown size can be scaled to a fixed
size.
- The values of `block.above` and `block.below` can now be retrieved in
context expressions.
- Increased accuracy of conversions between absolute units (pt, mm, cm,
in)
- Fixed a bug which could cause headings to be orphaned at the bottom of
the page
- Fixed footnotes within breakable blocks appearing on the page where
the breakable block ends instead of at the page where the footnote
marker is
- Added support for multi-column floating placement and figures via [`place.scope`](/docs/reference/layout/place/#parameters-scope) and [`figure.scope`](/docs/reference/model/figure/#parameters-scope). Two-column documents should now prefer `set page(columns: 2)` over `show: column.with(2)` (see the [Page Setup Guide](/docs/guides/page-setup/#columns)).
- Added support for automatic [line numbering](/docs/reference/model/par/#definitions-line) (often used in academic papers)
- Added [`par.spacing`](/docs/reference/model/par/#parameters-spacing) property for configuring paragraph spacing. This should now be used instead of `show par: set block(spacing: ..)` **(Breaking change)**
- Block-level elements like lists, grids, and stacks now show themselves as blocks and are thus affected by all block properties (e.g. `stroke`) rather than just `spacing` **(Breaking change)**
- Added [`block.sticky`](/docs/reference/layout/block/#parameters-sticky) property which prevents a page break after a block
- Added [`place.flush`](/docs/reference/layout/place/#definitions-flush) function which forces all floating figures to be placed before any further content
- Added [`skew`](/docs/reference/layout/skew/) function
- Added `auto` option for [`page.header`](/docs/reference/layout/page/#parameters-header) and [`page.footer`](/docs/reference/layout/page/#parameters-footer) which results in an automatic header/footer based on the numbering (which was previously inaccessible after a change)
- Added `gap` and `justify` parameters to [`repeat`](/docs/reference/layout/repeat/) function
- Added `width` and `height` parameters to the [`measure`](/docs/reference/layout/measure/) function to define the space in which the content should be measured. Especially useful in combination with [`layout`](/docs/reference/layout/layout/).
- The height of a `block`, `image`, `rect`, `square`, `ellipse`, or `circle` can now be specified in [fractional units](/docs/reference/layout/fraction/)
- The [`scale`](/docs/reference/layout/scale/) function now supports absolute lengths for `x`, `y`, `factor`. This way an element of unknown size can be scaled to a fixed size.
- The values of `block.above` and `block.below` can now be retrieved in context expressions.
- Increased accuracy of conversions between absolute units (pt, mm, cm, in)
- Fixed a bug which could cause headings to be orphaned at the bottom of the page
- Fixed footnotes within breakable blocks appearing on the page where the breakable block ends instead of at the page where the footnote marker is
- Fixed numbering of nested footnotes and footnotes in floats
- Fixed empty pages appearing when a [context](/docs/reference/context/) expression wraps whole pages
- Fixed `set block(spacing: x)` behaving differently from `set block(above: x, below: x)`
- Fixed behavior of [`rotate`](/docs/reference/layout/rotate/) and [`scale`](/docs/reference/layout/scale/) with `reflow: true`
- Fixed interaction of `align(horizon)` and `v(1fr)`
- Fixed various bugs where floating placement would yield overlapping results
- Fixed a bug where widow/orphan prevention would unnecessarily move text into the next column
- Fixed [weak spacing](/docs/reference/layout/h/#parameters-weak) not being trimmed at the start and end of lines in a paragraph (only at the start and end of paragraphs)
- Fixed interaction of weak page break and [`pagebreak.to`](/docs/reference/layout/pagebreak/#parameters-to)
- Fixed empty pages appearing when a context expression wraps whole
pages
- Fixed `{set block(spacing: x)}` behaving differently from
`{set block(above: x, below: x)}`
- Fixed behavior of `rotate` and `scale` with `{reflow: true}`
- Fixed interaction of `{align(horizon)}` and `{v(1fr)}`
- Fixed various bugs where floating placement would yield overlapping
results
- Fixed a bug where widow/orphan prevention would unnecessarily move
text into the next column
- Fixed weak spacing not being trimmed at the start and end of lines in
a paragraph (only at the start and end of paragraphs)
- Fixed interaction of weak page break and `pagebreak.to`
- Fixed compilation output of a single weak page break
- Fixed crash when [padding](/docs/reference/layout/pad/) by `100%`
## Text
- Fixed crash when padding by `{100%}`
# Text
- Tuned hyphenation: It is less eager by default and hyphenations close
to the edges of words are now discouraged more strongly **(May lead to
larger layout reflows)**
- New default font: Libertinus Serif. This is the maintained successor
to the old default font Linux Libertine. **(May lead to smaller
reflows)**
- Tuned hyphenation: It is less eager by default and hyphenations close to the edges of words are now discouraged more strongly **(May lead to larger layout reflows)**
- New default font: Libertinus Serif. This is the maintained successor to the old default font Linux Libertine. **(May lead to smaller reflows)**
- Setting the font to an unavailable family will now result in a warning
- Implemented a new smart quote algorithm, fixing various bugs where smart quotes weren't all that smart
- Added [`text.costs`](/docs/reference/text/text/#parameters-costs) parameter for tweaking various parameters that affect the choices of the layout engine during text layout
- Added `typm` highlighting mode for math in [raw blocks](/docs/reference/text/raw/#parameters-lang)
- Implemented a new smart quote algorithm, fixing various bugs where
smart quotes weren't all that smart
- Added `text.costs` parameter for tweaking various parameters that
affect the choices of the layout engine during text layout
- Added `typm` highlighting mode for math in raw blocks
- Added basic i18n for Galician, Catalan, Latin, Icelandic, Hebrew
- Implemented hyphenation duplication for Czech, Croatian, Lower Sorbian, Polish, Portuguese, Slovak, and Spanish.
- The [`smallcaps`](/docs/reference/text/smallcaps/) function is now an element function and can thereby be used in show(-set) rules.
- The [`raw.theme`](/docs/reference/text/raw/#parameters-theme) parameter can now be set to `none` to disable highlighting even in the presence of a language tag, and to `auto` to reset to the default
- Multiple [stylistic sets](/docs/reference/text/text/#parameters-stylistic-set) can now be enabled at once
- Implemented hyphenation duplication for Czech, Croatian, Lower
Sorbian, Polish, Portuguese, Slovak, and Spanish.
- The `smallcaps` function is now an element function and can thereby be
used in show(-set) rules.
- The `raw.theme` parameter can now be set to `{none}` to disable
highlighting even in the presence of a language tag, and to `{auto}`
to reset to the default
- Multiple stylistic sets can now be enabled at once
- Fixed the Chinese translation for "Equation"
- Fixed that hyphenation could occur outside of words
- Fixed incorrect layout of bidirectional text in edge cases
- Fixed layout of paragraphs with explicit trailing whitespace
- Fixed bugs related to empty paragraphs created via `#""`
- Fixed accidental trailing spaces for line breaks immediately preceding an inline equation
- Fixed [`text.historical-ligatures`](/docs/reference/text/text/#parameters-historical-ligatures) not working correctly
- Fixed accidental repetition of Thai characters around line breaks in some circumstances
- Fixed [smart quotes](/docs/reference/text/smartquote/) for Swiss French
- Fixed accidental trailing spaces for line breaks immediately preceding
an inline equation
- Fixed `text.historical-ligatures` not working correctly
- Fixed accidental repetition of Thai characters around line breaks in
some circumstances
- Fixed smart quotes for Swiss French
- New font metadata exceptions for Archivo, Kaiti SC, and Kaiti TC
- Updated bundled New Computer Modern fonts to version 6.0
## Math
# Math
- Block-level equations can now break over multiple pages if enabled via
`{show math.equation: set block(breakable: true)}`.
- Matrix and vector sizing is now more consistent across different cell
contents
- Added `stretch` function for manually or automatically stretching
characters like arrows or parentheses horizontally or vertically
- Improved layout of attachments on parenthesized as well as under- or
overlined expressions
- Improved layout of nested attachments resulting from code like
`[#let a0 = $a_0$; $a0^1$]`
- Block-level equations can now break over multiple pages if enabled via `show math.equation: set block(breakable: true)`.
- Matrix and vector sizing is now more consistent across different cell contents
- Added [`stretch`](/docs/reference/math/stretch/) function for manually or automatically stretching characters like arrows or parentheses horizontally or vertically
- Improved layout of attachments on parenthesized as well as under- or overlined expressions
- Improved layout of nested attachments resulting from code like `#let a0 = $a_0$; $a0^1$`
- Improved layout of primes close to superscripts
- Improved layout of fractions
- Typst now makes use of math-specific height-dependent kerning information in some fonts for better attachment layout
- The `floor` and `ceil` functions in math are now callable symbols, such that `$ floor(x) = lr(floor.l x floor.r) $`
- The [`mat.delim`](/docs/reference/math/mat/#parameters-delim), [`vec.delim`](/docs/reference/math/vec/#parameters-delim), and [`cases.delim`](/docs/reference/math/cases/#parameters-delim) parameters now allow any character that is considered a delimiter or "fence" (e.g. |) by Unicode. The `delim: "||"` notation is _not_ supported anymore and should be replaced by `delim: bar.double` **(Minor breaking change)**
- Added [`vec.align`](/docs/reference/math/vec/#parameters-align) and [`mat.align`](/docs/reference/math/mat/#parameters-align) parameters
- Added [`underparen`](/docs/reference/math/underover/#functions-underparen), [`overparen`](/docs/reference/math/underover/#functions-overparen), [`undershell`](/docs/reference/math/underover/#functions-undershell), and [`overshell`](/docs/reference/math/underover/#functions-overshell)
- Added `~` shorthand for `tilde.op` in math mode **(Minor breaking change)**
- Typst now makes use of math-specific height-dependent kerning
information in some fonts for better attachment layout
- The `floor` and `ceil` functions in math are now callable symbols,
such that `[$ floor(x) = lr(floor.l x floor.r) $]`
- The `mat.delim`, `vec.delim`, and `cases.delim` parameters now allow
any character that is considered a delimiter or "fence" (e.g. \|) by
Unicode. The `{delim: "||"}` notation is *not* supported anymore and
should be replaced by `{delim: bar.double}` **(Minor breaking
change)**
- Added `vec.align` and `mat.align` parameters
- Added `underparen`, `overparen`, `undershell`, and `overshell`
- Added `~` shorthand for `tilde.op` in math mode **(Minor breaking
change)**
- Fixed baseline alignment of equation numbers
- Fixed positioning of corner brackets (⌜, ⌝, ⌞, ⌟)
- Fixed baseline of large roots
- Fixed multiple minor layout bugs with attachments
- Fixed that alignment points could affect line height in math
- Fixed that spaces could show up between text and invisible elements like [`metadata`](/docs/reference/introspection/metadata/) in math
- Fixed that spaces could show up between text and invisible elements
like `metadata` in math
- Fixed a crash with recursive show rules in math
- Fixed [`lr.size`](/docs/reference/math/lr/#functions-lr-size) not affecting characters enclosed in [`mid`](/docs/reference/math/lr/#functions-mid) in some cases
- Fixed `lr.size` not affecting characters enclosed in `mid` in some
cases
- Fixed resolving of em units in sub- and superscripts
- Fixed bounding box of inline equations when a [text edge](/docs/reference/text/text/#parameters-top-edge) is set to `"bounds"`
## Introspection
- Fixed bounding box of inline equations when a text edge is set to
`{"bounds"}`
# Introspection
- Implemented a new system by which Typst tracks where elements end up
on the pages. This may lead to subtly different behavior in
introspections. **(Breaking change)**
- Fixed various bugs with wrong counter behavior in complex layout
situations, through a new, more principled implementation
- Counter updates can now be before the first, in between, and after the
last page when isolated by weak page breaks. This allows, for
instance, updating a counter before the first page header and
background.
- Implemented a new system by which Typst tracks where elements end up on the pages. This may lead to subtly different behavior in introspections. **(Breaking change)**
- Fixed various bugs with wrong counter behavior in complex layout situations, through a new, more principled implementation
- Counter updates can now be before the first, in between, and after the last page when isolated by weak page breaks. This allows, for instance, updating a counter before the first page header and background.
- Fixed logical ordering of introspections within footnotes and figures
- Fixed incorrect [`here().position()`](/docs/reference/introspection/here/) when [`place`](/docs/reference/layout/place/) was used in a context expression
- Fixed resolved positions of elements (in particular, headings) whose show rule emits an invisible element (like a state update) before a page break
- Fixed behavior of stepping a counter at a deeper level than its current state has
- Fixed citation formatting not working in table headers and a few other places
- Displaying the footnote counter will now respect the footnote numbering style
## Model
- Fixed incorrect `here().position()` when `place` was used in a context
expression
- Fixed resolved positions of elements (in particular, headings) whose
show rule emits an invisible element (like a state update) before a
page break
- Fixed behavior of stepping a counter at a deeper level than its
current state has
- Fixed citation formatting not working in table headers and a few other
places
- Displaying the footnote counter will now respect the footnote
numbering style
# Model
- Document set rules do not need to be at the very start of the document
anymore. The only restriction is that they must not occur inside of
layout containers.
- The `spacing` property of lists, enumerations, and term lists is now
also respected for tight lists
- Tight lists now only attach (with tighter spacing) to preceding
paragraphs, not arbitrary blocks
- The `quote` element is now locatable (can be used in queries)
- The bibliography heading now uses `depth` instead of `level` so that
its level can still be configured via a show-set rule
- Added support for more numbering formats: Devanagari, Eastern Arabic,
Bengali, and circled numbers
- Added `hanging-indent` parameter to heading function to tweak the
appearance of multi-line headings and improved default appearance of
multi-line headings
- Document set rules do not need to be at the very start of the document anymore. The only restriction is that they must not occur inside of layout containers.
- The `spacing` property of [lists](/docs/reference/model/list/#parameters-spacing), [enumerations](/docs/reference/model/enum/#parameters-spacing), and [term lists](/docs/reference/model/terms/#parameters-spacing) is now also respected for tight lists
- Tight lists now only attach (with tighter spacing) to preceding paragraphs, not arbitrary blocks
- The [`quote`](/docs/reference/model/quote/) element is now locatable (can be used in queries)
- The bibliography heading now uses `depth` instead of `level` so that its level can still be configured via a show-set rule
- Added support for more [numbering](/docs/reference/model/numbering/) formats: Devanagari, Eastern Arabic, Bengali, and circled numbers
- Added [`hanging-indent`](/docs/reference/model/heading/#parameters-hanging-indent) parameter to heading function to tweak the appearance of multi-line headings and improved default appearance of multi-line headings
- Improved handling of bidirectional text in outline entry
- Fixed document set rules being ignored in an otherwise empty document
- Fixed document set rules not being usable in context expressions
- Fixed bad interaction between `set document` and `set page`
- Fixed `show figure: set align(..)`. Since the default figure alignment is now a show-set rule, it is not revoked by `show figure: it => it.body` anymore. **(Minor breaking change)**
- Fixed bad interaction between `{set document}` and `{set page}`
- Fixed `{show figure: set align(..)}`. Since the default figure
alignment is now a show-set rule, it is not revoked by
`{show figure: it => it.body}` anymore. **(Minor breaking change)**
- Fixed numbering of footnote references
- Fixed spacing after bibliography heading
## Bibliography
# Bibliography
- The Hayagriva YAML `publisher` field can now accept a dictionary with
a `location` key. The top-level `location` key is now primarily
intended for event and item locations.
- The Hayagriva YAML `publisher` field can now accept a dictionary with a `location` key. The top-level `location` key is now primarily intended for event and item locations.
- Multiple page ranges with prefixes and suffixes are now allowed
- Added `director` and catch-all editor types to BibLaTeX parsing
- Added support for disambiguation to alphanumeric citation style
- The year 0 will now render as 1BC
- Fixes for sorting of bibliography entries
- Fixed pluralization of page range labels
- Fixed sorting of citations by their number
- Fixed how citation number ranges collapse
- Fixed when the short form of a title is used
- Fixed parsing of unbalanced dollars in BibLaTeX `url` field
- Updated built-in citation styles
## Visualization
# Visualization
- Added `fill-rule` parameter to `path` and `polygon` functions
- Fixed color mixing and gradients for Luma colors
- Added `fill-rule` parameter to [`path`](/docs/reference/visualize/path/#parameters-fill-rule) and [`polygon`](/docs/reference/visualize/polygon/#parameters-fill-rule) functions
- Fixed color mixing and gradients for [Luma colors](/docs/reference/visualize/color/#definitions-luma)
- Fixed conversion from Luma to CMYK colors
- Fixed offset gradient strokes in PNG export
- Fixed unintended cropping of some SVGs
- SVGs with foreign objects now produce a warning as they will likely not render correctly in Typst
## Syntax
- SVGs with foreign objects now produce a warning as they will likely
not render correctly in Typst
# Syntax
- Added support for nested imports like
`{import "file.typ": module.item}`
- Added support for parenthesized imports like
`{import "file.typ": (a, b, c)}`. With those, the import list can
break over multiple lines.
- Added support for nested imports like `import "file.typ": module.item`
- Added support for parenthesized imports like `import "file.typ": (a, b, c)`. With those, the import list can break over multiple lines.
- Fixed edge case in parsing of reference syntax
- Fixed edge case in parsing of heading, list, enum, and term markers immediately followed by comments
- Fixed edge case in parsing of heading, list, enum, and term markers
immediately followed by comments
- Fixed rare crash in parsing of parenthesized expressions
## Scripting
# Scripting
- Added new fixed-point [`decimal`](/docs/reference/foundations/decimal/) number type for highly precise arithmetic on numbers in base 10, as needed for finance
- Added `std` module for accessing standard library definitions even when a variable with the same name shadows/overwrites it
- Added [`array.to-dict`](/docs/reference/foundations/array/#definitions-to-dict), [`array.reduce`](/docs/reference/foundations/array/#definitions-reduce), [`array.windows`](/docs/reference/foundations/array/#definitions-windows) methods
- Added `exact` argument to [`array.zip`](/docs/reference/foundations/array/#definitions-zip)
- Added [`arguments.at`](/docs/reference/foundations/arguments/#definitions-at) method
- Added [`int.from-bytes`](/docs/reference/foundations/int/#definitions-from-bytes), [`int.to-bytes`](/docs/reference/foundations/int/#definitions-to-bytes), [`float.from-bytes`](/docs/reference/foundations/float/#definitions-from-bytes), and [`float.to-bytes`](/docs/reference/foundations/float/#definitions-to-bytes)
- Added proper support for negative values of the `digits` parameter of [`calc.round`](/docs/reference/foundations/calc/#functions-round) (the behaviour existed before but was subtly broken)
- Conversions from [`int`](/docs/reference/foundations/int/) to [`float`](/docs/reference/foundations/float/) will now error instead of saturating if the float is too large **(Minor breaking change)**
- Added `float.nan` and `float.inf`, removed `calc.nan` **(Minor breaking change)**
- Certain symbols are now generally callable like functions and not only specifically in math. Examples are accents or [`floor`](/docs/reference/math/lr/#functions-floor) and [`ceil`](/docs/reference/math/lr/#functions-ceil).
- Improved [`repr`](/docs/reference/foundations/repr/) of relative values, sequences, infinities, NaN, `type(none)` and `type(auto)`
- Fixed crash on whole packages (rather than just files) cyclically importing each other
- Fixed return type of [`calc.round`](/docs/reference/foundations/calc/#functions-round) on integers when a non-zero value is provided for `digits`
- Added new fixed-point `decimal` number type for highly precise
arithmetic on numbers in base 10, as needed for finance
## Styling
- Added `std` module for accessing standard library definitions even
when a variable with the same name shadows/overwrites it
- Added `array.to-dict`, `array.reduce`, `array.windows` methods
- Added `exact` argument to `array.zip`
- Added `arguments.at` method
- Added `int.from-bytes`, `int.to-bytes`, `float.from-bytes`, and
`float.to-bytes`
- Added proper support for negative values of the `digits` parameter of
`calc.round` (the behaviour existed before but was subtly broken)
- Conversions from `int` to `float` will now error instead of saturating
if the float is too large **(Minor breaking change)**
- Added `float.nan` and `float.inf`, removed `calc.nan` **(Minor
breaking change)**
- Certain symbols are now generally callable like functions and not only
specifically in math. Examples are accents or `floor` and `ceil`.
- Improved `repr` of relative values, sequences, infinities, NaN,
`{type(none)}` and `{type(auto)}`
- Fixed crash on whole packages (rather than just files) cyclically
importing each other
- Fixed return type of `calc.round` on integers when a non-zero value is
provided for `digits`
# Styling
- Text show rules now match across multiple text elements
- The string `"` in a text show rule now matches smart quotes
- Fixed a long-standing styling bug where the header and footer would incorrectly inherit styles from a lone element on the page (e.g. a heading)
- Fixed `set page` not working directly after a counter/state update
- Page fields configured via an explicit `page(..)[..]` call can now be properly retrieved in context expressions
## Export
- The string `{"}` in a text show rule now matches smart quotes
- Fixed a long-standing styling bug where the header and footer would
incorrectly inherit styles from a lone element on the page (e.g. a
heading)
- Fixed `{set page}` not working directly after a counter/state update
- Page fields configured via an explicit `{page(..)[..]}` call can now
be properly retrieved in context expressions
# Export
- Highly reduced PDF file sizes due to better font subsetting
- Emoji are now exported properly in PDF
- Added initial support for PDF/A. For now, only the standard PDF/A-2b is supported, but more is planned for the future. Enabled via `--pdf-standard a-2b` in the CLI and via the UI in File \> Export as \> PDF in the web app.
- Setting [`page.fill`](/docs/reference/layout/page/#parameters-fill) to `none` will now lead to transparent pages instead of white ones in PNG and SVG. The new default of `auto` means transparent for PDF and white for PNG and SVG.
- Added initial support for PDF/A. For now, only the standard PDF/A-2b
is supported, but more is planned for the future. Enabled via
`--pdf-standard a-2b` in the CLI and via the UI in File > Export as
> PDF in the web app.
- Setting `page.fill` to `{none}` will now lead to transparent pages
instead of white ones in PNG and SVG. The new default of `{auto}`
means transparent for PDF and white for PNG and SVG.
- Improved text copy-paste from PDF in complex scenarios
- Exported SVGs now contain the `data-typst-label` attribute on groups resulting from labelled [boxes](/docs/reference/layout/box/) and [blocks](/docs/reference/layout/block/)
- Fixed a bug where some fonts would not print correctly on professional printers
- Fixed a bug where transparency could leak from one PDF object to another
- Exported SVGs now contain the `data-typst-label` attribute on groups
resulting from labelled boxes and blocks
- Fixed a bug where some fonts would not print correctly on professional
printers
- Fixed a bug where transparency could leak from one PDF object to
another
- Fixed a bug with CMYK gradients in PDF
- Fixed various bugs with export of Oklab gradients in PDF
- Fixed crashes related to rendering of non-outline glyphs
- Two small fixes for PDF standard conformance
## Performance
# Performance
- Typst's layout engine is now multithreaded. Typical speedups are 2-3x for larger documents. The multithreading operates on page break boundaries, so explicit page breaks are necessary for it to kick in.
- Paragraph justification was optimized with a new two-pass algorithm. Speedups are larger for shorter paragraphs and range from 1-6x.
- Typst's layout engine is now multithreaded. Typical speedups are 2-3x
for larger documents. The multithreading operates on page break
boundaries, so explicit page breaks are necessary for it to kick in.
## Command Line Interface
- Paragraph justification was optimized with a new two-pass algorithm.
Speedups are larger for shorter paragraphs and range from 1-6x.
# Command Line Interface
- Added `--pages` option to select specific page ranges to export
- Added `--package-path` and `--package-cache-path` as well as `TYPST_PACKAGE_PATH` and `TYPST_PACKAGE_CACHE_PATH` environment variables for configuring where packages are loaded from and cached in, respectively
- Added `--ignore-system-fonts` flag to disable system fonts fully for better reproducibility
- Added `--make-deps` argument for outputting the dependencies of the current compilation as a Makefile
- Added `--pretty` option to `typst query`, with the default now being to minify (only applies to JSON format)
- Added `--backup-path` to `typst update` to configure where the previous version is backed up
- Added `--package-path` and `--package-cache-path` as well as
`TYPST_PACKAGE_PATH` and `TYPST_PACKAGE_CACHE_PATH` environment
variables for configuring where packages are loaded from and cached
in, respectively
- Added `--ignore-system-fonts` flag to disable system fonts fully for
better reproducibility
- Added `--make-deps` argument for outputting the dependencies of the
current compilation as a Makefile
- Added `--pretty` option to `typst query`, with the default now being
to minify (only applies to JSON format)
- Added `--backup-path` to `typst update` to configure where the
previous version is backed up
- Added useful links to help output
- The CLI will now greet users who invoke just `typst` for the first time
- The document can now be written to stdout by passing `-` as the output filename (for PDF or single-page image export)
- Typst will now emit a proper error message instead of failing silently when the certificate specified by `--cert` or `TYPST_CERT` could not be loaded
- The CLI now respects the `SOURCE_DATE_EPOCH` environment variable for better reproducibility
- When exporting multiple images, you can now use `t` (total pages), `p` (current page), and `0p` (zero-padded current page, same as current `n`) in the output path
- The CLI will now greet users who invoke just `typst` for the first
time
- The document can now be written to stdout by passing `-` as the output
filename (for PDF or single-page image export)
- Typst will now emit a proper error message instead of failing silently
when the certificate specified by `--cert` or `TYPST_CERT` could not
be loaded
- The CLI now respects the `SOURCE_DATE_EPOCH` environment variable for
better reproducibility
- When exporting multiple images, you can now use `{t}` (total pages),
`{p}` (current page), and `{0p}` (zero-padded current page, same as
current `{n}`) in the output path
- The input and output paths now allow non-UTF-8 values
- Times are now formatted more consistently across the CLI
- Fixed a bug related to the `--open` flag
- Fixed path completions for `typst` not working in zsh
## Tooling and Diagnostics
# Tooling and Diagnostics
- The "compiler" field for specifying the minimum Typst version required
by a package now supports imprecise bounds like 0.11 instead of 0.11.0
- Added warning when a label is ignored by Typst because no preceding
labellable element exists
- The "compiler" field for specifying the minimum Typst version required by a package now supports imprecise bounds like 0.11 instead of 0.11.0
- Added warning when a label is ignored by Typst because no preceding labellable element exists
- Added hint when trying to apply labels in code mode
- Added hint when trying to call a standard library function that has been shadowed/overwritten by a local definition
- Added hint when trying to set both the language and the region in the `lang` parameter
- Added hints when trying to compile non-Typst files (e.g. after having typed `typst c file.pdf` by accident)
- Added hint when trying to call a standard library function that has
been shadowed/overwritten by a local definition
- Added hint when trying to set both the language and the region in the
`lang` parameter
- Added hints when trying to compile non-Typst files (e.g. after having
typed `typst c file.pdf` by accident)
- Added hint when a string is used where a label is expected
- Added hint when a stray end of a block comment (`*/`) is encountered
- Added hints when destructuring arrays with the wrong number of elements
- Improved error message when trying to use a keyword as an identifier in a let binding
- Added hints when destructuring arrays with the wrong number of
elements
- Improved error message when trying to use a keyword as an identifier
in a let binding
- Improved error messages when accessing nonexistent fields
- Improved error message when a package exists, but not the specified version
- Improved error message when a package exists, but not the specified
version
- Improved hints for unknown variables
- Improved hint when trying to convert a length with non-zero em component to an absolute unit
- Improved hint when trying to convert a length with non-zero em
component to an absolute unit
- Fixed a crash that could be triggered by certain hover tooltips
- Fixed an off-by-one error in to-source jumps when first-line-indent is enabled
- Fixed an off-by-one error in to-source jumps when first-line-indent is
enabled
- Fixed suggestions for `.` after the end of an inline code expressions
- Fixed autocompletions being duplicated in a specific case
## Symbols
# Symbols
- New: `parallelogram`, `original`, `image`, `crossmark`, `rest`, `natural`, `flat`, `sharp`, `tiny`, `miny`, `copyleft`, `trademark`, `emoji.beet`, `emoji.fingerprint`, `emoji.harp`, `emoji.shovel`, `emoji.splatter`, `emoji.tree.leafless`,
- New variants: `club.stroked`, `diamond.stroked`, `heart.stroked`, `spade.stroked`, `gt.neq`, `lt.neq`, `checkmark.heavy`, `paren.double`, `brace.double`, `shell.double`, `arrow.turn`, `plus.double`, `plus.triple`, `infinity.bar`, `infinity.incomplete`, `infinity.tie`, `multimap.double`, `ballot.check`, `ballot.check.heavy`, `emptyset.bar`, `emptyset.circle`, `emptyset.arrow.l`, `emptyset.arrow.r`, `parallel.struck`, `parallel.eq`, `parallel.equiv`, `parallel.slanted`, `parallel.tilde`, `angle.l.curly`, `angle.l.dot`, `angle.r.curly`, `angle.r.dot`, `angle.oblique`, `angle.s`, `em.two`, `em.three`
- Renamed: `turtle` to `shell`, `notes` to `note`, `ballot.x` to `ballot.cross`, `succ.eq` to `succ.curly.eq`, `prec.eq` to `prec.curly.eq`, `servicemark` to `trademark.service`, `emoji.face.tired` to `emoji.face.distress` **(Breaking change)**
- Changed codepoint: `prec.eq`, `prec.neq`, `succ.eq`, `succ.neq`, `triangle` from ▷ to △, `emoji.face.tired` **(Breaking change)**
- Removed: `lt.curly` in favor of `prec`, `gt.curly` in favor of `succ` **(Breaking change)**
- New: `parallelogram`, `original`, `image`, `crossmark`, `rest`,
`natural`, `flat`, `sharp`, `tiny`, `miny`, `copyleft`, `trademark`,
`emoji.beet`, `emoji.fingerprint`, `emoji.harp`, `emoji.shovel`,
`emoji.splatter`, `emoji.tree.leafless`
## Deprecations
- New variants: `club.stroked`, `diamond.stroked`, `heart.stroked`,
`spade.stroked`, `gt.neq`, `lt.neq`, `checkmark.heavy`,
`paren.double`, `brace.double`, `shell.double`, `arrow.turn`,
`plus.double`, `plus.triple`, `infinity.bar`, `infinity.incomplete`,
`infinity.tie`, `multimap.double`, `ballot.check`,
`ballot.check.heavy`, `emptyset.bar`, `emptyset.circle`,
`emptyset.arrow.l`, `emptyset.arrow.r`, `parallel.struck`,
`parallel.eq`, `parallel.equiv`, `parallel.slanted`, `parallel.tilde`,
`angle.l.curly`, `angle.l.dot`, `angle.r.curly`, `angle.r.dot`,
`angle.oblique`, `angle.s`, `em.two`, `em.three`
- Renamed: `turtle` to `shell`, `notes` to `note`, `ballot.x` to
`ballot.cross`, `succ.eq` to `succ.curly.eq`, `prec.eq` to
`prec.curly.eq`, `servicemark` to `trademark.service`,
`emoji.face.tired` to `emoji.face.distress` **(Breaking change)**
- Changed codepoint: `prec.eq`, `prec.neq`, `succ.eq`, `succ.neq`,
`triangle` from ▷ to △, `emoji.face.tired` **(Breaking change)**
- Removed: `lt.curly` in favor of `prec`, `gt.curly` in favor of `succ`
**(Breaking change)**
# Deprecations
- `counter.display` without an established context
- `counter.final` with a location
- `state.final` with a location
- [`counter.display`](/docs/reference/introspection/counter/#definitions-display) without an established context
- [`counter.final`](/docs/reference/introspection/counter/#definitions-final) with a location
- [`state.final`](/docs/reference/introspection/state/#definitions-final) with a location
- `state.display`
- [`query`](/docs/reference/introspection/query/) with a location as the second argument
- [`locate`](/docs/reference/introspection/locate/) with a callback function
- [`measure`](/docs/reference/layout/measure/) with styles
- `query` with a location as the second argument
- `locate` with a callback function
- `measure` with styles
- `style`
## Development
# Development
- Added `typst-kit` crate which provides useful APIs for `World`
implementors
- Added `typst-kit` crate which provides useful APIs for `World` implementors
- Added go-to-definition API in `typst-ide`
- Added package manifest parsing APIs to `typst-syntax`
- As the compiler is now capable of multithreading, `World` implementations must satisfy `Send` and `Sync`
- Changed signature of `World::main` to allow for the scenario where the main file could not be loaded
- Removed `Tracer` in favor of `Warned<T>` and `typst::trace` function
- The `xz2` dependency used by the self-updater is now statically linked
- The Dockerfile now has an `ENTRYPOINT` directive
## Contributors
- Added package manifest parsing APIs to `typst-syntax`
- As the compiler is now capable of multithreading, `World`
implementations must satisfy `Send` and `Sync`
- Changed signature of `World::main` to allow for the scenario where the
main file could not be loaded
- Removed `Tracer` in favor of `Warned<T>` and `typst::trace` function
- The `xz2` dependency used by the self-updater is now statically linked
- The Dockerfile now has an `ENTRYPOINT` directive
@@ -1,247 +1,544 @@
# 0.13.0
# Highlights
## Highlights
- There is now a distinction between proper paragraphs and just
inline-level content. This is important for future work on
accessibility and means that first line indent can now be enabled for
all paragraphs instead of just consecutive ones.
- There is now a distinction between [proper paragraphs](/docs/reference/model/par/) and just inline-level content. This is important for future work on accessibility and means that [first line indent](/docs/reference/model/par/#parameters-first-line-indent) can now be enabled for all paragraphs instead of just consecutive ones.
- The [`outline`](/docs/reference/model/outline/) has a better out-of-the-box look and is more customizable
- The new [`curve`](/docs/reference/visualize/curve/) function (that supersedes the `path` function) provides a simpler and more flexible interface for creating Bézier curves
- The `image` function now supports raw [pixel raster formats](/docs/reference/visualize/image/#parameters-format) for generating images from within Typst
- Functions that accept [file paths](/docs/reference/syntax/#paths) now also accept raw [bytes](/docs/reference/foundations/bytes/), for full flexibility
- WebAssembly [plugins](/docs/reference/foundations/plugin/) are more flexible and automatically run multi-threaded
- Fixed a long-standing bug where single-letter strings in math (`$"a"$`) would be displayed in italics
- You can now specify which charset should be [covered](/docs/reference/text/text/#parameters-font) by which font family
- The [`pdf.embed`](/docs/reference/pdf/attach/) function lets you embed arbitrary files in the exported PDF
- HTML export is currently under active development. The feature is still _very_ incomplete, but already available for experimentation behind a feature flag.
- The `outline` has a better out-of-the-box look and is more
customizable
## Model
- The new `curve` function (that supersedes the `path` function)
provides a simpler and more flexible interface for creating Bézier
curves
- The `image` function now supports raw pixel raster formats for
generating images from within Typst
- Functions that accept file paths now also accept raw bytes, for full
flexibility
- WebAssembly plugins are more flexible and automatically run
multi-threaded
- Fixed a long-standing bug where single-letter strings in math
(`[$"a"$]`) would be displayed in italics
- You can now specify which charset should be covered by which font
family
- The `pdf.embed` function lets you embed arbitrary files in the
exported PDF
- HTML export is currently under active development. The feature is
still *very* incomplete, but already available for experimentation
behind a feature flag.
# Model
- There is now a distinction between proper paragraphs and just
inline-level content **(Breaking change)**
- All text at the root of a document is wrapped in paragraphs.
Meanwhile, text in a container (like a block) is only wrapped in a
paragraph if the container holds any block-level content. If all of
the content is inline-level, no paragraph is created.
- In the laid-out document, it's not immediately visible whether text
became part of a paragraph. However, it is still important for
accessibility, HTML export, and for properties like
`first-line-indent`.
- There is now a distinction between [proper paragraphs](/docs/reference/model/par/) and just inline-level content **(Breaking change)**
- All text at the root of a document is wrapped in paragraphs. Meanwhile, text in a container (like a block) is only wrapped in a paragraph if the container holds any block-level content. If all of the content is inline-level, no paragraph is created.
- In the laid-out document, it's not immediately visible whether text became part of a paragraph. However, it is still important for accessibility, HTML export, and for properties like `first-line-indent`.
- Show rules on `par` now only affect proper paragraphs
- The `first-line-indent` and `hanging-indent` properties also only affect proper paragraphs
- Creating a `par[..]` with body content that is not fully inline-level will result in a warning
- The default show rules of various built-in elements like lists, quotes, etc. were adjusted to ensure they produce/don't produce paragraphs as appropriate
- Removed support for booleans and content in [`outline.indent`](/docs/reference/model/outline/#parameters-indent)
- The [`outline`](/docs/reference/model/outline/) function was fully reworked to improve its out-of-the-box behavior **(Breaking change)**
- [Outline entries](/docs/reference/model/outline/#definitions-entry) are now [blocks](/docs/reference/layout/block/) and are thus affected by block spacing
- The `auto` indentation mode now aligns numberings and titles outline-wide for a grid-like look
- The `first-line-indent` and `hanging-indent` properties also only
affect proper paragraphs
- Creating a `{par[..]}` with body content that is not fully
inline-level will result in a warning
- The default show rules of various built-in elements like lists,
quotes, etc. were adjusted to ensure they produce/don't produce
paragraphs as appropriate
- Removed support for booleans and content in `outline.indent`
- The `outline` function was fully reworked to improve its
out-of-the-box behavior **(Breaking change)**
- Outline entries are now blocks and are thus affected by block
spacing
- The `{auto}` indentation mode now aligns numberings and titles
outline-wide for a grid-like look
- Automatic indentation now also indents entries without a numbering
- Titles wrapping over multiple lines now have hanging indent
- The page number won't appear alone on its own line anymore
- The link now spans the full entry instead of just the title and page number
- The link now spans the full entry instead of just the title and page
number
- The default spacing between outline leader dots was increased
- The [`fill`](/docs/reference/model/outline/#definitions-entry-fill) parameter was moved from `outline` to `outline.entry` and can thus be configured through show-set rules
- The `fill` parameter was moved from `outline` to `outline.entry` and
can thus be configured through show-set rules
- Removed `body` and `page` fields from outline entry
- Added `indented`, `prefix`, `inner`, `body`, and `page` methods on outline entries to simplify writing of show rules
- Added configuration to [`par.first-line-indent`](/docs/reference/model/par/#parameters-first-line-indent) for indenting all paragraphs instead of just consecutive ones
- Added [`form`](/docs/reference/model/ref/#parameters-form) parameter to `ref` function. Setting the form to `"page"` will produce a page reference instead of a textual one.
- Added [`document.description`](/docs/reference/model/document/#parameters-description) field, which results in corresponding PDF and HTML metadata
- Added [`enum.reversed`](/docs/reference/model/enum/#parameters-reversed) parameter
- Added support for Greek [numbering](/docs/reference/model/numbering/)
- When the [`link`](/docs/reference/model/link/) function wraps around a container like a [block](/docs/reference/layout/block/), it will now generate only one link for the whole block instead of individual links for all the visible leaf elements. This significantly reduces PDF file sizes when combining `link` and [`repeat`](/docs/reference/layout/repeat/).
- The [`link`](/docs/reference/model/link/) function will now only strip one prefix (like `mailto:` or `tel:`) instead of multiple
- The link function now suppresses hyphenation via a built-in show-set rule rather than through its default show rule
- Displaying the page counter without a specified numbering will now take the page numbering into account
## Visualization
- Added `indented`, `prefix`, `inner`, `body`, and `page` methods on
outline entries to simplify writing of show rules
- Added configuration to `par.first-line-indent` for indenting all
paragraphs instead of just consecutive ones
- Added `form` parameter to `ref` function. Setting the form to
`{"page"}` will produce a page reference instead of a textual one.
- Added `document.description` field, which results in corresponding PDF
and HTML metadata
- Added `enum.reversed` parameter
- Added support for Greek numbering
- When the `link` function wraps around a container like a block, it
will now generate only one link for the whole block instead of
individual links for all the visible leaf elements. This significantly
reduces PDF file sizes when combining `link` and `repeat`.
- The `link` function will now only strip one prefix (like `mailto:` or
`tel:`) instead of multiple
- The link function now suppresses hyphenation via a built-in show-set
rule rather than through its default show rule
- Displaying the page counter without a specified numbering will now
take the page numbering into account
# Visualization
- Added new `curve` function that supersedes the `path` function and
provides a simpler and more flexible interface. The `path` function is
now deprecated.
- The `image` function now supports raw pixel raster formats. This can
be used to generate images from within Typst without the need for
encoding in an image exchange format.
- Added `image.scaling` parameter for configuring how an image is scaled
by PNG export and PDF viewers (smooth or pixelated)
- Added `image.icc` parameter for providing or overriding the ICC
profile of an image
- Renamed `pattern` to `tiling`. The name `pattern` remains as a
deprecated alias.
- Added `gradient.center`, `gradient.radius`, `gradient.focal-center`,
and `gradient.focal-radius` methods
- Fixed interaction of clipping and outset on `box` and `block`
- Fixed panic with `path` of infinite length
- Added new [`curve`](/docs/reference/visualize/curve/) function that supersedes the [`path`](/docs/reference/visualize/path/) function and provides a simpler and more flexible interface. The `path` function is now deprecated.
- The `image` function now supports raw [pixel raster formats](/docs/reference/visualize/image/#parameters-format). This can be used to generate images from within Typst without the need for encoding in an image exchange format.
- Added [`image.scaling`](/docs/reference/visualize/image/#parameters-scaling) parameter for configuring how an image is scaled by PNG export and PDF viewers (smooth or pixelated)
- Added [`image.icc`](/docs/reference/visualize/image/#parameters-icc) parameter for providing or overriding the ICC profile of an image
- Renamed `pattern` to [`tiling`](/docs/reference/visualize/tiling/). The name `pattern` remains as a deprecated alias.
- Added [`gradient.center`](/docs/reference/visualize/gradient/#definitions-center), [`gradient.radius`](/docs/reference/visualize/gradient/#definitions-radius), [`gradient.focal-center`](/docs/reference/visualize/gradient/#definitions-focal-center), and [`gradient.focal-radius`](/docs/reference/visualize/gradient/#definitions-focal-radius) methods
- Fixed interaction of clipping and outset on [`box`](/docs/reference/layout/box/) and [`block`](/docs/reference/layout/block/)
- Fixed panic with [`path`](/docs/reference/visualize/path/) of infinite length
- Fixed non-solid (e.g. tiling) text fills in clipped blocks
- Fixed a crash for images with a DPI value of zero
- Fixed floating-point error in [`gradient.repeat`](/docs/reference/visualize/gradient/#definitions-repeat)
- Auto-detection of image formats from a raw buffer now has support for SVGs
## Scripting
- Fixed floating-point error in `gradient.repeat`
- Functions that accept [file paths](/docs/reference/syntax/#paths) now also accept raw [bytes](/docs/reference/foundations/bytes/)
- [`image`](/docs/reference/visualize/image/), [`cbor`](/docs/reference/data-loading/cbor/), [`csv`](/docs/reference/data-loading/csv/), [`json`](/docs/reference/data-loading/json/), [`toml`](/docs/reference/data-loading/toml/), [`xml`](/docs/reference/data-loading/xml/), and [`yaml`](/docs/reference/data-loading/yaml/) now support a path string or bytes and their `.decode` variants are deprecated
- [`plugin`](/docs/reference/foundations/plugin/), [`bibliography`](/docs/reference/model/bibliography/), [`bibliography.style`](/docs/reference/model/bibliography/#parameters-style), [`cite.style`](/docs/reference/model/cite/#parameters-style), [`raw.theme`](/docs/reference/text/raw/#parameters-theme), and [`raw.syntaxes`](/docs/reference/text/raw/#parameters-syntaxes) now accept bytes in addition to path strings. These did not have `.decode` variants, so this adds new flexibility.
- The `path` argument/field of [`image`](/docs/reference/visualize/image/) and [`bibliography`](/docs/reference/model/bibliography/) was renamed to `source` and `sources`, respectively **(Minor breaking change)**
- Improved WebAssembly [plugins](/docs/reference/foundations/plugin/)
- The `plugin` type is replaced by a [`plugin` function](/docs/reference/foundations/plugin/) that returns a [module](/docs/reference/foundations/module/) containing normal Typst functions. This module can be used with import syntax. **(Breaking change)**
- Plugins now automatically run in multiple threads without any changes by plugin authors
- A new [`plugin.transition`](/docs/reference/foundations/plugin/#definitions-transition) API is introduced which allows plugins to run impure initialization in a way that doesn't break Typst's purity guarantees
- The variable name bound by a bare import (no renaming, no import list) is now determined statically and dynamic imports without `as` renaming (e.g. `import "ot" + "her.typ"`) are a hard error **(Breaking change)**
- Values of the [`arguments`](/docs/reference/foundations/arguments/) type can now be added with `+` and [joined](/docs/reference/scripting/#blocks) in curly-braced code blocks
- Functions in an element function's scope can now be called with method syntax, bringing elements and types closer (in anticipation of a future full unification of the two). Currently, this is only useful for [`outline.entry`](/docs/reference/model/outline/#definitions-entry) as no other element function defines methods.
- Added [`calc.norm`](/docs/reference/foundations/calc/#functions-norm) function
- Added support for 32-bit floats in [`float.from-bytes`](/docs/reference/foundations/float/#definitions-from-bytes) and [`float.to-bytes`](/docs/reference/foundations/float/#definitions-to-bytes)
- The [`decimal`](/docs/reference/foundations/decimal/) constructor now also accepts decimal values
- Improved `repr` of [symbols](/docs/reference/foundations/symbol/), [arguments](/docs/reference/foundations/arguments/), and [types](/docs/reference/foundations/type/)
- Duplicate [symbol](/docs/reference/foundations/symbol/) variants and modifiers are now a hard error **(Breaking change)**
- Auto-detection of image formats from a raw buffer now has support for
SVGs
## Math
# Scripting
- Functions that accept file paths now also accept raw bytes
- `image`, `cbor`, `csv`, `json`, `toml`, `xml`, and `yaml` now
support a path string or bytes and their `.decode` variants are
deprecated
- `plugin`, `bibliography`, `bibliography.style`, `cite.style`,
`raw.theme`, and `raw.syntaxes` now accept bytes in addition to path
strings. These did not have `.decode` variants, so this adds new
flexibility.
- The `path` argument/field of `image` and `bibliography` was renamed
to `source` and `sources`, respectively **(Minor breaking change)**
- Improved WebAssembly plugins
- The `plugin` type is replaced by a `plugin` function that returns a
module containing normal Typst functions. This module can be used
with import syntax. **(Breaking change)**
- Plugins now automatically run in multiple threads without any
changes by plugin authors
- A new `plugin.transition` API is introduced which allows plugins to
run impure initialization in a way that doesn't break Typst's purity
guarantees
- The variable name bound by a bare import (no renaming, no import list)
is now determined statically and dynamic imports without `{as}`
renaming (e.g. `{import "ot" + "her.typ"}`) are a hard error
**(Breaking change)**
- Values of the `arguments` type can now be added with `+` and joined in
curly-braced code blocks
- Functions in an element function's scope can now be called with method
syntax, bringing elements and types closer (in anticipation of a
future full unification of the two). Currently, this is only useful
for `outline.entry` as no other element function defines methods.
- Added `calc.norm` function
- Added support for 32-bit floats in `float.from-bytes` and
`float.to-bytes`
- The `decimal` constructor now also accepts decimal values
- Improved `repr` of symbols, arguments, and types
- Duplicate symbol variants and modifiers are now a hard error
**(Breaking change)**
# Math
- Fixed a bug where single letter strings in math (`[$"a"$]`) would be
displayed in italics
- Math function calls can now have hyphenated named arguments and
support argument spreading
- Better looking accents thanks to support for the `flac` (Flattened
Accent Forms) and `dtls` (Dotless Forms) OpenType features
- Added `lcm` text operator
- The `bold` function now works with ϝ and Ϝ
- The `italic` function now works with ħ
- Fixed a bug where the extent of a math equation was wrongly affected
by internal metadata
- Fixed interaction of `lr` and context expressions
- Fixed weak spacing being unconditionally ignored in `lr`
- Fixed sub/superscripts sometimes being in the wrong position with `lr`
- Fixed multi-line annotations (e.g. overbrace) changing the math
baseline
- Fixed a bug where single letter strings in math (`$"a"$`) would be displayed in italics
- Math function calls can now have hyphenated named arguments and support [argument spreading](/docs/reference/foundations/arguments/#spreading)
- Better looking accents thanks to support for the `flac` (Flattened Accent Forms) and `dtls` (Dotless Forms) OpenType features
- Added `lcm` [text operator](/docs/reference/math/op/)
- The [`bold`](/docs/reference/math/styles/#functions-bold) function now works with ϝ and Ϝ
- The [`italic`](/docs/reference/math/styles/#functions-italic) function now works with ħ
- Fixed a bug where the extent of a math equation was wrongly affected by internal metadata
- Fixed interaction of [`lr`](/docs/reference/math/lr/#functions-lr) and [context](/docs/reference/context/) expressions
- Fixed weak spacing being unconditionally ignored in [`lr`](/docs/reference/math/lr/#functions-lr)
- Fixed sub/superscripts sometimes being in the wrong position with [`lr`](/docs/reference/math/lr/#functions-lr)
- Fixed multi-line annotations (e.g. overbrace) changing the math baseline
- Fixed merging of attachments when the base is a nested equation
- Fixed resolving of contextual (em-based) text sizes within math
- Fixed spacing around up tacks (⊥)
## Bibliography
# Bibliography
- Prose and author-only citations now use editor names if the author
names are unavailable
- Some non-standard but widely used BibLaTeX `editortype`s like
`producer`, `writer`, `scriptwriter`, and `none` (defined by
widespread style `biblatex-chicago` to mean performers within `music`
and `video` entries) are now recognized
- Prose and author-only citations now use editor names if the author names are unavailable
- Some non-standard but widely used BibLaTeX `editortype`s like `producer`, `writer`, `scriptwriter`, and `none` (defined by widespread style `biblatex-chicago` to mean performers within `music` and `video` entries) are now recognized
- CSL styles can now render affixes around the bibliography
- For BibTeX entries with `eprinttype = \{pubmed\}`, the PubMed ID will now be correctly processed
- Whitespace handling for strings delimiting initialized names has been improved
- Uppercase spelling after apostrophes used as quotation marks is now possible
- For BibTeX entries with `eprinttype = {pubmed}`, the PubMed ID will
now be correctly processed
- Whitespace handling for strings delimiting initialized names has been
improved
- Uppercase spelling after apostrophes used as quotation marks is now
possible
- Fixed bugs around the handling of CSL delimiting characters
- Fixed a problem with parsing multibyte characters in page ranges that could prevent Hayagriva from parsing some BibTeX page ranges
- Fixed a problem with parsing multibyte characters in page ranges that
could prevent Hayagriva from parsing some BibTeX page ranges
- Updated CSL APA style
- Updated CSL locales for Finnish, Swiss German, Austrian German, German, and Arabic
## Text
- Updated CSL locales for Finnish, Swiss German, Austrian German,
German, and Arabic
# Text
- Added support for specifying which charset should be covered by which
font family
- Added `all` parameter to `smallcaps` function that also enables small
capitals on uppercase letters
- Added support for specifying which charset should be [covered](/docs/reference/text/text/#parameters-font) by which font family
- Added [`all`](/docs/reference/text/smallcaps/#parameters-all) parameter to `smallcaps` function that also enables small capitals on uppercase letters
- Added basic i18n for Basque and Bulgarian
- [Justification](/docs/reference/model/par/#parameters-justify) does not affect [raw](/docs/reference/text/raw/) blocks anymore
- [CJK-Latin-spacing](/docs/reference/text/text/#parameters-cjk-latin-spacing) does not affect [raw](/docs/reference/text/raw/) text anymore
- Justification does not affect raw blocks anymore
- CJK-Latin-spacing does not affect raw text anymore
- Fixed wrong language codes being used for Greek and Ukrainian
- Fixed default quotes for Croatian and Bulgarian
- Fixed crash in RTL text handling
- Added support for [`raw`](/docs/reference/text/raw/) syntax highlighting for a few new languages: CFML, NSIS, and WGSL
- Added support for `raw` syntax highlighting for a few new languages:
CFML, NSIS, and WGSL
- New font metadata exception for New Computer Modern Sans Math
- Updated bundled New Computer Modern fonts to version 7.0.1
## Layout
# Layout
- Fixed various bugs with footnotes
- Fixed footnotes getting lost when multiple footnotes were nested within another footnote
- Fixed footnotes getting lost when multiple footnotes were nested
within another footnote
- Fixed endless loops with empty and overlarge footnotes
- Fixed crash with overlarge footnotes within a floating placement
- Fixed sizing of quadratic shapes ([`square`](/docs/reference/visualize/square/) and [`circle`](/docs/reference/visualize/circle/))
- Fixed [`block.sticky`](/docs/reference/layout/block/#parameters-sticky) not working properly at the top of a container
- Fixed sizing of quadratic shapes (`square` and `circle`)
- Fixed `block.sticky` not working properly at the top of a container
- Fixed crash due to consecutive weak spacing
- Fixed crash when a [block](/docs/reference/layout/block/) or text have negative sizes
- Fixed unnecessary hyphenations occurring in rare scenarios due to a bad interaction between padding and paragraph optimization
- Fixed lone [citations](/docs/reference/model/cite/) in [`align`](/docs/reference/layout/align/) not becoming their own paragraph
## Syntax
- Fixed crash when a block or text have negative sizes
- Fixed unnecessary hyphenations occurring in rare scenarios due to a
bad interaction between padding and paragraph optimization
- Fixed lone citations in `align` not becoming their own paragraph
# Syntax
- Top-level closing square brackets that do not have a matching opening
square bracket are now a hard error **(Minor breaking change)**
- Adding a space between the identifier and the parentheses in a set
rule is not allowed anymore **(Minor breaking change)**
- Numbers with a unit cannot have a base prefix anymore, e.g.
`0b100000pt` is not allowed anymore. Previously, it was syntactically
allowed but always resolved to a value of zero. **(Minor breaking
change)**
- Using `is` as an identifier will now warn as it might become a keyword
in the future
- Top-level closing square brackets that do not have a matching opening square bracket are now a hard error **(Minor breaking change)**
- Adding a space between the identifier and the parentheses in a set rule is not allowed anymore **(Minor breaking change)**
- Numbers with a unit cannot have a base prefix anymore, e.g. `0b100000pt` is not allowed anymore. Previously, it was syntactically allowed but always resolved to a value of zero. **(Minor breaking change)**
- Using `is` as an identifier will now warn as it might become a keyword in the future
- Fixed minor whitespace handling bugs
- in math mode argument lists
- at the end of headings
- between a term list's term and description
- Fixed parsing of empty single line raw blocks with 3+ backticks and a language tag
- Fixed parsing of empty single line raw blocks with 3+ backticks and a
language tag
- Fixed minor bug with parentheses parsing in math
- Markup that can only appear at the start of the line (headings, lists) can now also appear at the start of a list item
- Markup that can only appear at the start of the line (headings, lists)
can now also appear at the start of a list item
- A shebang `#!` at the very start of a file is now ignored
## PDF export
# PDF export
- Added `pdf.embed` function for embedding arbitrary files in the
exported PDF
- Added [`pdf.embed`](/docs/reference/pdf/attach/) function for embedding arbitrary files in the exported PDF
- Added support for PDF/A-3b export
- The PDF timestamp will now contain the timezone by default
## HTML export
# HTML export
**Note:** HTML export is currently under active development. The feature is still _very_ incomplete, but already available for experimentation behind a feature flag.
**Note:** HTML export is currently under active development. The feature
is still *very* incomplete, but already available for experimentation
behind a feature flag.
- Added HTML output support for some (but not all) of the built-in elements
- Added [`html.elem`](/docs/reference/html/elem/) function for outputting an arbitrary HTML element
- Added [`html.frame`](/docs/reference/html/frame/) function for integrating content that requires layout into HTML (by embedding an SVG)
- Added [`target`](/docs/reference/foundations/target/) function which returns either `"paged"` or `"html"` depending on the export target
- Added HTML output support for some (but not all) of the built-in
elements
## Tooling and Diagnostics
- Added `html.elem` function for outputting an arbitrary HTML element
- Added `html.frame` function for integrating content that requires
layout into HTML (by embedding an SVG)
- Added `target` function which returns either `{"paged"}` or `{"html"}`
depending on the export target
# Tooling and Diagnostics
- Autocompletion improvements
- Added autocompletion for file paths
- Smarter autocompletion of variables: Completing `rect(fill: |)` will now only show variables which contain a valid fill (either directly or nested, e.g. a dictionary containing a valid fill)
- Different functions will now autocomplete with different brackets (round vs square) depending on which kind is more useful
- Positional parameters which are already provided aren't autocompleted again anymore
- Smarter autocompletion of variables: Completing `{rect(fill: |)}`
will now only show variables which contain a valid fill (either
directly or nested, e.g. a dictionary containing a valid fill)
- Different functions will now autocomplete with different brackets
(round vs square) depending on which kind is more useful
- Positional parameters which are already provided aren't
autocompleted again anymore
- Fixed variable autocompletion not considering parameters
- Added autocompletion snippets for common figure usages
- Fixed autocompletion after half-completed import item
- Fixed autocompletion for `cite` function
- Added warning when an unconditional return in a code block discards joined content
- Added warning when an unconditional return in a code block discards
joined content
- Fixed error message when accessing non-existent label
- Fixed handling of nested imports in IDE functionality
## Command Line Interface
# Command Line Interface
- Added `--features` argument and `TYPST_FEATURES` environment variable
for opting into experimental features. The only feature so far is
`html`.
- Added a live reloading HTTP server to `typst watch` when targeting
HTML
- Added `--features` argument and `TYPST_FEATURES` environment variable for opting into experimental features. The only feature so far is `html`.
- Added a live reloading HTTP server to `typst watch` when targeting HTML
- Fixed self-update not being aware about certain target architectures
- Fixed crash when piping `typst fonts` output to another command
- Fixed handling of relative paths in `--make-deps` output
- Fixed handling of multipage SVG and PNG export in `--make-deps` output
- Colons in filenames are now correctly escaped in `--make-deps` output
## Symbols
# Symbols
- New
- `inter`, `inter.and`, `inter.big`, `inter.dot`, `inter.double`, `inter.sq`, `inter.sq.big`, `inter.sq.double`, `integral.inter`
- `inter`, `inter.and`, `inter.big`, `inter.dot`, `inter.double`,
`inter.sq`, `inter.sq.big`, `inter.sq.double`, `integral.inter`
- `asymp`, `asymp.not`
- `mapsto`, `mapsto.long`
- `divides.not.rev`, `divides.struck`
- `interleave`, `interleave.big`, `interleave.struck`
- `eq.triple.not`, `eq.dots`, `eq.dots.down`, `eq.dots.up`
- `smt`, `smt.eq`, `lat`, `lat.eq`
- `colon.tri`, `colon.tri.op`
- `dagger.triple`, `dagger.l`, `dagger.r`, `dagger.inv`
- `hourglass.stroked`, `hourglass.filled`
- `die.six`, `die.five`, `die.four`, `die.three`, `die.two`, `die.one`
- `errorbar.square.stroked`, `errorbar.square.filled`, `errorbar.diamond.stroked`, `errorbar.diamond.filled`, `errorbar.circle.stroked`, `errorbar.circle.filled`
- `errorbar.square.stroked`, `errorbar.square.filled`,
`errorbar.diamond.stroked`, `errorbar.diamond.filled`,
`errorbar.circle.stroked`, `errorbar.circle.filled`
- `numero`
- Renamed **(Breaking change)**
- `ohm.inv` to `Omega.inv`
- Changed codepoint **(Breaking change)**
- `angle.l.double` from `《` to `⟪`
- `angle.r.double` from `》` to `⟫`
- `angstrom` from U+212B (`Å`) to U+00C5 (`Å`)
- Deprecated
- `sect` and all its variants in favor of `inter`
- `integral.sect` in favor of `integral.inter`
- Removed **(Breaking change)**
- `degree.c` in favor of `°C` (`$upright(°C)$` or `$upright(degree C)$` in math)
- `degree.f` in favor of `°F` (`$upright(°F)$` or `$upright(degree F)$` in math)
- `kelvin` in favor of just K (`$upright(K)$` in math)
- `degree.c` in favor of `°C` (`[$upright(°C)$]` or
`[$upright(degree C)$]` in math)
- `degree.f` in favor of `°F` (`[$upright(°F)$]` or
`[$upright(degree F)$]` in math)
- `kelvin` in favor of just K (`[$upright(K)$]` in math)
- `ohm` in favor of `Omega`
## Deprecations
# Deprecations
- The [`path`](/docs/reference/visualize/path/) function in favor of the [`curve`](/docs/reference/visualize/curve/) function
- The name `pattern` for tiling patterns in favor of the new name [`tiling`](/docs/reference/visualize/tiling/)
- [`image.decode`](/docs/reference/visualize/image/#definitions-decode), [`cbor.decode`](/docs/reference/data-loading/cbor/#definitions-decode), [`csv.decode`](/docs/reference/data-loading/csv/#definitions-decode), [`json.decode`](/docs/reference/data-loading/json/#definitions-decode), [`toml.decode`](/docs/reference/data-loading/toml/#definitions-decode), [`xml.decode`](/docs/reference/data-loading/xml/#definitions-decode), [`yaml.decode`](/docs/reference/data-loading/yaml/#definitions-decode) in favor of the top-level functions directly accepting both paths and bytes
- The `sect` and its variants in favor of `inter`, and `integral.sect` in favor of `integral.inter`
- The compatibility behavior of type/str comparisons (e.g. `int == "integer"`) which was temporarily introduced in Typst 0.8 now emits warnings. It will be removed in Typst 0.14.
- The `path` function in favor of the `curve` function
## Removals
- The name `pattern` for tiling patterns in favor of the new name
`tiling`
- Removed `style` function and `styles` argument of [`measure`](/docs/reference/layout/measure/), use a [context](/docs/reference/context/) expression instead **(Breaking change)**
- Removed `state.display` function, use [`state.get`](/docs/reference/introspection/state/#definitions-get) instead **(Breaking change)**
- Removed `location` argument of [`state.at`](/docs/reference/introspection/state/#definitions-at), [`counter.at`](/docs/reference/introspection/counter/#definitions-at), and [`query`](/docs/reference/introspection/query/) **(Breaking change)**
- Removed compatibility behavior where [`counter.display`](/docs/reference/introspection/counter/#definitions-display) worked without [context](/docs/reference/context/) **(Breaking change)**
- Removed compatibility behavior of [`locate`](/docs/reference/introspection/locate/) **(Breaking change)**
- `image.decode`, `cbor.decode`, `csv.decode`, `json.decode`,
`toml.decode`, `xml.decode`, `yaml.decode` in favor of the top-level
functions directly accepting both paths and bytes
## Development
- The `sect` and its variants in favor of `inter`, and `integral.sect`
in favor of `integral.inter`
- The compatibility behavior of type/str comparisons (e.g.
`{int == "integer"}`) which was temporarily introduced in Typst 0.8
now emits warnings. It will be removed in Typst 0.14.
# Removals
- Removed `style` function and `styles` argument of `measure`, use a
context expression instead **(Breaking change)**
- Removed `state.display` function, use `state.get` instead **(Breaking
change)**
- Removed `location` argument of `state.at`, `counter.at`, and `query`
**(Breaking change)**
- Removed compatibility behavior where `counter.display` worked without
context **(Breaking change)**
- Removed compatibility behavior of `locate` **(Breaking change)**
# Development
- The `typst::compile` function is now generic and can return either a
`PagedDocument` or an `HtmlDocument`
- `typst-timing` now supports WebAssembly targets via `web-sys` when the
`wasm` feature is enabled
- The `typst::compile` function is now generic and can return either a `PagedDocument` or an `HtmlDocument`
- `typst-timing` now supports WebAssembly targets via `web-sys` when the `wasm` feature is enabled
- Increased minimum supported Rust version to 1.80
- Fixed linux/arm64 Docker image
## Contributors
- Fixed linux/arm64 Docker image
@@ -1,25 +1,27 @@
# 0.13.1
# Command Line Interface
## Command Line Interface
- Fixed high CPU usage for `typst watch` on Linux. Depending on the
project size, CPU usage would spike for varying amounts of time. This
bug appeared with 0.13.0 due to a behavioral change in the inotify
file watching backend.
- Fixed high CPU usage for `typst watch` on Linux. Depending on the project size, CPU usage would spike for varying amounts of time. This bug appeared with 0.13.0 due to a behavioral change in the inotify file watching backend.
# HTML export
## HTML export
- Fixed export of tables with gutters
- Fixed export of tables with [gutters](/docs/reference/model/table/#parameters-gutter)
- Fixed usage of `<html>` and `<body>` element within [context](/docs/reference/context/)
- Fixed querying of [metadata](/docs/reference/introspection/metadata/) next to `<html>` and `<body>` element
- Fixed usage of `<html>` and `<body>` element within context
## Visualization
- Fixed querying of metadata next to `<html>` and `<body>` element
- Fixed [curves](/docs/reference/visualize/curve/) with multiple non-closed components
# Visualization
## Introspection
- Fixed curves with multiple non-closed components
- Fixed a regression where labelled [symbols](/docs/reference/foundations/symbol/) could not be [queried](/docs/reference/introspection/query/) by label
# Introspection
## Deprecations
- Fixed a regression where labelled symbols could not be queried by
label
# Deprecations
- Fixed false positives in deprecation warnings for type/str comparisons
## Contributors
File diff suppressed because it is too large. Load diff
@@ -1,56 +1,116 @@
# 0.14.1
# PDF export
## PDF export
- Fixed regression where links to labelled elements would sometimes not
work correctly <https://github.com/LaurenzV/krilla/pull/304>
- Fixed regression where links to labelled elements would sometimes not work correctly [LaurenzV/krilla#304](https://github.com/LaurenzV/krilla/issues/304)
- Fixed bug where PDF text attributes could be written incorrectly [#7478](https://github.com/typst/typst/issues/7478)
- Fixed crash in link handling [#7471](https://github.com/typst/typst/issues/7471)
- Fixed crash for zero-sized pages [#7454](https://github.com/typst/typst/issues/7454)
- Fixed crash when a table [`vline`](/docs/reference/model/table/#definitions-vline) or [`hline`](/docs/reference/model/table/#definitions-hline) has an out-of-bounds index [#7448](https://github.com/typst/typst/issues/7448)
- Fixed crash in formatting of font-related PDF export errors [#7460](https://github.com/typst/typst/issues/7460)
- Fixed crash when a [`footnote`](/docs/reference/model/footnote/) or [`place`](/docs/reference/layout/place/) element was queried and reinserted into the document [#7216](https://github.com/typst/typst/issues/7216)
- Fixed crash for PNGs with invalid metadata [LaurenzV/krilla#286](https://github.com/LaurenzV/krilla/issues/286), [LaurenzV/krilla#287](https://github.com/LaurenzV/krilla/issues/287)
- Fixed bug where text in SVGs with `fill-and-stroke` paint order could be exported incorrectly [LaurenzV/krilla#292](https://github.com/LaurenzV/krilla/issues/292)
- Fixed bug with layer isolation in SVGs where blending/masking is used [LaurenzV/krilla#295](https://github.com/LaurenzV/krilla/issues/295)
- Fixed that table headers could be tagged incorrectly in some scenarios [LaurenzV/krilla#289](https://github.com/LaurenzV/krilla/issues/289)
- Fixed issues where generated PDFs could differ between 32-bit and 64-bit systems [LaurenzV/krilla#317](https://github.com/LaurenzV/krilla/issues/317), [LaurenzV/krilla#316](https://github.com/LaurenzV/krilla/issues/316), [LaurenzV/krilla#312](https://github.com/LaurenzV/krilla/issues/312)
- Upgraded JPEG decoder used during PDF export for improved compatibility, fixing a case where a valid JPEG was rejected [LaurenzV/krilla#288](https://github.com/LaurenzV/krilla/issues/288)
- A PDF document information dictionary that would be empty is now fully omitted instead [LaurenzV/krilla#280](https://github.com/LaurenzV/krilla/issues/280)
- A rare crash in PDF tagging was turned into a compiler error [#7450](https://github.com/typst/typst/issues/7450)
- Fixed bug where PDF text attributes could be written incorrectly
<https://github.com/typst/typst/pull/7478>
## HTML export
- Fixed crash in link handling
<https://github.com/typst/typst/pull/7471>
- Fixed export of table [headers](/docs/reference/model/table/#definitions-header) and [footers](/docs/reference/model/table/#definitions-footer) with gutter [#7332](https://github.com/typst/typst/issues/7332)
- A [`page`](/docs/reference/layout/page/) set rule in HTML export is now a warning instead of a hard error, in line with how unsupported elements are generally treated [#7513](https://github.com/typst/typst/issues/7513)
- Fixed crash for zero-sized pages
<https://github.com/typst/typst/pull/7454>
## Math
- Fixed crash when a table `vline` or `hline` has an out-of-bounds index
<https://github.com/typst/typst/pull/7448>
- Fixed regression where `arrow.l.r` could not be used as an [accent](/docs/reference/math/accent/) anymore [#7481](https://github.com/typst/typst/issues/7481)
- Fixed that single-letter strings did not react to spaces around them like multi-letter strings do [#7276](https://github.com/typst/typst/issues/7276)
- Fixed that spacing around [`mat`](/docs/reference/math/mat/) and [`vec`](/docs/reference/math/vec/) with a fence delimiter was whitespace-dependent [#7309](https://github.com/typst/typst/issues/7309)
- Fixed height calculation for horizontally stretched glyphs [#7327](https://github.com/typst/typst/issues/7327)
- Fixed crash in formatting of font-related PDF export errors
<https://github.com/typst/typst/pull/7460>
## Model
- Fixed crash when a `footnote` or `place` element was queried and
reinserted into the document
<https://github.com/typst/typst/pull/7216>
- Fixed regression where Typst would error in heading numbering functions that don't handle the counter state `(0,)`. This can occur in the first layout iteration. Such errors are usually automatically caught by Typst, which was not the case here. [#7459](https://github.com/typst/typst/issues/7459)
- Fixed crash for PNGs with invalid metadata
<https://github.com/LaurenzV/krilla/pull/286>
<https://github.com/LaurenzV/krilla/pull/287>
## Text
- Fixed bug where text in SVGs with `fill-and-stroke` paint order could
be exported incorrectly <https://github.com/LaurenzV/krilla/pull/292>
- Fixed regression where Typst would synthesize superscripts for some fonts even when [typographic](/docs/reference/text/super/#parameters-typographic) glyphs were available [#7462](https://github.com/typst/typst/issues/7462)
- Fixed regression where some oblique fonts would be classified as italic [#7483](https://github.com/typst/typst/issues/7483)
- Fixed bug with layer isolation in SVGs where blending/masking is used
<https://github.com/LaurenzV/krilla/pull/295>
## Scripting
- Fixed that table headers could be tagged incorrectly in some scenarios
<https://github.com/LaurenzV/krilla/pull/289>
- Fixed crash due to violated invariants in [`array.sorted`](/docs/reference/foundations/array/#definitions-sorted) [#7520](https://github.com/typst/typst/issues/7520)
- Fixed crashes due to overflow in [`calc.rem`](/docs/reference/foundations/calc/#functions-rem), [`calc.rem-euclid`](/docs/reference/foundations/calc/#functions-rem-euclid), [`calc.div-euclid`](/docs/reference/foundations/calc/#functions-div-euclid), [`calc.quo`](/docs/reference/foundations/calc/#functions-quo), and [`calc.gcd`](/docs/reference/foundations/calc/#functions-gcd) [#7419](https://github.com/typst/typst/issues/7419)
- Upgraded WebAssembly runtime, fixing a bug that [plugins](/docs/reference/foundations/plugin/) could run into [#7438](https://github.com/typst/typst/issues/7438)
- Fixed issues where generated PDFs could differ between 32-bit and
64-bit systems <https://github.com/LaurenzV/krilla/pull/317>
<https://github.com/LaurenzV/krilla/pull/316>
<https://github.com/LaurenzV/krilla/pull/312>
## Command Line Interface
- Upgraded JPEG decoder used during PDF export for improved
compatibility, fixing a case where a valid JPEG was rejected
<https://github.com/LaurenzV/krilla/pull/288>
- Compiling to standard output in combination with `--deps --deps-format=make` (which results in an error) will not produce an empty Make dependency file as a side effect anymore [#7246](https://github.com/typst/typst/issues/7246)
- A PDF document information dictionary that would be empty is now fully
omitted instead <https://github.com/LaurenzV/krilla/pull/280>
## Development
- A rare crash in PDF tagging was turned into a compiler error
<https://github.com/typst/typst/pull/7450>
- Increased minimum supported Rust version to 1.89 [#7363](https://github.com/typst/typst/issues/7363)
# HTML export
## Contributors
- Fixed export of table headers and footers with gutter
<https://github.com/typst/typst/pull/7332>
- A `page` set rule in HTML export is now a warning instead of a hard
error, in line with how unsupported elements are generally treated
<https://github.com/typst/typst/pull/7513>
# Math
- Fixed regression where `arrow.l.r` could not be used as an accent
anymore <https://github.com/typst/typst/pull/7481>
- Fixed that single-letter strings did not react to spaces around them
like multi-letter strings do
<https://github.com/typst/typst/pull/7276>
- Fixed that spacing around `mat` and `vec` with a fence delimiter was
whitespace-dependent <https://github.com/typst/typst/pull/7309>
- Fixed height calculation for horizontally stretched glyphs
<https://github.com/typst/typst/pull/7327>
# Model
- Fixed regression where Typst would error in heading numbering
functions that don't handle the counter state `{(0,)}`. This can occur
in the first layout iteration. Such errors are usually automatically
caught by Typst, which was not the case here.
<https://github.com/typst/typst/pull/7459>
# Text
- Fixed regression where Typst would synthesize superscripts for some
fonts even when typographic glyphs were available
<https://github.com/typst/typst/pull/7462>
- Fixed regression where some oblique fonts would be classified as
italic <https://github.com/typst/typst/pull/7483>
# Scripting
- Fixed crash due to violated invariants in `array.sorted`
<https://github.com/typst/typst/pull/7520>
- Fixed crashes due to overflow in `calc.rem`, `calc.rem-euclid`,
`calc.div-euclid`, `calc.quo`, and `calc.gcd`
<https://github.com/typst/typst/pull/7419>
- Upgraded WebAssembly runtime, fixing a bug that plugins could run into
<https://github.com/typst/typst/pull/7438>
# Command Line Interface
- Compiling to standard output in combination with
`--deps --deps-format=make` (which results in an error) will not
produce an empty Make dependency file as a side effect anymore
<https://github.com/typst/typst/pull/7246>
# Development
- Increased minimum supported Rust version to 1.89
<https://github.com/typst/typst/pull/7363>
@@ -1,11 +1,32 @@
# 0.14.2
# Security
## Security
- Updated the WebAssembly runtime used for executing plugins. The
version used in Typst 0.14.0 and 0.14.1 suffers from a memory handling
vulnerability. Based on our investigation, the vulnerability would be
very hard to exploit in practice, but an exploit could theoretically
be feasible. In any case, **we recommend upgrading to Typst 0.14.2.**
This holds in particular for local users. In the web app, the bug is
not critical as the browser offers an extra layer of protection.
- Updated the WebAssembly runtime used for executing [plugins](/docs/reference/foundations/plugin/). The version used in Typst 0.14.0 and 0.14.1 suffers from a memory handling vulnerability. Based on our investigation, the vulnerability would be very hard to exploit in practice, but an exploit could theoretically be feasible. In any case, **we recommend upgrading to Typst 0.14.2.** This holds in particular for local users. In the web app, the bug is not critical as the browser offers an extra layer of protection. Typst 0.13.1 and below are not affected by this vulnerability. _Technical details:_ The [`wasmi`](https://github.com/wasmi-labs/wasmi/) WebAssembly runtime versions used in 0.14.0 and 0.14.1 have a _use-after-free_ memory handling bug in certain memory growth situations. Specifically, the bug occurs when the plugin tries to grow its memory, but allocating the requested amount of memory fails. Based on our investigation, the bug is hard to trigger in practice as the WebAssembly linear memory is always limited to 4GB on a technical level and modern operating systems rarely fail to serve a 4GB memory allocation request (typically not even under RAM pressure). Once the bug is triggered, it would also still be very challenging to turn it into an actual exploit. Regardless, we recommend upgrading to Typst 0.14.2 for protection against a potential exploit.
Typst 0.13.1 and below are not affected by this vulnerability.
## Diagnostics
*Technical details:* The
[`wasmi`](https://github.com/wasmi-labs/wasmi/) WebAssembly runtime
versions used in 0.14.0 and 0.14.1 have a *use-after-free* memory
handling bug in certain memory growth situations. Specifically, the
bug occurs when the plugin tries to grow its memory, but allocating
the requested amount of memory fails. Based on our investigation, the
bug is hard to trigger in practice as the WebAssembly linear memory is
always limited to 4GB on a technical level and modern operating
systems rarely fail to serve a 4GB memory allocation request
(typically not even under RAM pressure). Once the bug is triggered, it
would also still be very challenging to turn it into an actual
exploit. Regardless, we recommend upgrading to Typst 0.14.2 for
protection against a potential exploit.
- Added a hint when [`array.sorted`](/docs/reference/foundations/array/#definitions-sorted) fails because a pair of elements could not be compared. This hint aids with fixing bugs in user code that were surfaced by a change in internal sorting behavior in Typst 0.14.1.
# Diagnostics
## Contributors
- Added a hint when `array.sorted` fails because a pair of elements
could not be compared. This hint aids with fixing bugs in user code
that were surfaced by a change in internal sorting behavior in Typst
0.14.1.
File diff suppressed because it is too large. Load diff
@@ -1,37 +1,60 @@
# 0.2.0
# Breaking changes
## Breaking changes
- Removed support for iterating over index and value in for loops. This
is now handled via unpacking and enumerating. Same goes for the `map`
method.
- Removed support for iterating over index and value in [for loops](/docs/reference/scripting/#loops). This is now handled via unpacking and enumerating. Same goes for the [`map`](/docs/reference/foundations/array/#definitions-map) method.
- [Dictionaries](/docs/reference/foundations/dictionary/) now iterate in insertion order instead of alphabetical order.
- Dictionaries now iterate in insertion order instead of alphabetical
order.
## New features
# New features
- Added [unpacking syntax](/docs/reference/scripting/#bindings) for let bindings, which allows things like `let (1, 2) = array`
- Added [`enumerate`](/docs/reference/foundations/array/#definitions-enumerate) method
- Added [`path`](/docs/reference/visualize/path/) function for drawing Bézier paths
- Added [`layout`](/docs/reference/layout/layout/) function to access the size of the surrounding page or container
- Added `key` parameter to [`sorted`](/docs/reference/foundations/array/#definitions-sorted) method
- Added unpacking syntax for let bindings, which allows things like
`{let (1, 2) = array}`
## Command line interface
- Added `enumerate` method
- Added `path` function for drawing Bézier paths
- Added `layout` function to access the size of the surrounding page or
container
- Added `key` parameter to `sorted` method
# Command line interface
- Fixed `--open` flag blocking the program
- New Computer Modern font is now embedded into the binary
- Shell completions and man pages can now be generated by setting the `GEN_ARTIFACTS` environment variable to a target directory and then building Typst
## Miscellaneous improvements
- New Computer Modern font is now embedded into the binary
- Shell completions and man pages can now be generated by setting the
`GEN_ARTIFACTS` environment variable to a target directory and then
building Typst
# Miscellaneous improvements
- Fixed page numbering in outline
- Added basic i18n for a few more languages (AR, NB, CS, NN, PL, SL, ES, UA, VI)
- Added a few numbering patterns (Ihora, Chinese)
- Added `sinc` [operator](/docs/reference/math/op/)
- Fixed bug where math could not be hidden with [`hide`](/docs/reference/layout/hide/)
- Fixed sizing issues with box, block, and shapes
- Fixed some translations
- Fixed inversion of "R" in [`cal`](/docs/reference/math/variants/#functions-cal) and [`frak`](/docs/reference/math/variants/#functions-frak) styles
- Fixed some styling issues in math
- Fixed supplements of references to headings
- Fixed syntax highlighting of identifiers in certain scenarios
- [Ratios](/docs/reference/layout/ratio/) can now be multiplied with more types and be converted to [floats](/docs/reference/foundations/float/) with the [`float`](/docs/reference/foundations/float/) function
## Contributors
- Added basic i18n for a few more languages (AR, NB, CS, NN, PL, SL, ES,
UA, VI)
- Added a few numbering patterns (Ihora, Chinese)
- Added `sinc` operator
- Fixed bug where math could not be hidden with `hide`
- Fixed sizing issues with box, block, and shapes
- Fixed some translations
- Fixed inversion of "R" in `cal` and `frak` styles
- Fixed some styling issues in math
- Fixed supplements of references to headings
- Fixed syntax highlighting of identifiers in certain scenarios
- Ratios can now be multiplied with more types and be converted to
floats with the `float` function
@@ -1,61 +1,109 @@
# 0.3.0
# Breaking changes
## Breaking changes
- Renamed a few symbols: What was previous `dot.op` is now just `dot`
and the basic dot is `dot.basic`. The same applies to `ast` and
`tilde`.
- Renamed a few symbols: What was previous `dot.op` is now just `dot` and the basic dot is `dot.basic`. The same applies to `ast` and `tilde`.
- Renamed `mod` to [`rem`](/docs/reference/foundations/calc/#functions-rem) to more accurately reflect the behavior. It will remain available as `mod` until the next update as a grace period.
- A lone underscore is not a valid identifier anymore, it can now only be used in patterns
- Removed `before` and `after` arguments from [`query`](/docs/reference/introspection/query/). This is now handled through flexible [selectors](/docs/reference/foundations/selector/) combinator methods
- Added support for [attachments](/docs/reference/math/attach/#functions-attach) (sub-, superscripts) that precede the base symbol. The `top` and `bottom` arguments have been renamed to `t` and `b`.
- Renamed `mod` to `rem` to more accurately reflect the behavior. It
will remain available as `mod` until the next update as a grace
period.
## New features
- A lone underscore is not a valid identifier anymore, it can now only
be used in patterns
- Added support for more complex [strokes](/docs/reference/visualize/stroke/) (configurable caps, joins, and dash patterns)
- Added [`cancel`](/docs/reference/math/cancel/) function for equations
- Added support for [destructuring](/docs/reference/scripting/#bindings) in argument lists and assignments
- Added [`alt`](/docs/reference/visualize/image/#parameters-alt) text argument to image function
- Added [`toml`](/docs/reference/data-loading/toml/) function for loading data from a TOML file
- Added [`zip`](/docs/reference/foundations/array/#definitions-zip), [`sum`](/docs/reference/foundations/array/#definitions-sum), and [`product`](/docs/reference/foundations/array/#definitions-product) methods for arrays
- Added `fact`, `perm`, `binom`, `gcd`, `lcm`, `atan2`, `quo`, `trunc`, and `fract` [calculation](/docs/reference/foundations/calc/) functions
- Removed `before` and `after` arguments from `query`. This is now
handled through flexible selectors combinator methods
## Improvements
- Added support for attachments (sub-, superscripts) that precede the
base symbol. The `top` and `bottom` arguments have been renamed to `t`
and `b`.
# New features
- Added support for more complex strokes (configurable caps, joins, and
dash patterns)
- Added `cancel` function for equations
- Added support for destructuring in argument lists and assignments
- Added `alt` text argument to image function
- Added `toml` function for loading data from a TOML file
- Added `zip`, `sum`, and `product` methods for arrays
- Added `fact`, `perm`, `binom`, `gcd`, `lcm`, `atan2`, `quo`, `trunc`,
and `fract` calculation functions
# Improvements
- Text in SVGs now displays properly
- Typst now generates a PDF heading outline
- [References](/docs/reference/model/ref/) now provides the referenced element as a field in show rules
- References now provides the referenced element as a field in show
rules
- Refined linebreak algorithm for better Chinese justification
- Locations are now a valid kind of selector
- Added a few symbols for algebra
- Added Spanish smart quote support
- Added [`selector`](/docs/reference/foundations/selector/) function to turn a selector-like value into a selector on which combinator methods can be called
- Added `selector` function to turn a selector-like value into a
selector on which combinator methods can be called
- Improved some error messages
- The outline and bibliography headings can now be styled with show-set rules
- The outline and bibliography headings can now be styled with show-set
rules
- Operations on numbers now produce an error instead of overflowing
## Bug fixes
# Bug fixes
- Fixed wrong linebreak before punctuation that follows inline
equations, citations, and other elements
- Fixed a bug with argument sinks
- Fixed wrong linebreak before punctuation that follows inline equations, citations, and other elements
- Fixed a bug with [argument sinks](/docs/reference/foundations/arguments/)
- Fixed strokes with thickness zero
- Fixed hiding and show rules in math
- Fixed alignment in matrices
- Fixed some alignment bugs in equations
- Fixed grid cell alignment
- Fixed alignment of list marker and enum markers in presence of global alignment settings
- Fixed [path](/docs/reference/visualize/path/) closing
- Fixed alignment of list marker and enum markers in presence of global
alignment settings
- Fixed path closing
- Fixed compiler crash with figure references
- A single trailing line breaks is now ignored in math, just like in text
## Command line interface
- A single trailing line breaks is now ignored in math, just like in
text
# Command line interface
- Font path and compilation root can now be set with the environment
variables `TYPST_FONT_PATHS` and `TYPST_ROOT`
- Font path and compilation root can now be set with the environment variables `TYPST_FONT_PATHS` and `TYPST_ROOT`
- The output of `typst fonts` now includes the embedded fonts
## Development
# Development
- Added instrumentation for debugging and optimization
- Added `--update` flag and `UPDATE_EXPECT` environment variable to update reference images for tests
- You can now run a specific subtest with `--subtest`
- Tests now run on multiple threads
## Contributors
- Added `--update` flag and `UPDATE_EXPECT` environment variable to
update reference images for tests
- You can now run a specific subtest with `--subtest`
- Tests now run on multiple threads
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more