repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi: agent skills (d2, gh-cli, jq, justfile, mdbook, niri, nushell, pastel, presenterm, rust-maud, tiger, uuid, wezterm)

151c8eaba2189538b44a2a5dc48eb903285f10e0

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (32)

pi/agent/skills/d2/SKILL.md

Added
new file mode 100644
1 +---
2 +name: d2
3 +description: D2 (Declarative Diagramming) language reference — syntax for shapes, connections, containers, styling, SQL tables, sequence diagrams, UML classes. Load when working with D2 diagram code.
4 +license: MIT
5 +---
7 +## D2 Language Reference
9 +D2 is a declarative diagramming language that turns text into diagrams. It stands for **Declarative Diagramming** — describe what you want diagrammed, it generates the image.
11 +**Official Resources:**
12 +- Docs: https://d2lang.com
13 +- Playground: https://play.d2lang.com
14 +- Cheat Sheet: https://d2lang.com/tour/cheat-sheet/
16 +---
18 +## Shapes
20 +### Basic Declaration
22 +```d2
23 +# Simple shape (default: rectangle)
24 +shape_name
26 +# Custom label
27 +key: "Display Label"
29 +# Multiple on one line (semicolon separated)
30 +shape1; shape2; shape3
31 +```
33 +### Shape Types
35 +```d2
36 +database.shape: cylinder
37 +decision.shape: diamond
38 +process.shape: hexagon
39 +cloud_service.shape: cloud
40 +user.shape: person
41 +```
43 +| Shape | Use Case |
44 +| ----------------- | ------------------------ |
45 +| `rectangle` | Default, general purpose |
46 +| `square` | 1:1 ratio |
47 +| `circle` | States, nodes (1:1) |
48 +| `oval` | Start/end points |
49 +| `diamond` | Decisions, conditions |
50 +| `hexagon` | Processes |
51 +| `cloud` | Cloud services |
52 +| `cylinder` | Databases, storage |
53 +| `person` | Users, actors |
54 +| `parallelogram` | Input/output |
55 +| `document` | Documents |
56 +| `page` | Page shape |
57 +| `queue` | Queue shape |
58 +| `package` | Package shape |
59 +| `step` | Step shape |
60 +| `callout` | Speech bubble |
61 +| `stored_data` | Data storage |
63 +### 1:1 Ratio Shapes
65 +`circle` and `square` maintain equal width and height. Long labels will expand both dimensions.
67 +---
69 +## Connections
71 +### Arrow Types
73 +```d2
74 +a -> b # Forward arrow
75 +a <- b # Backward arrow
76 +a -- b # Line (no arrow)
77 +a <-> b # Bidirectional
78 +```
80 +### Connection Labels
82 +```d2
83 +client -> server: "HTTP request"
84 +database <- api: "query"
85 +```
87 +### Chaining
89 +```d2
90 +a -> b -> c -> d
91 +```
93 +### Repeated Connections
95 +Repeated connections create new edges, they don't override:
97 +```d2
98 +Database -> S3: backup
99 +Database -> S3: backup # Creates second edge
100 +```
102 +### Cycles
104 +```d2
105 +Stage One -> Stage Two -> Stage Three -> Stage Four -> Stage One
106 +```
108 +### Arrowheads
110 +```d2
111 +a -> b: {
112 + source-arrowhead: {
113 + shape: diamond
114 + label: "start"
116 + target-arrowhead: {
117 + shape: arrow
118 + label: "end"
121 +```
123 +**Arrowhead shapes:** `triangle` (default), `arrow`, `diamond`, `circle`, `box`, `cross`, `cf-one`, `cf-many`
125 +---
127 +## Containers (Nested Shapes)
129 +### Nested Syntax
131 +```d2
132 +Frontend: {
133 + React App
134 + Redux
137 +Backend: {
138 + API Layer
139 + Services
142 +Frontend -> Backend: HTTP
143 +```
145 +### Container Labels
147 +```d2
148 +# Shorthand
149 +clouds: Cloud Services
151 +# Or using label keyword
152 +clouds: {
153 + label: Cloud Services
154 + aws
155 + gcloud
157 +```
159 +### Reference Parent
161 +Use `_` to reference the parent container from inside:
163 +```d2
164 +christmas: {
165 + presents -> _.birthdays.presents: regift
168 +birthdays: {
169 + presents
171 +```
173 +---
175 +## Direction
177 +```d2
178 +# Global direction
179 +direction: right # up, down, left, right
180 +```
182 +**Note:** Per-container direction only works with TALA layout engine.
184 +---
186 +## Styling
188 +### Style Block
190 +```d2
191 +component: {
192 + style: {
193 + fill: "#E3F2FD"
194 + stroke: "#1976D2"
195 + stroke-width: 2
196 + stroke-dash: 3
197 + opacity: 0.9
198 + shadow: true
199 + font-size: 14
200 + font-color: "#333"
201 + bold: true
202 + italic: true
203 + underline: true
204 + border-radius: 5
207 +```
209 +### Dot Notation
211 +```d2
212 +component.style.fill: "#4CAF50"
213 +connection.style.animated: true
214 +```
216 +---
218 +## Special Objects
220 +### SQL Tables
222 +```d2
223 +users: {
224 + shape: sql_table
225 + id: int {constraint: primary_key}
226 + name: varchar(255)
227 + email: varchar(255) {constraint: unique}
228 + role_id: int {constraint: foreign_key}
231 +orders: {
232 + shape: sql_table
233 + id: int {constraint: primary_key}
234 + user_id: int {constraint: foreign_key}
235 + total: decimal
238 +# Foreign key connection
239 +users.id <-> orders.user_id: "has many"
240 +```
242 +**Constraint shortcuts:** `primary_key` → PK, `foreign_key` → FK, `unique` → UNQ
244 +### UML Classes
246 +```d2
247 +User: {
248 + shape: class
249 + +id: int
250 + +name: string
251 + -password: string
252 + #internalField: string
253 + +getEmail(): string
254 + +setEmail(email: string): void
256 +```
258 +Visibility: `+` public, `-` private, `#` protected
260 +### Sequence Diagrams
262 +```d2
263 +api_flow: {
264 + shape: sequence_diagram
266 + client
267 + server
268 + database
270 + client -> server: request
271 + server -> database: query
272 + database -> server: results
273 + server -> client: response
275 +```
277 +**Key rules:**
278 +- Order of definitions matters (appears in that order)
279 +- Children share scope (same `alice` throughout)
280 +- Groups: containers with no connections but internal connections
281 +- Spans: nested objects on actors
282 +- Notes: nested objects with no connections
284 +```d2
285 +# Group example
286 +Office chatter: {
287 + shape: sequence_diagram
289 + alice
290 + bob
292 + group: {
293 + label: "awkward small talk"
294 + alice -> bob: hi
295 + bob -> alice: hello
298 +```
300 +### Code Blocks
302 +```d2
303 +code_example: {
304 + shape: code
305 + language: typescript
306 + content: |`
307 + const response = await fetch('/api');
308 + return response.json();
309 + `|
311 +```
313 +**Language aliases:** `md` → markdown, `tex` → latex, `js` → javascript, `go` → golang, `py` → python, `ts` → typescript
315 +### Markdown / Text
317 +```d2
318 +# Standalone markdown
319 +description: |md
320 + # Header
321 + - Bullet point
322 + - Another point
325 +# Text shape (no markdown)
326 +note: {
327 + shape: text
328 + label: "Plain text here"
330 +```
332 +### LaTeX
334 +```d2
335 +formula: |latex
336 + \frac{-b \pm \sqrt{b^2-4ac}}{2a}
338 +```
340 +---
342 +## Variables
344 +```d2
345 +vars: {
346 + primary-color: "#4A90D9"
347 + db-color: "#2ECC71"
350 +database.style.fill: ${primary-color}
351 +```
353 +---
355 +## Layout Engines
357 +| Engine | Best For | Command |
358 +| ------- | ----------------------------------- | -------------------------- |
359 +| `dagre` | General purpose, hierarchical | `d2 --layout=dagre` |
360 +| `elk` | Complex graphs, better edge routing | `d2 --layout=elk` |
361 +| `tala` | Software architecture, nested | `d2 --layout=tala` |
363 +**Engine-specific features:**
364 +- `near` to another object: TALA only
365 +- `width`/`height` on containers: ELK only
366 +- Per-container direction: TALA only
367 +- `top`/`left` positioning: TALA only
369 +---
371 +## Themes
373 +```bash
374 +# Apply theme by ID
375 +d2 -t 101 input.d2 out.svg
377 +# Theme ranges: 0-7, 101-104, 200-204, 300-303
378 +```
380 +---
382 +## CLI Reference
384 +```bash
385 +# Compile to SVG
386 +d2 input.d2 output.svg
388 +# Export formats
389 +d2 input.d2 output.png
390 +d2 input.d2 output.pdf
392 +# Watch mode
393 +d2 --watch input.d2 out.svg
395 +# Format D2 file
396 +d2 fmt input.d2
398 +# List layouts
399 +d2 layout
400 +```
402 +---
404 +## Common Patterns
406 +### Layered Architecture
408 +```d2
409 +direction: down
411 +Presentation: {
412 + UI Components
413 + Views
416 +Business: {
417 + Services
418 + Domain Logic
421 +Data: {
422 + Repositories
423 + Database
426 +Presentation -> Business
427 +Business -> Data
428 +```
430 +### Event-Driven System
432 +```d2
433 +Producer -> "Event Bus": Publish
434 +"Event Bus" -> Consumer A: Subscribe
435 +"Event Bus" -> Consumer B: Subscribe
436 +"Event Bus".shape: parallelogram
437 +```
439 +### Microservices
441 +```d2
442 +direction: right
444 +Gateway: {shape: hexagon}
446 +Auth Service: {style.fill: "#E3F2FD"}
447 +User Service: {style.fill: "#FFF3E0"}
448 +Order Service: {style.fill: "#FCE4EC"}
450 +Gateway -> Auth Service
451 +Gateway -> User Service
452 +Gateway -> Order Service
453 +```
455 +---
457 +## Installation
459 +```bash
460 +# Install
461 +curl -fsSL https://d2lang.com/install.sh | sh -s --
463 +# Verify
464 +d2 --version
466 +# Uninstall
467 +curl -fsSL https://d2lang.com/install.sh | sh -s -- --uninstall
468 +```
472 +---
474 +## Available Tools
476 +When working with D2 in this environment, you have access to these tools:
478 +### `d2_render`
480 +Render D2 code to an image file (SVG, PNG, or PDF).
482 +```typescript
483 +// Render inline code
484 +d2_render({ code: "a -> b: hello", format: "svg" })
486 +// Render from file
487 +d2_render({ file: "diagram.d2", format: "png" })
489 +// With options
490 +d2_render({
491 + code: "...",
492 + format: "svg",
493 + theme: "dark", // default, dark, terminal, earth, cool, grape, asteroid, flagship
494 + layout: "elk", // dagre, elk, tala
495 + pad: 50, // padding in pixels (0-500)
496 + returnBase64: true // return base64 instead of saving to file
498 +```
500 +**Parameters:**
501 +- `code` - D2 diagram code (required if file not specified)
502 +- `file` - Path to a .d2 file (required if code not specified)
503 +- `format` - Output format: `svg` (default), `png`, or `pdf`
504 +- `theme` - Visual theme: `default`, `dark`, `terminal`, `earth`, `cool`, `grape`, `asteroid`, `flagship`
505 +- `layout` - Layout engine: `dagre`, `elk`, or `tala`
506 +- `pad` - Padding around diagram in pixels (0-500)
507 +- `returnBase64` - Return base64 encoded output instead of saving to file
509 +**Output:** Saves to `.output/` directory (e.g., `.output/diagram.svg`) unless `returnBase64: true`
511 +### `d2_check`
513 +Check if D2 CLI is available and get version information.
515 +```typescript
516 +d2_check()
517 +// Returns: { available: true, version: "0.6.0", ... }
518 +```
520 +### `d2_themes`
522 +List available D2 themes with descriptions.
524 +```typescript
525 +d2_themes()
526 +// Returns: { themes: [...], usage: "...", example: "..." }
527 +```
529 +### `d2_layouts`
531 +List available layout engines with pros/cons.
533 +```typescript
534 +d2_layouts()
535 +// Returns: { layouts: [...], usage: "...", example: "..." }
536 +```
538 +---
540 +## Workflow with Tools
542 +1. **Check availability** (optional): `d2_check()`
543 +2. **Write D2 code** using the syntax in this reference
544 +3. **Render** with `d2_render({ code: "...", format: "svg" })`
545 +4. **Iterate** based on the output
547 +### Example Session
549 +```typescript
550 +// Check D2 is installed
551 +d2_check()
553 +// Render a simple diagram
554 +d2_render({
555 + code: `
556 + direction: right
557 + User -> Server: Request
558 + Server -> Database: Query
559 + Database -> Server: Result
560 + Server -> User: Response
561 + `,
562 + format: "svg",
563 + theme: "dark"
565 +// Output: .output/diagram-1234567890.svg
567 +// Or return as base64 for immediate use
568 +d2_render({
569 + code: "a -> b",
570 + returnBase64: true
572 +// Output: data:image/svg+xml;base64,...
573 +```

pi/agent/skills/find-skills

Added
new file mode 120000
1 +../../../../../.agents/skills/find-skills

pi/agent/skills/gh-cli/SKILL.md

Added
new file mode 100644
1 +---
2 +name: gh-cli
3 +description: GitHub API interaction via gh CLI — issues, PRs, releases, comments, workflows. Use when git alone cannot reach GitHub APIs or UI.
4 +---
6 +# GitHub CLI (gh)
8 +## Requirements
10 +- Python 3.8+
11 +- GitHub CLI (`gh`) installed and authenticated
13 +```bash
14 +# Verify installation
15 +gh --version
16 +gh auth status
18 +# If not authenticated
19 +gh auth login
20 +```
22 +## Core Capabilities
24 +### GitHub API Operations (gh only)
26 +```bash
27 +# Issues
28 +gh issue list --repo owner/repo --state open --label bug --limit 20
29 +gh issue view 123 --repo owner/repo --json comments
30 +gh issue create --title "Bug" --body "desc" --label bug --assignee user
31 +gh issue close 123
33 +# PRs
34 +gh pr list --repo owner/repo --state open --author user
35 +gh pr view 456 --repo owner/repo --json commits,reviews,statusCheckRollup
36 +gh pr create --title "Fix" --body "desc" --base main
37 +gh pr merge 456 --squash --delete-branch
39 +# Comments
40 +gh issue comment 123 --body "LGTM"
42 +# Releases
43 +gh release list --repo owner/repo --limit 10
44 +gh release view v1.0.0 --repo owner/repo --json
46 +# Code Search
47 +gh search code "TODO" --language python --owner org --limit 50
48 +```
50 +### Python-Enhanced Tools
52 +**Code Search** `scripts/gh_code_search.py` - Advanced filtering and formatting.
54 +```bash
55 +python3 scripts/gh_code_search.py "TODO" --language python --exclude-forks
56 +```
58 +**Workflow Failure Analysis** `scripts/gh_failed_run.py` - Extract errors from CI failures.
60 +```bash
61 +python3 scripts/gh_failed_run.py --repo owner/repo --pretty
62 +python3 scripts/gh_failed_run.py --run-id 12345 --json
63 +```
65 +**GitHub Pages** `scripts/gh_pages_deploy.py` - Automate Pages deployment.
67 +```bash
68 +python3 scripts/gh_pages_deploy.py status owner/repo --json
69 +python3 scripts/gh_pages_deploy.py enable owner/repo --dry-run
70 +```
72 +## Quick Reference
74 +| Task | Command |
75 +|------|---------|
76 +| List issues | `gh issue list [--repo owner/repo] [--state open]` |
77 +| View issue | `gh issue view N [--json]` |
78 +| Create issue | `gh issue create --title "..." --body "..."` |
79 +| List PRs | `gh pr list [--author user] [--state open]` |
80 +| View PR | `gh pr view N --json commits,reviews` |
81 +| Add comment | `gh issue comment N --body "..."` |
82 +| List releases | `gh release list [--repo owner/repo]` |
83 +| Code search | `gh search code "query" [--language LANG]` |
84 +| Workflow failures | `python3 scripts/gh_failed_run.py --repo owner/repo` |
85 +| GitHub Pages | `python3 scripts/gh_pages_deploy.py status owner/repo --json` |
87 +## Common Options
89 +### gh issue/pr
90 +```
91 +--repo OWNER/REPO Repository (defaults to current)
92 +--json FIELDS Output specific fields as JSON
93 +--state open|closed Filter by state
94 +--limit N Max results (default: 30)
95 +```
97 +### gh_code_search.py
98 +```
99 +-L, --limit N Max results (default: 30)
100 +--language LANG Filter by language
101 +-R, --repo OWNER/REPO Filter by repo (can repeat)
102 +--exclude-forks Skip forked repos
103 +-o, --output FORMAT json|pretty|summary (default: pretty)
104 +```
106 +### gh_failed_run.py
107 +```
108 +--repo OWNER/REPO Repository to analyze
109 +--run-id N Specific run ID (default: most recent failure)
110 +--pretty Pretty-print JSON
111 +--json JSON output
112 +```
114 +## Troubleshooting
116 +### "gh CLI is not installed"
117 +Install from https://cli.github.com/ or via package manager:
118 +```bash
119 +brew install gh # macOS
120 +sudo apt install gh # Linux
121 +winget install gh # Windows
122 +```
124 +### "gh CLI is not authenticated"
125 +```bash
126 +gh auth login
127 +```
129 +### Rate limit errors
130 +Wait and retry, or use authenticated gh:
131 +```bash
132 +gh auth refresh
133 +```
135 +### Pages enable fails with 403
136 +Requires admin permissions on the repository.
138 +### Pages enable fails with 422
139 +Pages may already be enabled. Use `status` to check.
141 +## Examples
143 +### Find security issues in public repos
144 +```bash
145 +python3 scripts/gh_code_search.py "eval(" --language javascript \
146 + --exclude-forks --exclude-private --sort-by matches
147 +```
149 +### Analyze a specific CI failure
150 +```bash
151 +python3 scripts/gh_failed_run.py --repo myorg/myrepo --run-id 12345 --pretty | jq '.failed_jobs[].error_excerpts'
152 +```
154 +### Check PR status including reviews
155 +```bash
156 +gh pr view 456 --repo owner/repo --json commits,reviews,statusCheckRollup | jq '.statusCheckRollup[] | select(.conclusion == "FAILURE")'
157 +```
159 +### Bulk close issues with label
160 +```bash
161 +gh issue list --repo owner/repo --label "wontfix" --state open --limit 100 | \
162 + jq -r '"gh issue close " + (.[] | .number | tostring)' | bash
163 +```
165 +### Search code across org
166 +```bash
167 +gh search code "password=" --owner myorg --language python --limit 50
168 +```
170 +### Pipeline: Enable Pages + Create Workflow
171 +```bash
172 +gh api repos/owner/repo/pages --method POST -f build_type=workflow
174 +# Clone and add workflow
175 +gh repo clone owner/repo /tmp/pages-setup
176 +cp .github/workflows/pages.yml /tmp/pages-setup/.github/workflows/
177 +cd /tmp/pages-setup && git add . && git commit -m "Add Pages workflow" && git push
178 +```

pi/agent/skills/gh-cli/references/README_gh_code_search.md

Added
new file mode 100644
1 +# gh_code_search.py
3 +A Python wrapper for `gh search code` with enhanced filtering and formatting capabilities.
5 +## Features
7 +- **All `gh search code` options**: Supports all native GitHub CLI search filters
8 +- **Custom filtering**: Exclude forks, private repos, or filter by match count
9 +- **Multiple output formats**: JSON, pretty-printed table, or summary statistics
10 +- **Sorting**: Sort results by match count, repository, or file path
11 +- **Error handling**: Graceful handling of rate limits, timeouts, and other errors
13 +## Requirements
15 +- Python 3.8+
16 +- GitHub CLI (`gh`) installed and authenticated
18 +## Installation
20 +```bash
21 +chmod +x gh_code_search.py
22 +```
24 +## Usage
26 +```bash
27 +./gh_code_search.py [OPTIONS] QUERY
28 +```
30 +### Basic Examples
32 +Search for "hello world" in Python files:
33 +```bash
34 +./gh_code_search.py "hello world" --language python
35 +```
37 +Search in a specific repository:
38 +```bash
39 +./gh_code_search.py "error handling" --repo microsoft/vscode
40 +```
42 +Search with multiple filters:
43 +```bash
44 +./gh_code_search.py "TODO" --extension md --exclude-forks --limit 10
45 +```
47 +### Output Formats
49 +**Pretty format** (default):
50 +```bash
51 +./gh_code_search.py "React component" --language typescript --output pretty
52 +```
54 +**Summary statistics**:
55 +```bash
56 +./gh_code_search.py "hello world" --language python --output summary
57 +```
59 +**JSON format**:
60 +```bash
61 +./gh_code_search.py "class.*Component" --language typescript --output json
62 +```
64 +### Advanced Filtering
66 +Exclude forks and sort by match count:
67 +```bash
68 +./gh_code_search.py "authentication" --exclude-forks --sort-by matches
69 +```
71 +Filter by minimum number of matches:
72 +```bash
73 +./gh_code_search.py "TODO" --min-matches 3 --output summary
74 +```
76 +Search in multiple repositories:
77 +```bash
78 +./gh_code_search.py "bug fix" --repo user/repo1 --repo user/repo2
79 +```
81 +## Options
83 +### GitHub Search Filters
85 +| Option | Description |
86 +|--------|-------------|
87 +| `-L, --limit` | Maximum number of results (default: 30) |
88 +| `--language` | Filter by programming language |
89 +| `--filename` | Filter by filename |
90 +| `--extension` | Filter by file extension |
91 +| `-R, --repo` | Filter by repository (can specify multiple) |
92 +| `--owner` | Filter by owner (can specify multiple) |
93 +| `--match` | Restrict search to "file" or "content" |
94 +| `--size` | Filter by file size range (e.g., "10..100" in KB) |
96 +### Custom Filters
98 +| Option | Description |
99 +|--------|-------------|
100 +| `--exclude-forks` | Exclude results from forked repositories |
101 +| `--exclude-private` | Exclude results from private repositories |
102 +| `--min-matches` | Minimum number of text matches per file |
104 +### Output Options
106 +| Option | Description |
107 +|--------|-------------|
108 +| `-o, --output` | Output format: json, pretty, summary (default: pretty) |
109 +| `--sort-by` | Sort by: matches, repo, path |
111 +## Error Handling
113 +The script handles common errors gracefully:
115 +- **Rate Limit**: Displays helpful message when GitHub API rate limit is exceeded
116 +- **Timeout**: Suggests simplifying query when search times out
117 +- **Invalid Query**: Validates query before execution
119 +## Exit Codes
121 +- `0`: Success
122 +- `1`: Error (rate limit, timeout, invalid query, etc.)
123 +- `130`: Cancelled by user (Ctrl+C)
125 +## Examples by Use Case
127 +### Find security issues
128 +```bash
129 +./gh_code_search.py "eval(" --language javascript --exclude-forks --sort-by matches
130 +```
132 +### Analyze TODO comments
133 +```bash
134 +./gh_code_search.py "TODO" --extension py --owner yourorg --output summary
135 +```
137 +### Find code patterns
138 +```bash
139 +./gh_code_search.py "class.*extends.*Component" --language typescript --limit 50 --output json
140 +```
142 +### Repository-specific search
143 +```bash
144 +./gh_code_search.py "database connection" --repo myorg/myrepo --output pretty
145 +```

pi/agent/skills/gh-cli/references/README_gh_failed_run.md

Added
new file mode 100644
1 +# GitHub Actions Failed Run Analyzer
3 +A Python script that analyzes the most recent failed GitHub Actions workflow run and provides detailed error information.
5 +## Prerequisites
7 +- Python 3.6+
8 +- [GitHub CLI (gh)](https://cli.github.com/) installed and authenticated
10 +## Installation
12 +1. Ensure you have the GitHub CLI installed:
13 + ```bash
14 + gh --version
15 + ```
17 +2. Make sure you're authenticated:
18 + ```bash
19 + gh auth status
20 + ```
22 +3. Make the script executable:
23 + ```bash
24 + chmod +x gh_failed_run.py
25 + ```
27 +## Usage
29 +### Basic Usage
31 +Analyze the most recent failed run in the current repository:
32 +```bash
33 +./gh_failed_run.py
34 +```
36 +Or with Python:
37 +```bash
38 +python3 gh_failed_run.py
39 +```
41 +### Analyze a Specific Repository
43 +```bash
44 +./gh_failed_run.py --repo owner/repo-name
45 +```
47 +### Pretty-Print JSON Output
49 +For more readable output with indentation:
50 +```bash
51 +./gh_failed_run.py --pretty
52 +```
54 +### Combined Example
56 +```bash
57 +./gh_failed_run.py --repo microsoft/vscode --pretty
58 +```
60 +## Output Format
62 +The script outputs JSON with the following structure:
64 +```json
66 + "run": {
67 + "number": 12345,
68 + "url": "https://github.com/owner/repo/actions/runs/12345",
69 + "workflow": "CI Tests",
70 + "conclusion": "failure",
71 + "status": "completed",
72 + "created_at": "2025-11-07T10:30:00Z",
73 + "branch": "main",
74 + "commit": "abc123...",
75 + "event": "push"
76 + },
77 + "failed_jobs": [
78 + {
79 + "name": "build",
80 + "conclusion": "failure",
81 + "status": "completed",
82 + "started_at": "2025-11-07T10:30:05Z",
83 + "completed_at": "2025-11-07T10:35:22Z",
84 + "error_excerpts": [
85 + "Error: Module 'foo' not found",
86 + "npm ERR! Failed at the build script",
87 + "Process completed with exit code 1"
88 + ]
89 + }
90 + ],
91 + "repository": "owner/repo-name"
93 +```
95 +## Features
97 +- **Automatic Detection**: Finds the most recent failed run without needing a run ID
98 +- **Error Extraction**: Intelligently extracts error messages from logs using pattern matching
99 +- **Multiple Job Support**: Analyzes all failed jobs in a run
100 +- **Flexible Repository Selection**: Works with current repository or any specified repository
101 +- **Clean Output**: Removes ANSI color codes and timestamps from error excerpts
103 +## Error Patterns Detected
105 +The script looks for common error indicators:
106 +- Lines containing "error", "failed", "failure"
107 +- Exception messages
108 +- Exit code messages
109 +- Timeout messages
110 +- Panic messages
112 +## Piping to Other Tools
114 +Since the output is JSON, you can easily pipe it to other tools:
116 +```bash
117 +# Extract just the error excerpts
118 +./gh_failed_run.py | jq '.failed_jobs[].error_excerpts[]'
120 +# Get the run URL
121 +./gh_failed_run.py | jq -r '.run.url'
123 +# Count failed jobs
124 +./gh_failed_run.py | jq '.failed_jobs | length'
126 +# Save to file
127 +./gh_failed_run.py --pretty > failed_run_analysis.json
128 +```
130 +## Troubleshooting
132 +### "gh CLI is not installed or not in PATH"
133 +Install the GitHub CLI from https://cli.github.com/
135 +### "No failed runs found"
136 +This means there are no failed workflow runs in the repository. The script only looks for runs with `failure` status.
138 +### "Error running gh command"
139 +Make sure you're authenticated with `gh auth login` and have access to the repository you're trying to analyze.
141 +## Exit Codes
143 +- `0`: Success
144 +- `1`: Error (gh CLI not found, command failed, JSON parsing error)
146 +## Advanced Usage
148 +### Filter Error Excerpts with grep
150 +```bash
151 +./gh_failed_run.py | jq -r '.failed_jobs[].error_excerpts[]' | grep -i "module"
152 +```
154 +### Monitor Multiple Repositories
156 +```bash
157 +for repo in owner/repo1 owner/repo2 owner/repo3; do
158 + echo "Checking $repo..."
159 + ./gh_failed_run.py --repo "$repo" --pretty
160 +done
161 +```
163 +### Integration with CI/CD
165 +You can use this script in your CI/CD pipeline to automatically analyze and report failures:
167 +```bash
168 +#!/bin/bash
169 +if ! ./gh_failed_run.py > failure_report.json; then
170 + echo "Failed to analyze run"
171 + exit 1
174 +# Send to monitoring system, Slack, etc.
175 +curl -X POST https://hooks.slack.com/... -d @failure_report.json
176 +```

pi/agent/skills/gh-cli/references/README_pages.md

Added
new file mode 100644
1 +# GitHub Pages Deployment Script
3 +A simple Python script to automate GitHub Pages deployment using the GitHub CLI (`gh`). This script provides an easy-to-use interface for enabling Pages, checking deployment status, triggering rebuilds, and creating GitHub Actions workflows.
5 +## Features
7 +- **Enable GitHub Pages** - Configure Pages with GitHub Actions or Jekyll build type
8 +- **Check Status** - Query Pages site information and deployment status
9 +- **Trigger Rebuilds** - Request new Pages builds via API
10 +- **Create Workflows** - Generate GitHub Actions workflow files for automated deployment
12 +## Prerequisites
14 +1. **GitHub CLI (`gh`)** - Must be installed and authenticated
15 + ```bash
16 + # Install GitHub CLI (see https://cli.github.com/)
17 + # macOS
18 + brew install gh
20 + # Linux
21 + sudo apt install gh # Debian/Ubuntu
23 + # Windows
24 + winget install GitHub.cli
26 + # Authenticate
27 + gh auth login
28 + ```
30 +2. **Python 3.6+**
32 +## Installation
34 +Simply download the script:
36 +```bash
37 +curl -O https://raw.githubusercontent.com/yourusername/yourrepo/main/gh_pages_deploy.py
38 +chmod +x gh_pages_deploy.py
39 +```
41 +Or clone this repository:
43 +```bash
44 +git clone https://github.com/yourusername/yourrepo.git
45 +cd yourrepo
46 +```
48 +## Usage
50 +### Enable GitHub Pages
52 +Enable Pages with GitHub Actions as the build source:
54 +```bash
55 +python gh_pages_deploy.py enable owner/repo
56 +```
58 +**Options:**
59 +- `--branch BRANCH` - Source branch (default: `main`)
60 +- `--path PATH` - Source path: `/` or `/docs` (default: `/`)
61 +- `--build-type TYPE` - Build type: `workflow` (GitHub Actions) or `legacy` (Jekyll)
62 +- `--no-https` - Disable HTTPS enforcement
64 +**Examples:**
66 +```bash
67 +# Enable with default settings (main branch, GitHub Actions)
68 +python gh_pages_deploy.py enable myusername/myrepo
70 +# Enable with custom branch and Jekyll
71 +python gh_pages_deploy.py enable myorg/myrepo --branch gh-pages --build-type legacy
73 +# Enable with /docs path
74 +python gh_pages_deploy.py enable myusername/myrepo --path /docs
75 +```
77 +### Check Status
79 +Check if Pages is enabled and view configuration:
81 +```bash
82 +python gh_pages_deploy.py status owner/repo
83 +```
85 +**Options:**
86 +- `--build-info` - Also show latest build information
88 +**Example:**
90 +```bash
91 +python gh_pages_deploy.py status myusername/myrepo --build-info
92 +```
94 +**Sample Output:**
96 +```
97 +Checking GitHub Pages status for myusername/myrepo...
99 +✓ GitHub Pages is enabled:
100 + URL: https://myusername.github.io/myrepo/
101 + Status: built
102 + Build type: workflow
103 + Source branch: main
104 + Source path: /
105 + HTTPS enforced: True
107 +Latest build:
108 + Status: built
109 + Commit: abc123def456
110 + Created: 2025-01-15T10:30:00Z
111 +```
113 +### Trigger Rebuild
115 +Manually trigger a new Pages build:
117 +```bash
118 +python gh_pages_deploy.py rebuild owner/repo
119 +```
121 +**Example:**
123 +```bash
124 +python gh_pages_deploy.py rebuild myusername/myrepo
125 +```
127 +### Create GitHub Actions Workflow
129 +Generate a GitHub Actions workflow file for automated Pages deployment:
131 +```bash
132 +python gh_pages_deploy.py create-workflow
133 +```
135 +**Options:**
136 +- `--output PATH` - Custom output path (default: `.github/workflows/pages.yml`)
138 +**Example:**
140 +```bash
141 +# Create in default location
142 +python gh_pages_deploy.py create-workflow
144 +# Create with custom path
145 +python gh_pages_deploy.py create-workflow --output .github/workflows/deploy.yml
146 +```
148 +This creates a workflow that:
149 +1. Runs on push to `main` branch
150 +2. Builds your site (customize the build step)
151 +3. Uploads the built site as an artifact
152 +4. Deploys to GitHub Pages
154 +**After creating the workflow:**
155 +1. Edit `.github/workflows/pages.yml` to add your build commands
156 +2. Commit and push the workflow to your repository
157 +3. The deployment will run automatically on the next push
159 +## Complete Workflow Example
161 +Here's a complete example of setting up GitHub Pages for a new repository:
163 +```bash
164 +# 1. Enable GitHub Pages with GitHub Actions
165 +python gh_pages_deploy.py enable myusername/myrepo
167 +# 2. Create the deployment workflow
168 +python gh_pages_deploy.py create-workflow
170 +# 3. Customize the workflow (edit .github/workflows/pages.yml)
171 +# Add your build commands, e.g., npm install && npm run build
173 +# 4. Commit and push
174 +git add .github/workflows/pages.yml
175 +git commit -m "Add GitHub Pages deployment workflow"
176 +git push origin main
178 +# 5. Check status
179 +python gh_pages_deploy.py status myusername/myrepo --build-info
180 +```
182 +## How It Works
184 +The script uses the GitHub CLI (`gh`) to interact with the GitHub REST API:
186 +- **Enable Pages**: `POST /repos/{owner}/{repo}/pages`
187 +- **Check Status**: `GET /repos/{owner}/{repo}/pages`
188 +- **Trigger Rebuild**: `POST /repos/{owner}/{repo}/pages/builds`
189 +- **Latest Build**: `GET /repos/{owner}/{repo}/pages/builds/latest`
191 +All authentication is handled by the GitHub CLI, so you don't need to manage tokens manually.
193 +## GitHub Actions Workflow
195 +The generated workflow file (`.github/workflows/pages.yml`) uses the official GitHub Actions for Pages deployment:
197 +- `actions/configure-pages@v5` - Configure Pages metadata
198 +- `actions/upload-pages-artifact@v3` - Package and upload site
199 +- `actions/deploy-pages@v4` - Deploy to Pages
201 +This is the **official, recommended approach** for GitHub Pages deployment.
203 +## Customizing Your Build
205 +Edit the "Build site" step in `.github/workflows/pages.yml`:
207 +### Static HTML Site
208 +```yaml
209 +- name: Build site
210 + run: |
211 + mkdir -p _site
212 + cp -r * _site/
213 +```
215 +### Node.js / npm
216 +```yaml
217 +- name: Build site
218 + run: |
219 + npm install
220 + npm run build
221 + mkdir -p _site
222 + cp -r dist/* _site/
223 +```
225 +### Python / MkDocs
226 +```yaml
227 +- name: Setup Python
228 + uses: actions/setup-python@v4
229 + with:
230 + python-version: '3.x'
232 +- name: Build site
233 + run: |
234 + pip install mkdocs
235 + mkdocs build
236 + mv site _site
237 +```
239 +### Jekyll
240 +```yaml
241 +- name: Setup Ruby
242 + uses: ruby/setup-ruby@v1
243 + with:
244 + ruby-version: '3.1'
246 +- name: Build site
247 + run: |
248 + gem install jekyll bundler
249 + bundle install
250 + bundle exec jekyll build -d _site
251 +```
253 +## Troubleshooting
255 +### "GitHub CLI is not authenticated"
257 +Run `gh auth login` to authenticate the GitHub CLI.
259 +### "Failed to enable Pages: ... requires admin permissions"
261 +You need admin access to the repository to enable GitHub Pages.
263 +### "Pages may already be enabled"
265 +Pages is already configured. Use `status` command to check configuration, or update settings in the repository settings.
267 +### Workflow not deploying
269 +1. Check that Pages source is set to "GitHub Actions" in repository settings (Settings > Pages)
270 +2. Verify the workflow file is in `.github/workflows/` directory
271 +3. Check workflow runs in the Actions tab
272 +4. Ensure proper permissions in the workflow file
274 +## API Reference
276 +### GitHubPagesManager Class
278 +```python
279 +manager = GitHubPagesManager('owner/repo')
281 +# Enable Pages
282 +manager.enable_pages(
283 + branch='main',
284 + path='/',
285 + build_type='workflow', # or 'legacy'
286 + https_enforced=True
289 +# Check status
290 +manager.check_status()
292 +# Trigger rebuild
293 +manager.trigger_rebuild()
295 +# Get latest build info
296 +manager.get_latest_build()
297 +```
299 +## Repository Settings
301 +After enabling Pages with this script, you can verify settings at:
303 +```
304 +https://github.com/owner/repo/settings/pages
305 +```
307 +Ensure the "Source" is set to:
308 +- **GitHub Actions** (if using `build_type='workflow'`)
309 +- **Deploy from a branch** (if using `build_type='legacy'`)
311 +## License
313 +MIT License - feel free to use and modify as needed.
315 +## Resources
317 +- [GitHub Pages Documentation](https://docs.github.com/pages)
318 +- [GitHub CLI Documentation](https://cli.github.com/manual/)
319 +- [GitHub REST API - Pages](https://docs.github.com/rest/pages)
320 +- [GitHub Actions for Pages](https://github.com/actions/deploy-pages)

pi/agent/skills/gh-cli/scripts/gh_code_search.py

Added
new file mode 100755
1 +#!/usr/bin/env python3
2 +"""
3 +Python wrapper for 'gh search code' with filtering and formatting capabilities.
5 +Provides enhanced search functionality with custom filters and multiple output formats.
6 +"""
8 +import argparse
9 +import json
10 +import subprocess
11 +import sys
12 +from typing import List, Dict, Any, Optional
13 +from pathlib import Path
16 +class GHSearchError(Exception):
17 + """Custom exception for gh search errors."""
18 + pass
21 +def check_gh_installed() -> bool:
22 + """Check if gh CLI is installed and authenticated."""
23 + try:
24 + result = subprocess.run(
25 + ["gh", "auth", "status"],
26 + capture_output=True,
27 + text=True,
28 + check=False
29 + )
30 + return result.returncode == 0
31 + except FileNotFoundError:
32 + return False
35 +def build_gh_command(args: argparse.Namespace) -> List[str]:
36 + """
37 + Build the gh search code command from parsed arguments.
39 + Args:
40 + args: Parsed command-line arguments
42 + Returns:
43 + List of command components for subprocess
44 + """
45 + cmd = ["gh", "search", "code", args.query]
47 + # Add limit
48 + if args.limit:
49 + cmd.extend(["--limit", str(args.limit)])
51 + # Add language filter
52 + if args.language:
53 + cmd.extend(["--language", args.language])
55 + # Add filename filter
56 + if args.filename:
57 + cmd.extend(["--filename", args.filename])
59 + # Add extension filter
60 + if args.extension:
61 + cmd.extend(["--extension", args.extension])
63 + # Add repository filters (can have multiple)
64 + if args.repo:
65 + for repo in args.repo:
66 + cmd.extend(["--repo", repo])
68 + # Add owner filters (can have multiple)
69 + if args.owner:
70 + for owner in args.owner:
71 + cmd.extend(["--owner", owner])
73 + # Add match type filter
74 + if args.match:
75 + cmd.extend(["--match", args.match])
77 + # Add size filter
78 + if args.size:
79 + cmd.extend(["--size", args.size])
81 + # Always request JSON output with all available fields
82 + cmd.extend(["--json", "path,repository,sha,textMatches,url"])
84 + return cmd
87 +def execute_search(cmd: List[str], timeout: int = 30) -> List[Dict[str, Any]]:
88 + """
89 + Execute the gh search code command and parse JSON output.
91 + Args:
92 + cmd: Command to execute
93 + timeout: Timeout in seconds
95 + Returns:
96 + List of search results
98 + Raises:
99 + GHSearchError: If the command fails
100 + """
101 + try:
102 + result = subprocess.run(
103 + cmd,
104 + capture_output=True,
105 + text=True,
106 + check=True,
107 + timeout=timeout
110 + # Parse JSON output
111 + if result.stdout.strip():
112 + return json.loads(result.stdout)
113 + return []
115 + except subprocess.TimeoutExpired:
116 + raise GHSearchError(
117 + f"Search timed out after {timeout} seconds. "
118 + "Try a simpler query or increase --timeout."
121 + except subprocess.CalledProcessError as e:
122 + # Parse error message
123 + error_msg = e.stderr.strip()
125 + if "HTTP 403" in error_msg and "rate limit" in error_msg.lower():
126 + raise GHSearchError(
127 + "GitHub API rate limit exceeded. Please wait and try again later.\n"
128 + f"Details: {error_msg}"
130 + elif "HTTP 408" in error_msg:
131 + raise GHSearchError(
132 + "Search query timed out. Try a simpler query or try again later.\n"
133 + f"Details: {error_msg}"
135 + else:
136 + raise GHSearchError(f"GitHub search failed: {error_msg}")
138 + except json.JSONDecodeError as e:
139 + raise GHSearchError(f"Failed to parse JSON output: {e}")
142 +def filter_results(results: List[Dict[str, Any]], args: argparse.Namespace) -> List[Dict[str, Any]]:
143 + """
144 + Apply custom filters to search results.
146 + Args:
147 + results: Raw search results
148 + args: Parsed arguments with filter options
150 + Returns:
151 + Filtered results
152 + """
153 + filtered = results
155 + # Filter out forks if requested
156 + if args.exclude_forks:
157 + filtered = [r for r in filtered if not r.get("repository", {}).get("isFork", False)]
159 + # Filter out private repos if requested
160 + if args.exclude_private:
161 + filtered = [r for r in filtered if not r.get("repository", {}).get("isPrivate", False)]
163 + # Filter by minimum match count
164 + if args.min_matches:
165 + filtered = [
166 + r for r in filtered
167 + if len(r.get("textMatches", [])) >= args.min_matches
170 + return filtered
173 +def sort_results(results: List[Dict[str, Any]], sort_by: Optional[str]) -> List[Dict[str, Any]]:
174 + """
175 + Sort results by specified criteria.
177 + Args:
178 + results: Search results to sort
179 + sort_by: Sort criteria (matches, repo, path)
181 + Returns:
182 + Sorted results
183 + """
184 + if not sort_by:
185 + return results
187 + if sort_by == "matches":
188 + return sorted(results, key=lambda r: len(r.get("textMatches", [])), reverse=True)
189 + elif sort_by == "repo":
190 + return sorted(results, key=lambda r: r.get("repository", {}).get("nameWithOwner", ""))
191 + elif sort_by == "path":
192 + return sorted(results, key=lambda r: r.get("path", ""))
194 + return results
197 +def format_json(results: List[Dict[str, Any]]) -> str:
198 + """Format results as JSON."""
199 + return json.dumps(results, indent=2)
202 +def format_pretty(results: List[Dict[str, Any]]) -> str:
203 + """Format results as pretty-printed table."""
204 + if not results:
205 + return "No results found."
207 + output = []
208 + output.append(f"Found {len(results)} result(s)\n")
209 + output.append("=" * 80)
211 + for i, result in enumerate(results, 1):
212 + repo = result.get("repository", {}).get("nameWithOwner", "Unknown")
213 + path = result.get("path", "Unknown")
214 + url = result.get("url", "")
215 + matches = result.get("textMatches", [])
217 + output.append(f"\n{i}. {repo}:{path}")
218 + output.append(f" URL: {url}")
219 + output.append(f" Matches: {len(matches)}")
221 + # Show first text match snippet
222 + if matches:
223 + fragment = matches[0].get("fragment", "")
224 + if fragment:
225 + # Truncate long fragments
226 + if len(fragment) > 100:
227 + fragment = fragment[:97] + "..."
228 + output.append(f" Preview: {fragment}")
230 + output.append("-" * 80)
232 + return "\n".join(output)
235 +def format_summary(results: List[Dict[str, Any]]) -> str:
236 + """Format results as summary statistics."""
237 + if not results:
238 + return "No results found."
240 + # Aggregate stats
241 + repos = {}
242 + total_matches = 0
243 + extensions = {}
245 + for result in results:
246 + repo_name = result.get("repository", {}).get("nameWithOwner", "Unknown")
247 + repos[repo_name] = repos.get(repo_name, 0) + 1
249 + matches = result.get("textMatches", [])
250 + total_matches += len(matches)
252 + path = result.get("path", "")
253 + if "." in path:
254 + ext = path.rsplit(".", 1)[-1]
255 + extensions[ext] = extensions.get(ext, 0) + 1
257 + output = []
258 + output.append("SEARCH SUMMARY")
259 + output.append("=" * 80)
260 + output.append(f"Total files found: {len(results)}")
261 + output.append(f"Total text matches: {total_matches}")
262 + output.append(f"Unique repositories: {len(repos)}")
264 + output.append(f"\nTop Repositories:")
265 + for repo, count in sorted(repos.items(), key=lambda x: x[1], reverse=True)[:10]:
266 + output.append(f" {repo}: {count} file(s)")
268 + output.append(f"\nFile Extensions:")
269 + for ext, count in sorted(extensions.items(), key=lambda x: x[1], reverse=True):
270 + output.append(f" .{ext}: {count} file(s)")
272 + return "\n".join(output)
275 +def main():
276 + """Main entry point."""
277 + parser = argparse.ArgumentParser(
278 + description="Enhanced wrapper for 'gh search code' with filtering and formatting.",
279 + formatter_class=argparse.RawDescriptionHelpFormatter,
280 + epilog="""
281 +Examples:
282 + %(prog)s "hello world" --language python
283 + %(prog)s "error handling" --repo microsoft/vscode --output pretty
284 + %(prog)s "TODO" --extension md --exclude-forks --output summary
285 + %(prog)s "class.*Component" --language typescript --sort-by matches
286 + %(prog)s "TODO" --output json --output-file results.json
287 + """
290 + # Check gh installation
291 + if not check_gh_installed():
292 + print("Error: GitHub CLI (gh) is not installed or not authenticated.", file=sys.stderr)
293 + print("Install from: https://cli.github.com/", file=sys.stderr)
294 + print("Then run: gh auth login", file=sys.stderr)
295 + sys.exit(1)
297 + # Required arguments
298 + parser.add_argument("query", help="Search query (supports GitHub code search syntax)")
300 + # gh search code options
301 + parser.add_argument("-L", "--limit", type=int, default=30,
302 + help="Maximum number of results (default: 30)")
303 + parser.add_argument("--language", help="Filter by programming language")
304 + parser.add_argument("--filename", help="Filter by filename")
305 + parser.add_argument("--extension", help="Filter by file extension")
306 + parser.add_argument("-R", "--repo", action="append", help="Filter by repository (can specify multiple)")
307 + parser.add_argument("--owner", action="append", help="Filter by owner (can specify multiple)")
308 + parser.add_argument("--match", choices=["file", "content"],
309 + help="Restrict search to file path or content")
310 + parser.add_argument("--size", help="Filter by file size range (e.g., '10..100' in KB)")
312 + # Custom filtering options
313 + parser.add_argument("--exclude-forks", action="store_true",
314 + help="Exclude results from forked repositories")
315 + parser.add_argument("--exclude-private", action="store_true",
316 + help="Exclude results from private repositories")
317 + parser.add_argument("--min-matches", type=int,
318 + help="Minimum number of text matches per file")
320 + # Output options
321 + parser.add_argument("-o", "--output", choices=["json", "pretty", "summary"],
322 + default="pretty", help="Output format (default: pretty)")
323 + parser.add_argument("--sort-by", choices=["matches", "repo", "path"],
324 + help="Sort results by criteria")
325 + parser.add_argument("--output-file", type=Path,
326 + help="Write output to file instead of stdout")
327 + parser.add_argument("--timeout", type=int, default=30,
328 + help="Timeout for search in seconds (default: 30)")
330 + args = parser.parse_args()
332 + try:
333 + # Build and execute search command
334 + cmd = build_gh_command(args)
335 + results = execute_search(cmd, timeout=args.timeout)
337 + # Apply filters
338 + results = filter_results(results, args)
340 + # Sort results
341 + results = sort_results(results, args.sort_by)
343 + # Format output
344 + if args.output == "json":
345 + output = format_json(results)
346 + elif args.output == "summary":
347 + output = format_summary(results)
348 + else: # pretty
349 + output = format_pretty(results)
351 + # Write to file or stdout
352 + if args.output_file:
353 + args.output_file.parent.mkdir(parents=True, exist_ok=True)
354 + args.output_file.write_text(output)
355 + print(f"Results written to {args.output_file}", file=sys.stderr)
356 + else:
357 + print(output)
358 + sys.exit(0)
360 + except GHSearchError as e:
361 + print(f"Error: {e}", file=sys.stderr)
362 + sys.exit(1)
363 + except KeyboardInterrupt:
364 + print("\nSearch cancelled by user.", file=sys.stderr)
365 + sys.exit(130)
366 + except Exception as e:
367 + print(f"Unexpected error: {e}", file=sys.stderr)
368 + sys.exit(1)
371 +if __name__ == "__main__":
372 + main()

pi/agent/skills/gh-cli/scripts/gh_failed_run.py

Added
new file mode 100755
1 +#!/usr/bin/env python3
2 +"""
3 +GitHub Actions Failed Run Analyzer
5 +This script finds the most recent failed GitHub Actions run (or a specific run)
6 +and provides detailed information about what went wrong, including error excerpts from logs.
7 +"""
9 +import argparse
10 +import json
11 +import subprocess
12 +import sys
13 +import re
14 +from typing import Optional, Dict, List, Any
17 +# Comprehensive ANSI escape sequence patterns
18 +ANSI_PATTERNS = [
19 + r'\x1b\[[0-9;]*m', # SGR (color/style)
20 + r'\x1b\[[0-9;]*;[0-9;]*m', # Extended SGR
21 + r'\x1b\][^\x07]*\x07', # OSC (title, etc)
22 + r'\x1b\[[0-9;]*H', # Cursor position
23 + r'\x1b\[([0-9]+)?J', # Erase display
24 + r'\x1b\[([0-9]+)?K', # Erase line
25 + r'\x1b\[[0-9;]*;[0-9;]*H', # Cursor position
26 + r'\r', # Carriage return (keep newlines)
30 +def clean_ansi(text: str) -> str:
31 + """Remove all ANSI escape sequences from text."""
32 + result = text
33 + for pattern in ANSI_PATTERNS:
34 + result = re.sub(pattern, '', result)
35 + return result
38 +def check_gh_installed() -> bool:
39 + """Check if gh CLI is installed and authenticated."""
40 + try:
41 + result = subprocess.run(
42 + ["gh", "auth", "status"],
43 + capture_output=True,
44 + text=True,
45 + check=False
46 + )
47 + return result.returncode == 0
48 + except FileNotFoundError:
49 + return False
52 +def run_gh_command(cmd: List[str], timeout: int = 60) -> Dict[str, Any]:
53 + """
54 + Execute a gh CLI command and return parsed JSON output.
56 + Args:
57 + cmd: List of command arguments to pass to gh
58 + timeout: Timeout in seconds
60 + Returns:
61 + Parsed JSON output from the command
63 + Raises:
64 + SystemExit: If gh command fails
65 + """
66 + try:
67 + result = subprocess.run(
68 + cmd,
69 + capture_output=True,
70 + text=True,
71 + check=True,
72 + timeout=timeout
73 + )
74 + return json.loads(result.stdout) if result.stdout else {}
75 + except subprocess.TimeoutExpired:
76 + print(f"Error: gh command timed out after {timeout}s", file=sys.stderr)
77 + sys.exit(1)
78 + except subprocess.CalledProcessError as e:
79 + print(f"Error running gh command: {' '.join(cmd)}", file=sys.stderr)
80 + print(f"Error: {e.stderr}", file=sys.stderr)
81 + sys.exit(1)
82 + except json.JSONDecodeError as e:
83 + print(f"Error parsing JSON output from gh command", file=sys.stderr)
84 + print(f"Error: {e}", file=sys.stderr)
85 + sys.exit(1)
88 +def get_run_by_id(run_id: int, repo: Optional[str] = None) -> Optional[Dict[str, Any]]:
89 + """
90 + Get a specific workflow run by ID.
92 + Args:
93 + run_id: The workflow run database ID
94 + repo: Optional repository in format 'owner/name'
96 + Returns:
97 + Run information dictionary or None if not found
98 + """
99 + cmd = [
100 + "gh", "run", "view", str(run_id),
101 + "--json", "databaseId,number,conclusion,status,createdAt,displayTitle,url,headBranch,headSha,event"
104 + if repo:
105 + cmd.extend(["--repo", repo])
107 + try:
108 + runs = run_gh_command(cmd)
109 + return runs if runs else None
110 + except SystemExit:
111 + return None
114 +def get_most_recent_failed_run(repo: Optional[str] = None) -> Optional[Dict[str, Any]]:
115 + """
116 + Get the most recent failed workflow run.
118 + Args:
119 + repo: Optional repository in format 'owner/name'
121 + Returns:
122 + Run information dictionary or None if no failed runs found
123 + """
124 + cmd = [
125 + "gh", "run", "list",
126 + "--status", "failure",
127 + "--limit", "1",
128 + "--json", "databaseId,number,conclusion,status,createdAt,displayTitle,url,headBranch,headSha,event"
131 + if repo:
132 + cmd.extend(["--repo", repo])
134 + runs = run_gh_command(cmd)
136 + if not runs:
137 + return None
139 + return runs[0]
142 +def get_failed_jobs(run_id: int, repo: Optional[str] = None) -> List[Dict[str, Any]]:
143 + """
144 + Get all jobs from a run and filter for failed ones.
146 + Args:
147 + run_id: The workflow run database ID
148 + repo: Optional repository in format 'owner/name'
150 + Returns:
151 + List of failed job dictionaries
152 + """
153 + cmd = [
154 + "gh", "run", "view", str(run_id),
155 + "--json", "jobs"
158 + if repo:
159 + cmd.extend(["--repo", repo])
161 + result = run_gh_command(cmd)
162 + jobs = result.get("jobs", [])
164 + # Filter for failed jobs (conclusion is failure, timed_out, cancelled, etc.)
165 + failed_jobs = [
166 + job for job in jobs
167 + if job.get("conclusion") not in ["success", "skipped", None]
170 + return failed_jobs
173 +def extract_error_excerpts(log_text: str, max_lines: int = 50) -> List[str]:
174 + """
175 + Extract relevant error lines from log text.
177 + Args:
178 + log_text: Raw log text from failed job
179 + max_lines: Maximum number of error lines to return
181 + Returns:
182 + List of error excerpt strings
183 + """
184 + error_patterns = [
185 + r".*\berror\b.*",
186 + r".*\bfailed\b.*",
187 + r".*\bfailure\b.*",
188 + r".*\bexception\b.*",
189 + r".*\bERROR\b.*",
190 + r".*\bFAILED\b.*",
191 + r".*\bFAILURE\b.*",
192 + r".*\bEXCEPTION\b.*",
193 + r".*\bcannot\b.*",
194 + r".*\bpanic\b.*",
195 + r".*Process completed with exit code [1-9].*",
196 + r".*\btimeout\b.*",
199 + excerpts = []
200 + lines = log_text.split('\n')
202 + for line in lines:
203 + # Clean ANSI codes and normalize whitespace
204 + clean_line = clean_ansi(line).strip()
206 + if not clean_line:
207 + continue
209 + # Skip GitHub Actions metadata lines (but keep error messages)
210 + if re.match(r'^##\[command\]', clean_line):
211 + continue
212 + if re.match(r'^##\[group\]', clean_line):
213 + continue
214 + if re.match(r'^##\[endgroup\]', clean_line):
215 + continue
217 + # Check if line matches any error pattern
218 + for pattern in error_patterns:
219 + if re.search(pattern, clean_line, re.IGNORECASE):
220 + if clean_line not in excerpts:
221 + excerpts.append(clean_line)
222 + if len(excerpts) >= max_lines:
223 + return excerpts
224 + break
226 + return excerpts
229 +def get_job_logs(run_id: int, job_name: str, repo: Optional[str] = None) -> str:
230 + """
231 + Get logs for a specific failed job.
233 + Args:
234 + run_id: The workflow run database ID
235 + job_name: The name of the job
236 + repo: Optional repository in format 'owner/name'
238 + Returns:
239 + Log text for the job
240 + """
241 + cmd = [
242 + "gh", "run", "view", str(run_id),
243 + "--log-failed",
244 + "--job", job_name
247 + if repo:
248 + cmd.extend(["--repo", repo])
250 + try:
251 + result = subprocess.run(
252 + cmd,
253 + capture_output=True,
254 + text=True,
255 + check=True,
256 + timeout=120
258 + return result.stdout
259 + except subprocess.CalledProcessError:
260 + # If specific job logs fail, try getting all failed logs
261 + cmd_all = [
262 + "gh", "run", "view", str(run_id),
263 + "--log-failed"
265 + if repo:
266 + cmd_all.extend(["--repo", repo])
268 + try:
269 + result = subprocess.run(
270 + cmd_all,
271 + capture_output=True,
272 + text=True,
273 + check=True,
274 + timeout=120
276 + return result.stdout
277 + except subprocess.CalledProcessError:
278 + return ""
281 +def analyze_failed_run(repo: Optional[str] = None, run_id: Optional[int] = None) -> Dict[str, Any]:
282 + """
283 + Analyze a failed run and extract all relevant information.
285 + Args:
286 + repo: Optional repository in format 'owner/name'
287 + run_id: Optional specific run ID to analyze
289 + Returns:
290 + Dictionary containing run analysis
291 + """
292 + # Get run info
293 + if run_id:
294 + run = get_run_by_id(run_id, repo)
295 + else:
296 + run = get_most_recent_failed_run(repo)
298 + if not run:
299 + return {
300 + "error": f"No failed runs found{f' for run {run_id}' if run_id else ''}",
301 + "repository": repo or "current"
304 + # Get failed jobs using databaseId
305 + failed_jobs = get_failed_jobs(run["databaseId"], repo)
307 + # Build result structure
308 + result = {
309 + "run": {
310 + "number": run["number"],
311 + "database_id": run["databaseId"],
312 + "url": run["url"],
313 + "workflow": run["displayTitle"],
314 + "conclusion": run["conclusion"],
315 + "status": run["status"],
316 + "created_at": run["createdAt"],
317 + "branch": run.get("headBranch"),
318 + "commit": run.get("headSha"),
319 + "event": run.get("event")
320 + },
321 + "failed_jobs": [],
322 + "repository": repo or "current"
325 + # Analyze each failed job
326 + for job in failed_jobs:
327 + job_info = {
328 + "name": job["name"],
329 + "conclusion": job["conclusion"],
330 + "status": job.get("status"),
331 + "started_at": job.get("startedAt"),
332 + "completed_at": job.get("completedAt"),
333 + "error_excerpts": []
336 + # Get logs and extract errors using databaseId
337 + logs = get_job_logs(run["databaseId"], job["name"], repo)
338 + if logs:
339 + job_info["error_excerpts"] = extract_error_excerpts(logs)
341 + result["failed_jobs"].append(job_info)
343 + return result
346 +def main():
347 + """Main entry point for the script."""
348 + parser = argparse.ArgumentParser(
349 + description="Analyze GitHub Actions failed runs and extract error information",
350 + formatter_class=argparse.RawDescriptionHelpFormatter,
351 + epilog="""
352 +Examples:
353 + %(prog)s # Analyze current repository
354 + %(prog)s --repo owner/name # Analyze specific repository
355 + %(prog)s --run-id 12345 # Analyze specific run ID
356 + %(prog)s --json # Output as compact JSON
357 + %(prog)s --pretty # Output as pretty JSON
358 + """
361 + parser.add_argument(
362 + "--repo",
363 + type=str,
364 + help="Repository to analyze in format 'owner/name'"
367 + parser.add_argument(
368 + "--run-id",
369 + type=int,
370 + help="Specific run ID to analyze"
373 + parser.add_argument(
374 + "--pretty",
375 + action="store_true",
376 + help="Pretty-print JSON output with indentation"
379 + parser.add_argument(
380 + "--json",
381 + action="store_true",
382 + help="Output as JSON (alias for machine-readable)"
385 + parser.add_argument(
386 + "--timeout",
387 + type=int,
388 + default=120,
389 + help="Timeout for fetching logs in seconds (default: 120)"
392 + args = parser.parse_args()
394 + # Check if gh CLI is installed
395 + if not check_gh_installed():
396 + print("Error: gh CLI is not installed or not in PATH", file=sys.stderr)
397 + print("Install it from: https://cli.github.com/", file=sys.stderr)
398 + sys.exit(1)
400 + # Analyze the failed run
401 + result = analyze_failed_run(args.repo, args.run_id)
403 + # Output JSON
404 + if args.pretty or (args.json and args.pretty):
405 + print(json.dumps(result, indent=2))
406 + else:
407 + print(json.dumps(result))
410 +if __name__ == "__main__":
411 + main()

pi/agent/skills/gh-cli/scripts/gh_pages_deploy.py

Added
new file mode 100755
1 +#!/usr/bin/env python3
2 +"""
3 +GitHub Pages Deployment Script
5 +A Python script to automate GitHub Pages deployment using the GitHub CLI (gh).
6 +Supports enabling Pages, checking status, triggering rebuilds, and creating deployment workflows.
8 +Requirements:
9 + - GitHub CLI (gh) must be installed and authenticated
10 + - Python 3.8+
12 +Usage:
13 + python gh_pages_deploy.py enable <owner>/<repo> [--branch BRANCH] [--path PATH]
14 + python gh_pages_deploy.py status <owner>/<repo>
15 + python gh_pages_deploy.py rebuild <owner>/<repo>
16 + python gh_pages_deploy.py create-workflow [--output PATH]
17 +"""
19 +import argparse
20 +import json
21 +import subprocess
22 +import sys
23 +import re
24 +from pathlib import Path
25 +from typing import Dict, Optional, Tuple, List
28 +class GitHubPagesError(Exception):
29 + """Custom exception for GitHub Pages errors."""
30 + pass
33 +def check_gh_auth() -> Tuple[bool, List[str]]:
34 + """
35 + Verify gh CLI is authenticated and check available scopes.
37 + Returns:
38 + Tuple of (is_authenticated, scopes_list)
39 + """
40 + try:
41 + result = subprocess.run(
42 + ['gh', 'auth', 'status', '--show-token'],
43 + capture_output=True,
44 + text=True,
45 + check=False
46 + )
47 + if result.returncode != 0:
48 + return False, []
50 + # Extract scopes from output
51 + scopes = []
52 + for line in result.stdout.split('\n'):
53 + if 'scope' in line.lower():
54 + # Parse scope lines like " - workflow:..."
55 + match = re.search(r':\s*(\w+)', line)
56 + if match:
57 + scopes.append(match.group(1))
59 + return True, scopes
60 + except FileNotFoundError:
61 + return False, []
64 +def format_json(data: Dict) -> str:
65 + """Format data as JSON for machine output."""
66 + return json.dumps(data, indent=2)
69 +def format_message(msg: str, style: str = "info") -> str:
70 + """Format a message with style prefix."""
71 + prefixes = {
72 + "info": "ℹ",
73 + "success": "✓",
74 + "error": "✗",
75 + "warning": "⚠",
76 + }
77 + return f"{prefixes.get(style, '')} {msg}"
80 +class GitHubPagesManager:
81 + """Manager class for GitHub Pages operations using gh CLI."""
83 + def __init__(self, repo: str, dry_run: bool = False, json_output: bool = False):
84 + """
85 + Initialize the manager with a repository.
87 + Args:
88 + repo: Repository in format 'owner/repo'
89 + dry_run: If True, only show what would be done
90 + json_output: If True, output machine-readable JSON
91 + """
92 + self.repo = repo
93 + self.dry_run = dry_run
94 + self.json_output = json_output
95 + self.last_result: Dict = {}
96 + self._verify_gh_cli()
98 + def _verify_gh_cli(self) -> None:
99 + """Verify that gh CLI is installed and authenticated."""
100 + is_auth, scopes = check_gh_auth()
101 + if not is_auth:
102 + error = {
103 + "error": "GitHub CLI is not authenticated",
104 + "solution": "Run 'gh auth login' to authenticate"
106 + if self.json_output:
107 + print(format_json(error))
108 + else:
109 + print(format_message("GitHub CLI is not authenticated.", "error"), file=sys.stderr)
110 + print("Run 'gh auth login' to authenticate.", file=sys.stderr)
111 + sys.exit(1)
113 + # Verify repo scope
114 + if 'repo' not in scopes:
115 + warning = {
116 + "warning": "Missing 'repo' scope",
117 + "scopes": scopes,
118 + "may_not_work": "Private repo operations may fail"
120 + if self.json_output:
121 + print(format_json(warning))
123 + def _run_gh_api(
124 + self,
125 + endpoint: str,
126 + method: str = 'GET',
127 + data: Optional[Dict] = None,
128 + check: bool = True
129 + ) -> Tuple[int, Dict]:
130 + """
131 + Execute a gh api command.
133 + Args:
134 + endpoint: API endpoint (e.g., '/repos/owner/repo/pages')
135 + method: HTTP method (GET, POST, PUT, DELETE)
136 + data: Optional data dictionary for POST/PUT requests
137 + check: Whether to raise error on non-zero exit code
139 + Returns:
140 + Tuple of (status_code, response_dict)
141 + """
142 + if self.dry_run and method != 'GET':
143 + print(f"[DRY RUN] Would execute: {method} {endpoint}", file=sys.stderr)
144 + if data:
145 + print(f"[DRY RUN] With data: {json.dumps(data)}", file=sys.stderr)
146 + return 0, {"dry_run": True, "endpoint": endpoint, "method": method}
148 + cmd = [
149 + 'gh', 'api',
150 + '-X', method,
151 + '-H', 'Accept: application/vnd.github+json',
152 + '-H', 'X-GitHub-Api-Version: 2022-11-28',
153 + endpoint
156 + # Add data fields if provided
157 + if data:
158 + for key, value in data.items():
159 + if isinstance(value, bool):
160 + cmd.extend(['-f', f'{key}={"true" if value else "false"}'])
161 + elif isinstance(value, dict):
162 + # Handle nested objects (e.g., source[branch])
163 + for subkey, subvalue in value.items():
164 + cmd.extend(['-f', f'{key}[{subkey}]={subvalue}'])
165 + else:
166 + cmd.extend(['-f', f'{key}={value}'])
168 + try:
169 + result = subprocess.run(
170 + cmd,
171 + capture_output=True,
172 + text=True,
173 + check=check,
174 + timeout=30
177 + response = {}
178 + if result.stdout.strip():
179 + try:
180 + response = json.loads(result.stdout)
181 + except json.JSONDecodeError:
182 + response = {'raw': result.stdout}
184 + if result.returncode != 0 and check:
185 + error_msg = result.stderr or str(response)
186 + raise GitHubPagesError(f"API call failed: {error_msg}")
188 + return result.returncode, response
190 + except subprocess.TimeoutExpired:
191 + raise GitHubPagesError("API request timed out after 30 seconds")
192 + except subprocess.CalledProcessError as e:
193 + error_msg = e.stderr or str(e)
194 + raise GitHubPagesError(f"Failed to execute gh command: {error_msg}")
196 + def enable_pages(
197 + self,
198 + branch: str = 'main',
199 + path: str = '/',
200 + build_type: str = 'workflow',
201 + https_enforced: bool = True
202 + ) -> Dict:
203 + """
204 + Enable GitHub Pages for the repository.
206 + Args:
207 + branch: Source branch (default: 'main')
208 + path: Source path, '/' or '/docs' (default: '/')
209 + build_type: 'workflow' for GitHub Actions or 'legacy' for Jekyll (default: 'workflow')
210 + https_enforced: Whether to enforce HTTPS (default: True)
212 + Returns:
213 + API response dictionary
214 + """
215 + if not self.json_output:
216 + print(f"Enabling GitHub Pages for {self.repo}...")
217 + print(f" Branch: {branch}")
218 + print(f" Path: {path}")
219 + print(f" Build type: {build_type}")
221 + endpoint = f'/repos/{self.repo}/pages'
223 + data = {
224 + 'source': {
225 + 'branch': branch,
226 + 'path': path
227 + },
228 + 'build_type': build_type
231 + # Try to create Pages site
232 + status, response = self._run_gh_api(endpoint, method='POST', data=data, check=False)
234 + if status == 0 or response.get('dry_run'):
235 + is_dry_run = response.get('dry_run', False)
236 + self.last_result = {
237 + "status": "success" if not is_dry_run else "dry_run",
238 + "action": "pages_enabled",
239 + "repository": self.repo,
240 + "config": {
241 + "branch": branch,
242 + "path": path,
243 + "build_type": build_type,
244 + "https_enforced": https_enforced
245 + },
246 + "dry_run": is_dry_run
248 + if self.json_output:
249 + print(format_json(self.last_result))
250 + elif is_dry_run:
251 + print(format_message("GitHub Pages would be enabled (dry-run)", "success"))
252 + else:
253 + print(format_message("GitHub Pages enabled successfully!", "success"))
255 + # Update to enforce HTTPS if requested (skip in dry run)
256 + if https_enforced and not self.dry_run:
257 + if not self.json_output:
258 + print(" Enforcing HTTPS...")
259 + self._run_gh_api(
260 + endpoint,
261 + method='PUT',
262 + data={'https_enforced': True},
263 + check=False
266 + return response
267 + elif status == 422:
268 + # Pages might already exist
269 + if not self.json_output:
270 + print(format_message("Pages may already be enabled. Checking status...", "warning"))
271 + return self.check_status()
272 + else:
273 + error = response.get('message', 'Unknown error')
274 + self.last_result = {"status": "error", "error": error}
275 + if self.json_output:
276 + print(format_json(self.last_result))
277 + else:
278 + print(format_message(f"Failed to enable Pages: {error}", "error"), file=sys.stderr)
279 + return response
281 + def check_status(self) -> Dict:
282 + """
283 + Check GitHub Pages status and configuration.
285 + Returns:
286 + API response dictionary with Pages information
287 + """
288 + if not self.json_output:
289 + print(f"Checking GitHub Pages status for {self.repo}...")
291 + endpoint = f'/repos/{self.repo}/pages'
292 + status, response = self._run_gh_api(endpoint, check=False)
294 + if status == 0:
295 + self.last_result = {
296 + "status": "enabled",
297 + "repository": self.repo,
298 + "url": response.get('html_url', 'N/A'),
299 + "pages_status": response.get('status', 'N/A'),
300 + "build_type": response.get('build_type', 'N/A'),
301 + "source": response.get('source', {}),
302 + "https_enforced": response.get('https_enforced', False),
303 + "custom_domain": response.get('cname')
305 + if self.json_output:
306 + print(format_json(self.last_result))
307 + else:
308 + print(format_message("GitHub Pages is enabled:", "success"))
309 + print(f" URL: {response.get('html_url', 'N/A')}")
310 + print(f" Status: {response.get('status', 'N/A')}")
311 + print(f" Build type: {response.get('build_type', 'N/A')}")
313 + source = response.get('source', {})
314 + print(f" Source branch: {source.get('branch', 'N/A')}")
315 + print(f" Source path: {source.get('path', 'N/A')}")
316 + print(f" HTTPS enforced: {response.get('https_enforced', False)}")
318 + if response.get('cname'):
319 + print(f" Custom domain: {response.get('cname')}")
320 + else:
321 + self.last_result = {
322 + "status": "disabled",
323 + "repository": self.repo,
324 + "message": "GitHub Pages is not enabled"
326 + if self.json_output:
327 + print(format_json(self.last_result))
328 + else:
329 + print(format_message("GitHub Pages is not enabled for this repository.", "warning"), file=sys.stderr)
331 + return response
333 + def trigger_rebuild(self) -> Dict:
334 + """
335 + Trigger a new GitHub Pages build.
337 + Returns:
338 + API response dictionary
339 + """
340 + if not self.json_output:
341 + print(f"Triggering rebuild for {self.repo}...")
343 + endpoint = f'/repos/{self.repo}/pages/builds'
344 + status, response = self._run_gh_api(endpoint, method='POST', check=False)
346 + if status == 0 or response.get('dry_run'):
347 + self.last_result = {
348 + "status": "triggered",
349 + "repository": self.repo,
350 + "build_url": response.get('url')
352 + if self.json_output:
353 + print(format_json(self.last_result))
354 + else:
355 + print(format_message("Build triggered successfully!", "success"))
356 + print(f" Status: {response.get('status', 'N/A')}")
357 + if 'url' in response:
358 + print(f" Build URL: {response['url']}")
359 + else:
360 + error = response.get('message', 'Unknown error')
361 + self.last_result = {"status": "error", "error": error}
362 + if self.json_output:
363 + print(format_json(self.last_result))
364 + else:
365 + print(format_message(f"Failed to trigger build: {error}", "error"), file=sys.stderr)
367 + return response
369 + def get_latest_build(self) -> Dict:
370 + """
371 + Get the latest build information.
373 + Returns:
374 + API response dictionary with latest build info
375 + """
376 + endpoint = f'/repos/{self.repo}/pages/builds/latest'
377 + status, response = self._run_gh_api(endpoint, check=False)
379 + if status == 0:
380 + self.last_result = {
381 + "status": response.get('status', 'N/A'),
382 + "commit": response.get('commit', 'N/A'),
383 + "created_at": response.get('created_at'),
384 + "error": response.get('error', {})
386 + if self.json_output:
387 + print(format_json(self.last_result))
388 + else:
389 + print("\nLatest build:")
390 + print(f" Status: {response.get('status', 'N/A')}")
391 + print(f" Commit: {response.get('commit', 'N/A')}")
392 + if 'created_at' in response:
393 + print(f" Created: {response['created_at']}")
394 + if 'error' in response and response['error'].get('message'):
395 + print(f" Error: {response['error']['message']}")
397 + return response
400 +def create_workflow_file(output_path: Optional[str] = None, force: bool = False) -> Dict:
401 + """
402 + Create a GitHub Actions workflow file for Pages deployment.
404 + Args:
405 + output_path: Optional custom output path (default: .github/workflows/pages.yml)
406 + force: Overwrite existing file without prompting
408 + Returns:
409 + Result dictionary
410 + """
411 + if output_path is None:
412 + output_path = '.github/workflows/pages.yml'
414 + workflow_file = Path(output_path)
416 + if workflow_file.exists() and not force:
417 + result = {
418 + "status": "skipped",
419 + "reason": "file_exists",
420 + "path": str(workflow_file.absolute())
422 + print(format_json(result))
423 + return result
425 + workflow_content = """name: Deploy to GitHub Pages
427 +on:
428 + push:
429 + branches: ["main"]
430 + workflow_dispatch:
432 +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
433 +permissions:
434 + contents: read
435 + pages: write
436 + id-token: write
438 +# Allow only one concurrent deployment
439 +concurrency:
440 + group: "pages"
441 + cancel-in-progress: false
443 +jobs:
444 + # Build job
445 + build:
446 + runs-on: ubuntu-latest
447 + steps:
448 + - name: Checkout
449 + uses: actions/checkout@v4
451 + - name: Setup Pages
452 + uses: actions/configure-pages@v5
454 + - name: Build site
455 + run: |
456 + # Add your build commands here
457 + # Example: npm install && npm run build
458 + # For static sites, you can skip this step
460 + # Create output directory
461 + mkdir -p _site
463 + # Copy your built files to _site/
464 + # Example: cp -r dist/* _site/
465 + # For now, copying everything as example:
466 + cp -r * _site/ 2>/dev/null || true
468 + - name: Upload artifact
469 + uses: actions/upload-pages-artifact@v3
470 + with:
471 + path: '_site'
473 + # Deployment job
474 + deploy:
475 + environment:
476 + name: github-pages
477 + url: ${{ steps.deployment.outputs.page_url }}
478 + runs-on: ubuntu-latest
479 + needs: build
480 + steps:
481 + - name: Deploy to GitHub Pages
482 + id: deployment
483 + uses: actions/deploy-pages@v4
484 +"""
486 + workflow_file.parent.mkdir(parents=True, exist_ok=True)
487 + workflow_file.write_text(workflow_content)
489 + result = {
490 + "status": "created",
491 + "path": str(workflow_file.absolute())
493 + print(format_json(result))
495 + if not Path.cwd().name == 'gh-cli':
496 + print("\nNext steps:")
497 + print("1. Customize the 'Build site' step with your build commands")
498 + print("2. Ensure the correct files are copied to _site/")
499 + print("3. Commit and push this workflow file to your repository")
500 + print("4. Enable GitHub Pages with 'GitHub Actions' as the source")
501 + return result
504 +def main():
505 + """Main entry point for the CLI."""
506 + parser = argparse.ArgumentParser(
507 + description='Automate GitHub Pages deployment using gh CLI',
508 + formatter_class=argparse.RawDescriptionHelpFormatter
511 + # Global options
512 + parser.add_argument('--dry-run', action='store_true',
513 + help='Show what would be done without making changes')
514 + parser.add_argument('--json', action='store_true',
515 + help='Output machine-readable JSON')
517 + subparsers = parser.add_subparsers(dest='command', help='Commands')
519 + # Enable command
520 + enable_parser = subparsers.add_parser('enable', help='Enable GitHub Pages')
521 + enable_parser.add_argument('repo', help='Repository in format owner/repo')
522 + enable_parser.add_argument('--branch', default='main', help='Source branch (default: main)')
523 + enable_parser.add_argument('--path', default='/', choices=['/', '/docs'], help='Source path (default: /)')
524 + enable_parser.add_argument('--build-type', default='workflow', choices=['workflow', 'legacy'],
525 + help='Build type: workflow (GitHub Actions) or legacy (Jekyll)')
526 + enable_parser.add_argument('--no-https', action='store_true', help='Disable HTTPS enforcement')
528 + # Status command
529 + status_parser = subparsers.add_parser('status', help='Check Pages status')
530 + status_parser.add_argument('repo', help='Repository in format owner/repo')
531 + status_parser.add_argument('--build-info', action='store_true', help='Show latest build information')
533 + # Rebuild command
534 + rebuild_parser = subparsers.add_parser('rebuild', help='Trigger a new build')
535 + rebuild_parser.add_argument('repo', help='Repository in format owner/repo')
537 + # Create workflow command
538 + workflow_parser = subparsers.add_parser('create-workflow', help='Create GitHub Actions workflow file')
539 + workflow_parser.add_argument('--output', help='Output path (default: .github/workflows/pages.yml)')
540 + workflow_parser.add_argument('--force', action='store_true', help='Overwrite existing file')
542 + args = parser.parse_args()
544 + if not args.command:
545 + parser.print_help()
546 + sys.exit(1)
548 + try:
549 + if args.command == 'enable':
550 + manager = GitHubPagesManager(
551 + args.repo,
552 + dry_run=args.dry_run,
553 + json_output=args.json
555 + manager.enable_pages(
556 + branch=args.branch,
557 + path=args.path,
558 + build_type=args.build_type,
559 + https_enforced=not args.no_https
562 + if args.build_type == 'workflow' and not args.json:
563 + print("\nTip: Create a deployment workflow with:")
564 + print(" gh pages create-workflow")
566 + elif args.command == 'status':
567 + manager = GitHubPagesManager(args.repo, json_output=args.json)
568 + manager.check_status()
570 + if args.build_info:
571 + manager.get_latest_build()
573 + elif args.command == 'rebuild':
574 + manager = GitHubPagesManager(args.repo, dry_run=args.dry_run, json_output=args.json)
575 + manager.trigger_rebuild()
577 + elif args.command == 'create-workflow':
578 + create_workflow_file(args.output, args.force)
580 + except KeyboardInterrupt:
581 + print("\nCancelled by user.", file=sys.stderr)
582 + sys.exit(130)
583 + except GitHubPagesError as e:
584 + result = {"status": "error", "error": str(e)}
585 + print(format_json(result))
586 + sys.exit(1)
587 + except Exception as e:
588 + result = {"status": "error", "error": str(e)}
589 + print(format_json(result))
590 + sys.exit(1)
593 +if __name__ == '__main__':
594 + main()

pi/agent/skills/jq/SKILL.md

Added
new file mode 100644
1 +---
2 +name: jq
3 +description: Process and transform JSON data from the command line. Use when extracting, filtering, mapping, or aggregating JSON. Ideal for API responses, config files, log parsing, and data pipelines.
4 +---
6 +# jq - JSON Processor
8 +## Quick Reference
10 +### Common Options
11 +| Option | Description |
12 +|--------|-------------|
13 +| `-c` | Compact output (no pretty-print) |
14 +| `-r` | Raw output (no quotes around strings) |
15 +| `-n` | Null input (use with computed values) |
16 +| `-s` | Slurp (read all into array) |
17 +| `-S` | Sort keys on output |
18 +| `-M` | Monochrome (no colors) |
19 +| `-C` | Colorize output |
20 +| `--arg name value` | Set variable `$name` to string |
21 +| `--argjson name value` | Set variable `$name` to JSON value |
23 +### Identity & Object Filters
24 +| Filter | Description |
25 +|--------|-------------|
26 +| `.` | Identity (pass through unchanged) |
27 +| `.foo` | Access key `foo` |
28 +| `.foo.bar` | Nested access |
29 +| `.[]` | Iterate array elements / object values |
30 +| `.[0]` | Array index |
31 +| `.[0:3]` | Array slice |
32 +| `keys` | Get object keys |
33 +| `length` | Get length |
34 +| `type` | Get type (string, number, object, array, boolean, null) |
36 +### Boolean & Conditional Filters
37 +| Filter | Description |
38 +|--------|-------------|
39 +| `select(expr)` | Filter by boolean expression |
40 +| `map(expr)` | Apply expression to each element |
41 +| `map_values(expr)` | Apply to each object value |
42 +| `any` / `all` | Boolean reduction |
43 +| `first` / `last` / `nth(n)` | Element extraction |
44 +| `unique` / `unique_by(expr)` | Deduplication |
45 +| `sort` / `sort_by(expr)` | Sorting |
46 +| `reverse` | Reverse order |
47 +| `group_by(expr)` | Group elements |
49 +### String & Number Filters
50 +| Filter | Description |
51 +|--------|-------------|
52 +| `split(str)` | Split string into array |
53 +| `join(str)` | Join array into string |
54 +| `ascii_downcase` / `ascii_upcase` | Case conversion |
55 +| `tostring` | Convert to string |
56 +| `tonumber` | Convert to number |
57 +| `floor` / `ceil` / `round` | Number rounding |
58 +| `infinite`, `nan`, `isfinite`, `isnan`, `isnormal` | Number tests |
60 +### Object & Array Construction
61 +| Filter | Description |
62 +|--------|-------------|
63 +| `{a, b}` | Object shorthand |
64 +| `{a: .x, b: .y}` | Object with renamed keys |
65 +| `range(n)` | Generate 0 to n-1 |
66 +| `to_entries` | Object to `[{key, value}]` |
67 +| `from_entries` | `[{key, value}]` to object |
68 +| `with_entries(expr)` | Transform object entries |
70 +### Null Handling
71 +| Filter | Description |
72 +|--------|-------------|
73 +| `//` | Alternative (default value) |
74 +| `// "default"` | With fallback |
75 +| `first`, `last`, etc. | Error on empty, use `// []` |
77 +### Pipelines
78 +```bash
79 +# Chain filters
80 +jq '.foo | .bar | .[]' file.json
82 +# Multiple outputs
83 +jq -c '.[] | {id, name}' file.json
84 +```
86 +### Variables
87 +```bash
88 +# Command-line variables
89 +jq --arg name "value" '$name' # String "value"
90 +jq --argjson count 42 '$count' # Number 42
92 +# Interpolation in filter
93 +jq --arg key "foo" '.[$key]' file.json
94 +```
96 +## Common Patterns
98 +### Extract array of values
99 +```bash
100 +jq '.[].name' data.json # Array of names
101 +jq '[.items[].price | tonumber]' data.json # Array of numbers
102 +```
104 +### Filter array
105 +```bash
106 +jq '[.items[] | select(.active == true)]' data.json
107 +jq '.items[] | select(.age > 21)' data.json
108 +```
110 +### Transform object
111 +```bash
112 +jq 'map({id, name: .title})' data.json
113 +jq 'with_entries({key: .key, value: .value * 2})' data.json
114 +```
116 +### Flatten nested
117 +```bash
118 +jq '..objects' data.json # Recursive descent
119 +jq '.. | select(type == "string")' data.json # All strings
120 +```
122 +### Aggregations
123 +```bash
124 +jq 'map(.price) | add' data.json # Sum
125 +jq 'map(.price) | add / length' data.json # Average
126 +jq 'group_by(.category)' data.json # Group
127 +jq 'unique_by(.id)' data.json # Dedupe
128 +```
130 +### Merge objects
131 +```bash
132 +jq 'add' file1.json file2.json # Merge arrays
133 +jq 'reduce .[] as $item ({}; . + $item)' # Reduce merge
134 +```
136 +### Date/Time
137 +```bash
138 +# Unix timestamp to ISO
139 +jq 'todate' file.json
141 +# Current datetime
142 +jq -n 'now'
143 +jq -n 'now | strftime("%Y-%m-%d")'
144 +```
146 +### Pretty-print vs Compact
147 +```bash
148 +jq . data.json # Pretty (default)
149 +jq -c . data.json # Compact
150 +jq -M . data.json # No color
151 +jq -C . data.json # Force color
152 +```
154 +### Input Variants
155 +```bash
156 +echo '{"a":1}' | jq '.' # Single input
157 +echo '{"a":1}' '{"b":2}' | jq -s '.' # All as array
158 +echo 'text' | jq -R '.' # Raw input as string
159 +jq -n '{time: now}' # No input, computed
160 +```
162 +### Environment & Args
163 +```bash
164 +# Named args
165 +jq --arg name "Alice" '.name = $name' data.json
167 +# Positional args
168 +jq '. * $ARGS' --argjson extra '{"x":1}' data.json
170 +# JSON args
171 +jq --argjson cfg '{"debug": true}' '$cfg' data.json
172 +```
174 +## Troubleshooting
176 +### Empty output
177 +- Check: `jq 'has("field")' data.json`
178 +- Use `//` for default: `jq '.missing // "N/A"'`
180 +### Type errors
181 +- Use `tonumber`, `tostring` for conversion
182 +- Check with `jq 'type'`
184 +### null vs empty
185 +- `null` is a value; empty filter produces nothing
186 +- `first` errors on empty; use `first // "default"`
188 +### Performance
189 +```bash
190 +# Stop at first match
191 +jq 'first | select(.id == "123")' data.json
193 +# Stream processing for large files
194 +jq --stream '.path' large.json
196 +# Compact for large outputs
197 +jq -c '.' large.json > output.json
198 +```
200 +## Resources
201 +- [jqlang.org](https://jqlang.org/)
202 +- [jq play](https://jqplay.org/) - Interactive playground
203 +- `man jq` for full manual

pi/agent/skills/justfile/SKILL.md

Added
new file mode 100644
1 +---
2 +name: justfile
3 +description: Just is a command runner / task manager. Use when creating build scripts, project automation, running multiple commands, or managing development workflows. Creates recipes in a justfile.
4 +---
6 +# Just - Command Runner
8 +## Quick Reference
10 +### Common Commands
11 +| Command | Description |
12 +|---------|-------------|
13 +| `just` | Run first recipe |
14 +| `just -l` | List all recipes |
15 +| `just recipe` | Run specific recipe |
16 +| `just -n` | Dry-run (show what would run) |
17 +| `just --check` | Check formatting |
18 +| `just --fmt` | Format justfile |
19 +| `just -c "cmd"` | Run arbitrary command with env |
20 +| `just --choose` | Interactive recipe selection |
21 +| `just -e` | Edit justfile with $EDITOR |
22 +| `just --evaluate` | Print all variables |
24 +### Common Options
25 +| Option | Description |
26 +|--------|-------------|
27 +| `-n`, `--dry-run` | Print without executing |
28 +| `-q`, `--quiet` | Suppress output |
29 +| `--set VAR VAL` | Override variable |
30 +| `-f FILE` | Use specific justfile |
31 +| `-g` | Use global justfile |
32 +| `--color <WHEN>` | Color output (always/auto/never) |
33 +| `--time` | Print execution time |
34 +| `-v` | Verbose output |
36 +## Justfile Syntax
38 +### Basic Recipe
39 +```justfile
40 +recipe-name:
41 + command arg1 arg2
42 + another command
43 +```
45 +### Recipe with Arguments
46 +```justfile
47 +hello target:
48 + echo "Hello, {{target}}!"
49 +```
51 +### Recipe with Dependencies
52 +```justfile
53 +build: deps test
54 + cargo build --release
55 +```
57 +### Private Recipe (hidden)
58 +```justfile
59 +_helper:
60 + internal command
62 +public: _helper
63 + echo "done"
64 +```
66 +### Recipe Groups
67 +```justfile
68 +[group('build')]
69 +build:
70 + cargo build
72 +[group('test')]
73 +test:
74 + cargo test
76 +[group('deploy')]
77 +deploy:
78 + ./deploy.sh
79 +```
81 +## Variables
83 +```justfile
84 +# String variable
85 +name := "project"
86 +port := "8080"
88 +# Command interpolation
89 +timestamp := `date +%s`
90 +git_branch := `git branch --show-current`
92 +# Set from environment
93 +HOME_DIR := env("HOME")
94 +OPTIONAL := env_or_default("MY_VAR", "fallback")
96 +# Use variables
97 +print-vars:
98 + echo "Project: {{name}}"
99 + echo "Port: {{port}}"
100 +```
102 +## Common Patterns
104 +### Watch & Restart
105 +```justfile
106 +dev:
107 + cargo run
109 +dev-hot:
110 + cargo watch -x run
111 +```
113 +### Docker Commands
114 +```justfile
115 +dc := "docker compose"
117 +up:
118 + {{dc}} up -d
120 +down:
121 + {{dc}} down
123 +logs:
124 + {{dc}} logs -f
126 +build:
127 + {{dc}} build --no-cache
128 +```
130 +### Git Workflow
131 +```justfile
132 +status:
133 + git status
135 +push:
136 + git push origin `git branch --show-current`
138 +clean-branches:
139 + git branch --merged | grep -v main | xargs git branch -d
140 +```
142 +### Multiple Targets
143 +```justfile
144 +# Run: just clean-all prod dev
145 +clean-all target +targets:
146 + rm -rf {{target}} {{targets}}
147 +```
149 +### Conditional Execution
150 +```justfile
151 +install:
152 + #!/bin/bash
153 + if command -v brew &> /dev/null; then
154 + brew install {{package}}
155 + else
156 + apt install {{package}}
157 + fi
158 +```
160 +### Setting Environment
161 +```justfile
162 +export RUST_BACKTRACE := "1"
163 +export CARGO_TERM_COLOR := "always"
165 +run:
166 + cargo run
167 +```
169 +### Load .env
170 +```justfile
171 +set dotenv-load
173 +database_url := env("DATABASE_URL")
175 +migrate:
176 + diesel migration run
177 +```
179 +## Aliases
181 +```justfile
182 +alias t := test
183 +alias b := build
184 +alias l := lint
186 +test:
187 + cargo test
189 +build:
190 + cargo build
192 +lint:
193 + cargo clippy
194 +```
196 +## Settings
198 +```justfile
199 +# Don't print commands before running
200 +set quiet
202 +# Windows-compatible paths
203 +set windows-path
205 +# Enable unstable features
206 +set unstable
208 +# Dotenv loading
209 +set dotenv-load
211 +# Shell for recipe lines
212 +set shell := ["bash", "-c"]
214 +# Silent by default
215 +set silent
216 +```
218 +## Shebang Recipes
220 +```justfile
221 +# Runs in /bin/sh, not bash
222 +python-script:
223 + #!/usr/bin/env python3
224 + print("Hello from Python!")
226 +# Explicit shell
227 +bash-script:
228 + #!/bin/bash
229 + set -euo pipefail
230 + echo "Hello from bash!"
231 +```
233 +## Modules (include other justfiles)
235 +```justfile
236 +mod path/to/justfile
238 +build: path/to/justfile.build
239 + echo "main build"
240 +```
242 +## Common Recipes
244 +### Development Server
245 +```justfile
246 +dev:
247 + npm run dev
249 +dev-backend:
250 + cargo run
252 +dev-frontend:
253 + npm run dev
254 +```
256 +### Testing
257 +```justfile
258 +test:
259 + cargo test
261 +test-all: test-integrations test-unit
263 +test-unit:
264 + cargo test --lib
266 +test-integrations:
267 + cargo test --test '*'
269 +coverage:
270 + cargo tarpaulin --output-dir coverage
271 +```
273 +### Build & Release
274 +```justfile
275 +version := `git describe --tags`
277 +build:
278 + cargo build --release
280 +package: build
281 + mkdir -p dist
282 + cp target/release/{{project_name}} dist/
283 + tar -czf dist/{{project_name}}-{{version}}.tar.gz dist
285 +publish: package
286 + gh release create v{{version}} dist/*
287 +```
289 +### Database
290 +```justfile
291 +migrate:
292 + diesel migration run
294 +rollback:
295 + diesel migration revert
297 +reset: rollback migrate seed
299 +seed:
300 + psql $DATABASE_URL < seeds.sql
301 +```
303 +### Container
304 +```justfile
305 +docker-build:
306 + docker build -t myapp:{{version}} .
308 +docker-run:
309 + docker run -p 8080:8080 myapp:{{version}}
311 +docker-push:
312 + docker push myapp:{{version}}
313 +```
315 +## Checking & Formatting
317 +```bash
318 +# Check formatting
319 +just --check
321 +# Format justfile
322 +just --fmt
324 +# List recipes with groups
325 +just --list --groups
326 +```
328 +## Common Mistakes
330 +### Forgetting Indentation
331 +```justfile
332 +# WRONG - must use spaces (4 by default)
333 +recipe:
334 +command1
335 + command2
337 +# CORRECT
338 +recipe:
339 + command1
340 + command2
341 +```
343 +### String vs Literal
344 +```justfile
345 +# Variables need {{}}
346 +path := "/tmp/file"
347 +copy:
348 + cp {{path}} /dest
350 +# Raw strings for special chars
351 +path := `echo "/tmp/file with 'quotes'"`
352 +```
354 +### Dependencies Run Even on Failure
355 +```justfile
356 +# Use private recipes if deps should be conditional
357 +task: _conditional
358 + echo "main"
360 +_conditional:
361 + #!/bin/bash
362 + condition && do-something || true
363 +```
365 +## Best Practices
367 +1. **Use aliases** for frequent commands
368 +2. **Group related recipes** with `[group()]`
369 +3. **Export env vars** at top for visibility
370 +4. **Document recipes** with doc comments
371 +5. **Use `set quiet`** for cleaner output on success
372 +6. **Include version** for reproducibility
373 +7. **Use shebang** for complex scripts requiring error handling
375 +## Resources
376 +- [github.com/casey/just](https://github.com/casey/just)
377 +- `just --completions bash` for shell completions
378 +- `man just` for full manual

pi/agent/skills/mdbook/SKILL.md

Added
new file mode 100644
1 +---
2 +name: mdbook
3 +description: Build documentation books with mdbook — SUMMARY.md structure, chapter organization, themes, search, preprocessors, static HTML generation, GitHub Pages deployment.
4 +license: MIT
5 +---
7 +# mdbook Skill
9 +mdbook is a Rust tool for creating modern books from Markdown files. It's used
10 +extensively in the Rust ecosystem (The Rust Book, Rust by Example) and is
11 +excellent for technical documentation.
13 +## Quick Reference: CLI Commands
15 +| Command | Description |
16 +| ------------------- | --------------------------------------- |
17 +| `mdbook init <dir>` | Initialize new book in directory |
18 +| `mdbook build` | Build the book (outputs to `book/` dir) |
19 +| `mdbook serve` | Serve book locally with live reload |
20 +| `mdbook watch` | Watch for changes and rebuild |
21 +| `mdbook test` | Run tests in Rust code blocks |
22 +| `mdbook clean` | Remove built book directory |
23 +| `mdbook dump-ast` | Print AST of markdown files |
25 +### Common Flags
27 +| Flag | Description |
28 +| ---------------- | ----------------------------------- |
29 +| `-d, --dest-dir` | Output directory (default: `book/`) |
30 +| `-o, --open` | Open browser after serving |
31 +| `-p, --port` | Port for serve (default: 3000) |
32 +| `-l, --language` | Language for search |
34 +---
36 +## 1. Quick Start
38 +### Installation
40 +```bash
41 +# Via cargo (recommended)
42 +cargo install mdbook
44 +# Via package managers
45 +# macOS
46 +brew install mdbook
48 +# Arch Linux
49 +pacman -S mdbook
51 +# Debian/Ubuntu
52 +apt install mdbook
54 +# Windows (via cargo or releases)
55 +cargo install mdbook
56 +```
58 +### Initialize a New Book
60 +```bash
61 +# Create new book in my-book directory
62 +mdbook init my-book
64 +# With custom theme (creates theme/ directory)
65 +mdbook init --theme my-book
67 +# With ignore file
68 +mdbook init --ignore my-book
69 +```
71 +This creates:
73 +```
74 +my-book/
75 +├── book.toml # Book configuration
76 +├── src/
77 +│ └── SUMMARY.md # Chapter list
78 +└── theme/
79 + ├── index.js # Custom JavaScript
80 + ├── index.css # Custom styles
81 + └── book.js # Theme JavaScript
82 +```
84 +### Development Server
86 +```bash
87 +# Serve with live reload (default port 3000)
88 +mdbook serve
90 +# Open in browser automatically
91 +mdbook serve --open
93 +# Custom port
94 +mdbook serve -p 8080
96 +# Watch only (no server, just rebuild on changes)
97 +mdbook watch
98 +```
100 +### Build for Production
102 +```bash
103 +# Build to book/ directory
104 +mdbook build
106 +# Custom output directory
107 +mdbook build -d dist
108 +```
110 +---
112 +## 2. Book Structure
114 +### Directory Layout
116 +```
117 +book/
118 +├── book.toml # Configuration
119 +├── src/
120 +│ ├── SUMMARY.md # Required: chapter order
121 +│ ├── chapter1.md
122 +│ ├── chapter2.md
123 +│ └── images/ # Local images
124 +├── theme/ # Optional custom theme
125 +│ ├── index.css
126 +│ ├── index.js
127 +│ ├── book.js
128 +│ └── fonts/
129 +└── book/ # Output directory
130 + └── index.html
131 +```
133 +### book.toml Configuration
135 +```toml
136 +[book]
137 +title = "My Book Title"
138 +authors = ["Author Name"]
139 +description = "Book description"
140 +src = "src"
141 +language = "en"
143 +[build]
144 +build-dir = "book"
145 +create-missing = true
147 +[output.html]
148 +additional-css = ["custom.css"]
149 +additional-js = ["custom.js"]
150 +google-analytics = "UA-XXXXX"
151 +```
153 +### SUMMARY.md Format
155 +The SUMMARY.md defines chapter order and structure:
157 +```markdown
158 +# Summary
160 +[Introduction](./intro.md)
162 +- [Getting Started](./getting-started.md)
163 + - [Installation](./getting-started/installation.md)
164 + - [Configuration](./getting-started/config.md)
166 +- [Chapter 1](./chapter1.md)
167 + - [Section 1.1](./chapter1/section1.md)
169 +[Appendix](./appendix.md)
171 +[Conclusion](./conclusion.md)
172 +```
174 +**Rules:**
176 +- Must start with `# Summary` header
177 +- Links are relative to `src/` directory
178 +- Indented items become subsections
179 +- First link is often the intro (no requirement)
180 +- Use `[Title](./path.md)` format
182 +### Front Matter (Optional)
184 +Add metadata at the top of markdown files:
186 +```markdown
187 +---
188 +title: Chapter Title
189 +description: Chapter description for SEO
190 +license: MIT
191 +---
193 +# Chapter Title
195 +Content starts here...
196 +```
198 +---
200 +## 3. Markdown Features
202 +mdbook supports standard Markdown plus extensions:
204 +### Admonitions (Note Blocks)
206 +```markdown
207 +> **Note**: This is a note.
209 +> **Warning**: Be careful with this!
211 +> **Tip**: Here's a helpful tip.
213 +> **Danger**: Warning message.
214 +```
216 +Renders as styled boxes. Types: note, warning, tip, danger, info.
218 +### Task Lists
220 +```markdown
221 +- [ ] Unchecked task
222 +- [x] Completed task
223 +```
225 +### Tables
227 +```markdown
228 +| Header 1 | Header 2 | Header 3 |
229 +| -------- | -------- | -------- |
230 +| Cell 1 | Cell 2 | Cell 3 |
231 +| Cell 4 | Cell 5 | Cell 6 |
232 +```
234 +### Footnotes
236 +```markdown
237 +Here is a footnote[^1].
239 +[^1]: Here is the footnote content.
240 +```
242 +### Smart Punctuation
244 +Automatic conversion:
246 +- `...` → `…` (ellipsis)
247 +- `--` → `–` (en dash)
248 +- `---` → `—` (em dash)
249 +- `"quote"` → "curly quotes"
251 +### Code Blocks with Syntax Highlighting
253 +````markdown
254 +```rust
255 +fn main() {
256 + println!("Hello, world!");
258 +```
259 +````
261 +Supported languages: rust, python, javascript, typescript, go, java, c, cpp,
262 +bash, json, yaml, toml, sql, html, css, and many more.
264 +### Heading Anchors
266 +Headings automatically get anchors for linking:
268 +```markdown
269 +## My Heading {#custom-id}
270 +```
272 +### Links
274 +```markdown
275 +[Internal link](./chapter.md) [External link](https://example.com)
276 +[Link with title](./chapter.md "Title")
277 +```
279 +---
281 +## 4. Configuration (book.toml)
283 +### Essential Options
285 +```toml
286 +[book]
287 +title = "Book Title"
288 +authors = ["Author <email@example.com>"]
289 +description = "Description for search engines"
290 +src = "src"
291 +language = "en"
293 +[build]
294 +build-dir = "book"
295 +create-missing = true # Auto-create missing SUMMARY.md entries
296 +```
298 +### HTML Output Options
300 +```toml
301 +[output.html]
302 +# Custom CSS/JS
303 +additional-css = ["custom.css"]
304 +additional-js = ["custom.js"]
306 +# Theme options
307 +theme = "theme/" # Custom theme directory
308 +theme-rtl = "theme-rtl/" # RTL theme
310 +# Search
311 +search.enable = true
312 +search.separator = "\\s+"
313 +search.preload = ["en"]
315 +# GitHub editing
316 +edit-url-base = "https://github.com/user/repo/edit/main/src"
318 +# Navigation
319 +disable-children-links = false
320 +footnote-section = "Footnotes"
322 +# Analytics
323 +google-analytics = "UA-XXXXX"
325 +# Static files
326 +static-files = ["images/"]
328 +# Custom favicon
329 +favicon-path = "favicon.png"
331 +# Copy fonts
332 +copy-fonts = true
334 +[output.html.index-route] # Custom home page
335 +index = "intro.md"
337 +[output.html.redirect] # URL redirects
338 +"/old-page" = "/new-page"
339 +```
341 +### Table of Contents
343 +```toml
344 +[output.html.toc]
345 +# Levels shown in table of contents
346 +included-level = 3
347 +```
349 +### Playground (Interactive Code)
351 +```toml
352 +[output.html.playground]
353 +editable = true # Allow editing
354 +copyable = true # Show copy button
355 +line-numbers = false # Show line numbers
356 +```
358 +---
360 +## 5. CLI Commands Detail
362 +### mdbook build
364 +```bash
365 +# Build with custom config
366 +mdbook build --config book.toml
368 +# Build specific directory
369 +mdbook build ./my-book
371 +# Verbose output
372 +mdbook build -v
373 +```
375 +### mdbook serve
377 +```bash
378 +# Basic serve
379 +mdbook serve
381 +# Custom host/port
382 +mdbook serve -p 3000 -h 127.0.0.1
384 +# Open browser
385 +mdbook serve -o
387 +# Don't open (useful in containers)
388 +mdbook serve --no-open
390 +# Live reload port (websocket)
391 +mdbook serve --livereload 3001
392 +```
394 +### mdbook watch
396 +```bash
397 +# Watch for changes
398 +mdbook watch
400 +# With custom config
401 +mdbook watch --config book.toml
403 +# Watch specific dir
404 +mdbook watch ./docs
405 +```
407 +### mdbook test
409 +Tests Rust code examples in code blocks. See Section 6.
411 +### mdbook clean
413 +```bash
414 +# Clean build directory
415 +mdbook clean
417 +# Clean specific dir
418 +mdbook clean ./my-book
419 +```
421 +---
423 +## 6. Testing Code (mdbook test)
425 +mdbook can test Rust code examples in your book.
427 +### Basic Usage
429 +```bash
430 +mdbook test
431 +```
433 +This finds all `rust` code blocks and runs them as tests.
435 +### Ignored Code
437 +````markdown
438 +```rust,ignore
439 +// This won't be tested
440 +let x = unimplemented!();
441 +```
442 +````
444 +````
445 +### No-Run Code
447 +```markdown
448 +```rust,no_run
449 +// Compiles but doesn't run
450 +// Useful for code that won't compile in tests
451 +````
453 +````
454 +### Should Panic
456 +```markdown
457 +```rust,should_panic
458 +#[should_panic]
459 +fn test_panic() {
460 + panic!("This test passes if it panics");
462 +````
464 +````
465 +### Hidden Code
467 +```markdown
468 +```rust,hidden
469 +// Not displayed in book but included in tests
470 +use crate::helper;
471 +````
473 +````
474 +### Multiple Attributes
476 +```markdown
477 +```rust,ignore,no_run
478 +// Ignored and not run
479 +````
481 +````
482 +### Dependencies
484 +```toml
485 +[output.html.playground]
486 +rust-replacements = [
487 + "fn main() => || {", main() for snippets # Replace fn
489 +````
491 +---
493 +## 7. Preprocessors
495 +Preprocessors extend mdbook functionality. Install via cargo, enable in
496 +book.toml.
498 +### mdbook-mermaid (Diagrams)
500 +```bash
501 +cargo install mdbook-mermaid
502 +```
504 +```toml
505 +[preprocessor.mermaid]
506 +renderers = ["html"]
507 +```
509 +````markdown
510 +```mermaid
511 +graph TD
512 + A[Start] --> B{Decision}
513 + B -->|Yes| C[Do Something]
514 + B -->|No| D[Do Something Else]
515 +```
516 +````
518 +````
519 +### mdbook-admonish (Enhanced Admonitions)
521 +```bash
522 +cargo install mdbook-admonish
523 +````
525 +```toml
526 +[preprocessor.admonish]
527 +renderers = ["html"]
528 +```
530 +```markdown
531 +:::note This is a note. :::
533 +:::tip[Custom Title] This is a tip with custom title. :::
535 +:::warning This is a warning. :::
537 +:::danger This is a danger box. :::
538 +```
540 +### mdbook-katex (Math)
542 +```bash
543 +cargo install mdbook-katex
544 +```
546 +```toml
547 +[preprocessor.katex]
548 +renderers = ["html"]
550 +[katex]
551 +# Optional: custom KaTeX options
552 +```
554 +```markdown
555 +Inline math: $E = mc^2$
557 +Block math: $$
558 +\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}
560 +```
562 +### mdbook-toc (Table of Contents)
564 +```bash
565 +cargo install mdbook-toc
566 +```
568 +```toml
569 +[preprocessor.toc]
570 +renderers = ["html"]
571 +```
573 +Adds inline TOC to chapters.
575 +### mdbook-d2 (D2 Diagrams)
577 +```bash
578 +cargo install mdbook-d2
579 +```
581 +```toml
582 +[preprocessor.d2]
583 +renderers = ["html"]
584 +```
586 +````markdown
587 +```d2
588 +shape: schema
589 +books: {
590 + shape: sql_table
591 + columns: {
592 + id: int
593 + title: string
594 + author_id: int
597 +authors: {
598 + shape: sql_table
599 + columns: {
600 + id: int
601 + name: string
604 +books.author_id -> authors.id
605 +```
606 +````
608 +````
609 +### mdbook-plantuml
611 +```bash
612 +cargo install mdbook-plantuml
613 +````
615 +```toml
616 +[preprocessor.plantuml]
617 +plantuml = "plantuml" # Or path to plantuml jar
618 +```
620 +### All Preprocessors
622 +```bash
623 +# Install all common ones
624 +cargo install mdbook-mermaid mdbook-admonish mdbook-katex mdbook-d2 mdbook-toc mdbook-linkcheck
625 +```
627 +---
629 +## 8. Theming
631 +### Custom CSS
633 +Create `theme/index.css`:
635 +```css
636 +/* Override theme colors */
637 +:root {
638 + --bg: #ffffff;
639 + --fg: #333333;
640 + --sidebar-bg: #f5f5f5;
641 + --theme-anchors: #0066cc;
644 +/* Custom page styling */
645 +.page {
646 + font-family: "Inter", system-ui, sans-serif;
649 +/* Code blocks */
650 +.highlight {
651 + border-radius: 8px;
653 +```
655 +### Custom JavaScript
657 +Create `theme/index.js`:
659 +```javascript
660 +// Custom JavaScript for interactivity
661 +document.addEventListener("DOMContentLoaded", () => {
662 + // Add custom functionality
663 + console.log("Book loaded!");
664 +});
665 +```
667 +### Override Theme Files
669 +```
670 +theme/
671 +├── index.css # Your CSS overrides
672 +├── index.js # Your JS
673 +├── book.js # Override default book.js
674 +├── head.hbs # Custom HTML head content
675 +├── header.hbs # Custom header
676 +└── footer.hbs # Custom footer
677 +```
679 +### fonts
681 +```css
682 +@font-face {
683 + font-family: "Custom Font";
684 + src: url("fonts/custom.woff2") format("woff2");
686 +```
688 +---
690 +## 9. Diagrams
692 +### Mermaid Diagrams
694 +Install mdbook-mermaid, then:
696 +````markdown
697 +```mermaid
698 +sequenceDiagram
699 + participant A as Alice
700 + participant B as Bob
701 + A->>B: Hello Bob!
702 + B-->>A: Hi Alice!
703 +```
704 +````
706 +````
707 +Supported diagram types:
708 +- Flowcharts (graph, flowchart)
709 +- Sequence diagrams
710 +- Class diagrams
711 +- State diagrams
712 +- ER diagrams
713 +- Gantt charts
714 +- Pie charts
716 +### D2 Diagrams
718 +Install mdbook-d2 for modern diagrams:
720 +```markdown
721 +```d2
722 +input: shape circle
723 +output: shape circle
724 +input -> output: data flow
725 +````
727 +````
728 +### PlantUML
730 +Install mdbook-plantuml:
732 +```markdown
733 +@startuml
734 +Alice -> Bob: Hello
735 +Bob --> Alice: Hi!
736 +@enduml
737 +````
739 +### Images
741 +```markdown
742 +![Alt text](images/diagram.png)
744 +<!-- With size -->
745 +<img src="images/diagram.png" width="500" />
746 +```
748 +---
750 +## 10. Deployment
752 +### GitHub Pages (Recommended)
754 +Create `.github/workflows/deploy.yml`:
756 +```yaml
757 +name: Deploy Book
759 +on:
760 + push:
761 + branches: [main]
763 +permissions:
764 + contents: write
766 +jobs:
767 + deploy:
768 + runs-on: ubuntu-latest
769 + steps:
770 + - uses: actions/checkout@v4
772 + - name: Install mdbook
773 + uses: rust-lang/actions/setup@v2
774 + with:
775 + toolchain: stable
776 + - run: cargo install mdbook
778 + - name: Build book
779 + run: mdbook build
781 + - name: Deploy
782 + uses: peaceiris/actions-gh-pages@v3
783 + with:
784 + github_token: ${{ secrets.GITHUB_TOKEN }}
785 + publish_dir: ./book
786 +```
788 +Enable GitHub Pages in repo settings → Pages → Source: "Deploy from a branch" →
789 +branch: gh-pages
791 +### Netlify
793 +Create `netlify.toml`:
795 +```toml
796 +[build]
797 + command = "mdbook build"
798 + publish = "book"
800 +[build.environment]
801 + MDBOOK_VERSION = "latest"
802 +```
804 +### Vercel
806 +Create `vercel.json`:
808 +```json
810 + "buildCommand": "mdbook build",
811 + "outputDirectory": "book",
812 + "installCommand": "cargo install mdbook"
814 +```
816 +### Docker
818 +```dockerfile
819 +FROM rust:latest as builder
820 +RUN cargo install mdbook
821 +COPY . /app
822 +WORKDIR /app
823 +RUN mdbook build
825 +FROM nginx:alpine
826 +COPY --from=builder /app/book /usr/share/nginx/html
827 +EXPOSE 80
828 +```
830 +---
832 +## 11. Best Practices
834 +### Directory Structure for Large Books
836 +```
837 +src/
838 +├── SUMMARY.md
839 +├── part1/
840 +│ ├── SUMMARY.md
841 +│ ├── chapter1.md
842 +│ └── chapter2.md
843 +├── part2/
844 +│ ├── SUMMARY.md
845 +│ ├── chapter3.md
846 +│ └── chapter4.md
847 +├── reference/
848 +│ ├── SUMMARY.md
849 +│ └── api.md
850 +└── assets/
851 + ├── images/
852 + └── diagrams/
853 +```
855 +Each part has its own SUMMARY.md for modularity.
857 +### Versioning
859 +```toml
860 +[output.html]
861 +# Add version selector
862 +git-repository-url = "https://github.com/user/repo"
863 +git-repository-branch = "main"
864 +```
866 +### Search Optimization
868 +```toml
869 +[output.html.search]
870 +preload = ["en", "de"] # Languages to preload
871 +```
873 +### Performance Tips
875 +1. **Lazy load images**: Use proper image formats (WebP)
876 +2. **Minimize custom JS**: Each script slows loading
877 +3. **Use preprocessors sparingly**: Each adds build time
878 +4. **Enable cache headers**: Configure in deployment
880 +### Common Issues
882 +| Issue | Solution |
883 +| ------------------ | -------------------------------------- |
884 +| Images not showing | Use relative paths from src/ |
885 +| Code not tested | Add `rust` language tag to code blocks |
886 +| Build fails | Check SUMMARY.md for broken links |
887 +| Search not working | Verify language is set correctly |
889 +---
891 +## 12. Useful Tips & Tricks
893 +### Auto-generate SUMMARY from files
895 +```bash
896 +# Use a script to generate SUMMARY.md
897 +ls -1 src/**/*.md | sed 's|^src/| - |' | sed 's|\.md$||'
898 +```
900 +### Preview while editing
902 +```bash
903 +mdbook watch -p 3000 -o &
904 +# Opens browser, rebuilds on file changes
905 +```
907 +### Check links
909 +Install mdbook-linkcheck:
911 +```bash
912 +cargo install mdbook-linkcheck
913 +```
915 +```toml
916 +[preprocessor.linkcheck]
917 +```
919 +### Multi-language books
921 +```toml
922 +[book]
923 +title = "My Book"
925 +[output.html.print]
926 +enable = true # Generate print-friendly version
927 +```
929 +### PDF Export
931 +Use browser print to PDF, or:
933 +```bash
934 +mdbook build
935 +# Then use tools likewkhtmltopdf
936 +```
938 +---
940 +## Related Skills
942 +- **rust**: For writing Rust code examples in your book
943 +- **documentation**: For writing effective documentation
944 +- **cli-design**: For creating CLI tools that use mdbook output
946 +(End of file)

pi/agent/skills/niri/SKILL.md

Added
new file mode 100644
1 +---
2 +name: niri
3 +description: "Edit niri Wayland compositor config in KDL — input, keyboard, touchpad, outputs, key bindings, window rules, layout, animations, gestures, VRR, Xwayland, and niri msg IPC commands. Use when: editing ~/.config/niri/config.kdl, configuring niri, mentioned niri-WM, or niri window manager."
4 +license: MIT
5 +---
7 +# niri — Wayland compositor config editor
9 +niri is a scrollable tiling Wayland compositor configured via KDL at
10 +`~/.config/niri/config.kdl`.
12 +## Config file basics
14 +- **Location**: `~/.config/niri/config.kdl`
15 +- **Syntax**: [KDL](https://kdl.dev/) — similar to TOML but with slashes
16 +- **Live-reload**: Save and changes apply immediately
17 +- **Validation**: Run `niri validate` to check for errors before restarting
18 +- **Default config**: If no config exists, niri creates one from the embedded
19 + default at build time
20 +- **Include files**: Use `include "file.kdl"` to split config across files
21 + (`since 25.11`)
23 +## Config sections quick reference
25 +| Section | Controls | Docs |
26 +| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
27 +| `input {}` | Keyboard layout, repeat, numlock; touchpad/mouse/trackpoint/trackball/tablet/touch settings; focus-follows-mouse, mod-key | [Input](https://niri-wm.github.io/niri/Configuration%3A-Input.html) |
28 +| `output "name" {}` | Per-monitor: mode, scale, transform, position, VRR, background, hot-corners, layout overrides | [Outputs](https://niri-wm.github.io/niri/Configuration%3A-Outputs.html) |
29 +| `binds {}` | Key bindings, scroll bindings, mouse click bindings | [Key Bindings](https://niri-wm.github.io/niri/Configuration%3A-Key-Bindings.html) |
30 +| `switch-events {}` | Lid open/close, tablet mode switch bindings | [Switch Events](https://niri-wm.github.io/niri/Configuration%3A-Switch-Events.html) |
31 +| `layout {}` | Gaps, column widths, focus ring, border, shadow, tab-indicator, struts, background | [Layout](https://niri-wm.github.io/niri/Configuration%3A-Layout.html) |
32 +| `workspace "name" {}` | Named workspaces (always exist, can bind to outputs) | [Named Workspaces](https://niri-wm.github.io/niri/Configuration%3A-Named-Workspaces.html) |
33 +| `window-rule {}` | Per-window matching and properties (opacity, floating, size, VRR, etc.) | [Window Rules](https://niri-wm.github.io/niri/Configuration%3A-Window-Rules.html) |
34 +| `layer-rule {}` | Per-layer-shell-surface matching and properties (opacity, shadow, radius) | [Layer Rules](https://niri-wm.github.io/niri/Configuration%3A-Layer-Rules.html) |
35 +| `animations {}` | Animation curves/duration for workspace-switch, window-open/close, resize, overview | [Animations](https://niri-wm.github.io/niri/Configuration%3A-Animations.html) |
36 +| `gestures {}` | DnD edge scroll, workspace switch, hot-corners | [Gestures](https://niri-wm.github.io/niri/Configuration%3A-Gestures.html) |
37 +| `recent-windows {}` | Alt-Tab switcher: debounce, highlights, previews, binds | [Recent Windows](https://niri-wm.github.io/niri/Configuration%3A-Recent-Windows.html) |
38 +| `debug {}` | Debug flags, DRM device override, tracing | [Debug Options](https://niri-wm.github.io/niri/Configuration%3A-Debug-Options.html) |
39 +| Top-level flags | `spawn-at-startup`, `prefer-no-csd`, `screenshot-path`, `cursor`, `overview`, `xwayland-satellite`, `clipboard`, `hotkey-overlay`, `config-notification` | [Miscellaneous](https://niri-wm.github.io/niri/Configuration%3A-Miscellaneous.html) |
41 +## KDL syntax basics
43 +```kdl
44 +// Single-line comment
45 +/- multi-line comment (comments out entire section) -/
47 +// Flags (enable by writing, disable by commenting out)
48 +input {
49 + focus-follows-mouse
50 + // warp-mouse-to-focus // disabled
53 +// Sections (most can only appear once)
54 +input {
55 + keyboard {
56 + xkb {
57 + layout "us"
58 + variant "colemak_dh_ortho"
59 + options "compose:ralt,ctrl:nocaps"
60 + }
61 + repeat-delay 600
62 + repeat-rate 25
63 + numlock
64 + }
65 + touchpad {
66 + tap
67 + natural-scroll
68 + accel-speed 0.2
69 + }
72 +// Repeating sections (by device/output name)
73 +output "eDP-1" {
74 + scale 2.0
75 + mode "1920x1080@120.030"
77 +output "HDMI-A-1" {
78 + mode "2560x1440@143.912"
81 +// Colors
82 +focus-ring {
83 + active-color "#7fc8ff"
84 + inactive-color "#505050"
85 + urgent-color "#9b0000"
86 + active-gradient from="#80c8ff" to="#bbddff" angle=45
89 +// Proportions vs fixed
90 +preset-column-widths {
91 + proportion 0.33333
92 + proportion 0.5
93 + fixed 1280
95 +default-column-width { proportion 0.5; }
97 +// Regex strings
98 +window-rule {
99 + match app-id=r#"^org\.telegram\.desktop$"#
100 + match title="^Picture-in-Picture$"
102 +```
104 +## Important rules
106 +1. **`binds {}` has NO defaults** — if you include it, you must provide all
107 + bindings you need. Copy from the default config first.
108 +2. **Most sections cannot repeat** — only `output "name" {}`,
109 + `workspace "name" {}`, `window-rule {}`, and `layer-rule {}` can repeat.
110 +3. **Window rules are ordered** — earlier rules match first and override later
111 + ones.
112 +4. **Most settings merge** — when included files set partial sections, only
113 + those properties change; other properties keep their values.
114 +5. **`struts` is non-merging** — writing `struts {}` in an included file
115 + completely replaces (doesn't merge with) a prior `struts {}`.
117 +## Common patterns
119 +### Change keybindings
121 +```kdl
122 +binds {
123 + // Mod is Super on TTY, Alt in nested/winit mode
124 + Mod+T { spawn "alacritty"; }
125 + Mod+D { spawn "fuzzel"; }
126 + Mod+Shift+E { quit; }
127 + Mod+Q { close-window; }
128 + Mod+Left { focus-column-left; }
129 + Mod+Right { focus-column-right; }
130 + Mod+J { focus-window-down; }
131 + Mod+K { focus-window-up; }
132 + Mod+Shift+Left { move-column-left; }
133 + Mod+Shift+Right { move-column-right; }
134 + Mod+U { focus-workspace-down; }
135 + Mod+I { focus-workspace-up; }
136 + Mod+Shift+U { move-workspace-down; }
137 + Mod+Shift+I { move-workspace-up; }
138 + Mod+Shift+F { toggle-fullscreen; }
139 + Mod+V { move-window-between-floating-and-tiling; }
140 + Mod+F { maximize-column; }
141 + Mod+R { switch-preset-column-width; }
142 + Mod+Shift+R { switch-preset-window-height; }
143 + Mod+- { resize-column-width -10; }
144 + Mod+= { resize-column-width +10; }
145 + Mod+Tab { recent-windows-cycle; }
146 + Mod+Shift+Tab { recent-windows-cycle reverse; }
148 +```
150 +### Configure outputs
152 +```kdl
153 +// Built-in laptop screen
154 +output "eDP-1" {
155 + scale 2.0
158 +// External monitor with high refresh
159 +output "HDMI-A-1" {
160 + mode "2560x1440@143.912"
161 + position x=1920 y=0
162 + variable-refresh-rate
165 +// Rotate a monitor
166 +output "DP-1" {
167 + transform "90"
170 +// Disable a monitor
171 +output "HDMI-A-2" {
172 + off
174 +```
176 +### Window rules
178 +```kdl
179 +// Open Firefox maximized
180 +window-rule {
181 + match app-id="firefox$"
182 + open-maximized true
185 +// Firefox PiP floating at bottom-left
186 +window-rule {
187 + match app-id="firefox$" title="^Picture-in-Picture$"
188 + open-floating true
189 + default-floating-position x=32 y=32 relative-to="bottom-left"
190 + default-column-width { fixed 480; }
191 + default-window-height { fixed 270; }
194 +// Make Telegram floating except media viewer
195 +window-rule {
196 + match app-id=r#"^org\.telegram\.desktop$"#
197 + exclude title="^Media viewer$"
198 + open-floating true
201 +// Block sensitive windows from screencasts
202 +window-rule {
203 + match app-id=r#"^org\.keepassxc\.KeePassXC$"#
204 + block-out-from "screencast"
207 +// App-specific column width
208 +window-rule {
209 + match app-id="^blender$"
210 + default-column-width { fixed 1200; }
213 +// Screencasted windows get red border
214 +window-rule {
215 + match is-window-cast-target=true
216 + focus-ring { active-color "#f38ba8"; inactive-color "#7d0d2d"; }
217 + border { inactive-color "#7d0d2d"; }
220 +// Default floating position for a "dropdown terminal"
221 +window-rule {
222 + match app-id="^dropdown$"
223 + open-floating true
224 + default-floating-position x=0 y=0 relative-to="top"
225 + default-window-height { proportion 0.5; }
226 + default-column-width { proportion 0.8; }
228 +```
230 +### Layout: gaps, border, focus ring, shadow
232 +```kdl
233 +layout {
234 + gaps 16
235 + default-column-width { proportion 0.5; }
236 + preset-column-widths {
237 + proportion 0.2
238 + proportion 0.33333
239 + proportion 0.5
240 + proportion 0.66667
241 + proportion 0.8
243 + center-focused-column "on-overflow"
244 + always-center-single-column
245 + empty-workspace-above-first
247 + focus-ring {
248 + on
249 + width 4
250 + active-color "#7fc8ff"
251 + inactive-color "#505050"
252 + urgent-color "#9b0000"
255 + border {
256 + off
257 + // width 4
258 + // active-color "#ffc87f"
259 + // inactive-color "#505050"
262 + shadow {
263 + on
264 + softness 30
265 + spread 5
266 + offset x=0 y=5
267 + draw-behind-window true
268 + color "#00000070"
271 + tab-indicator {
272 + on
273 + hide-when-single-tab
274 + place-within-column
275 + gap 5
276 + width 4
277 + length total-proportion=0.5
278 + position "right"
281 + insert-hint {
282 + on
283 + color "#ffc87f80"
286 + struts {
287 + left 64
288 + right 64
289 + top 64
290 + bottom 64
293 +```
295 +### Input: keyboard, touchpad
297 +```kdl
298 +input {
299 + keyboard {
300 + xkb {
301 + layout "us"
302 + variant "colemak_dh_ortho"
303 + options "compose:ralt,ctrl:nocaps"
305 + repeat-delay 600
306 + repeat-rate 25
307 + track-layout "global"
308 + numlock
311 + touchpad {
312 + tap
313 + dwt
314 + natural-scroll
315 + accel-speed 0.2
316 + accel-profile "flat"
317 + click-method "clickfinger"
318 + scroll-method "two-finger"
321 + mouse {
322 + natural-scroll
323 + accel-speed 0.2
326 + focus-follows-mouse
327 + warp-mouse-to-focus
328 + workspace-auto-back-and-forth
331 +mod-key "Super"
332 +mod-key-nested "Alt"
333 +```
335 +### Animations
337 +```kdl
338 +animations {
339 + workspace-switch {
340 + spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
342 + window-open {
343 + duration-ms 150
344 + curve "ease-out-expo"
346 + window-close {
347 + duration-ms 150
348 + curve "ease-out-quad"
350 + horizontal-view-movement {
351 + spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
353 + window-movement {
354 + spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
356 + window-resize {
357 + spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
359 + overview-open-close {
360 + spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
363 +```
365 +### Named workspaces with layout overrides
367 +```kdl
368 +workspace "browser"
369 +workspace "chat" {
370 + open-on-output "HDMI-A-1"
372 +workspace "code" {
373 + layout {
374 + gaps 32
375 + border {
376 + on
377 + width 4
379 + struts {
380 + left 64
381 + right 64
382 + bottom 64
383 + top 64
387 +```
389 +### Spawn at startup
391 +```kdl
392 +spawn-at-startup "waybar"
393 +spawn-at-startup "alacritty"
394 +spawn-sh-at-startup "mate-polkit &"
395 +```
397 +### Layer rules (for waybar, fuzzel, etc.)
399 +```kdl
400 +layer-rule {
401 + match namespace="waybar"
402 + // waybar opacity
404 +layer-rule {
405 + match namespace="^launcher$"
406 + opacity 0.95
407 + shadow { on; }
408 + geometry-corner-radius 10
410 +layer-rule {
411 + match namespace="^notifications$"
412 + block-out-from "screencast"
414 +```
416 +### Gestures
418 +```kdl
419 +gestures {
420 + dnd-edge-view-scroll {
421 + trigger-width 30
422 + delay-ms 100
423 + max-speed 1500
425 + dnd-edge-workspace-switch {
426 + trigger-height 50
427 + delay-ms 100
428 + max-speed 1500
430 + hot-corners {
431 + top-left
432 + // top-right
433 + // bottom-left
434 + // bottom-right
437 +```
439 +### Recent windows (Alt-Tab switcher)
441 +```kdl
442 +recent-windows {
443 + debounce-ms 750
444 + open-delay-ms 150
445 + highlight {
446 + active-color "#999999ff"
447 + urgent-color "#ff9999ff"
448 + padding 30
449 + corner-radius 0
451 + previews {
452 + max-height 480
453 + max-scale 0.5
455 + binds {
456 + Alt+Tab { next-window; }
457 + Alt+Shift+Tab { previous-window; }
458 + Alt+grave { next-window filter="app-id"; }
459 + Alt+Shift+grave { previous-window filter="app-id"; }
462 +```
464 +### Miscellaneous settings
466 +```kdl
467 +prefer-no-csd
469 +screenshot-path "~/Pictures/Screenshots/Screenshot from %Y-%m-%d %H-%M-%S.png"
471 +cursor {
472 + xcursor-theme "breeze_cursors"
473 + xcursor-size 48
474 + hide-when-typing
475 + hide-after-inactive-ms 1000
478 +overview {
479 + zoom 0.5
480 + backdrop-color "#262626"
481 + workspace-shadow {
482 + softness 40
483 + spread 10
484 + offset x=0 y=10
485 + color "#00000050"
489 +xwayland-satellite {
490 + // off
491 + path "xwayland-satellite"
494 +clipboard {
495 + disable-primary
498 +hotkey-overlay {
499 + skip-at-startup
500 + hide-not-bound
503 +config-notification {
504 + disable-failed
506 +```
508 +## niri msg IPC commands
510 +Communicate with a running niri instance via `niri msg`. Socket at
511 +`$NIRI_SOCKET`.
513 +### Query state
515 +```bash
516 +niri msg outputs # List outputs with modes, VRR support
517 +niri msg windows # List all windows
518 +niri msg workspaces # List workspaces
519 +niri msg focused-window # Focused window info
520 +niri msg focused-output # Focused output name
521 +niri msg layers # List layer-shell surfaces
522 +niri msg pick-window # Click window → print app-id and title
523 +niri msg --json outputs # JSON output for scripting
524 +```
526 +### Actions
528 +```bash
529 +niri msg action focus-workspace <index-or-name>
530 +niri msg action focus-workspace-up
531 +niri msg action focus-workspace-down
532 +niri msg action move-workspace-to-top
533 +niri msg action move-column-to-workspace <workspace-name>
534 +niri msg action move-window-to-workspace <workspace-name>
536 +niri msg action focus-column-left
537 +niri msg action focus-column-right
538 +niri msg action focus-column-first
539 +niri msg action focus-column-last
540 +niri msg action focus-window-down
541 +niri msg action focus-window-up
543 +niri msg action move-column-left
544 +niri msg action move-column-right
545 +niri msg action move-window-down
546 +niri msg action move-window-up
548 +niri msg action switch-preset-column-width
549 +niri msg action switch-preset-window-height
550 +niri msg action set-column-width <+/-pixels>
551 +niri msg action set-window-height <+/-pixels>
552 +niri msg action maximize-column
553 +niri msg action center-column
554 +niri msg action resize-column-width <+/-percentage>
555 +niri msg action resize-window-height <+/-percentage>
557 +niri msg action toggle-fullscreen
558 +niri msg action maximize
559 +niri msg action unmaximize
560 +niri msg action move-window-between-floating-and-tiling
562 +niri msg action spawn <program> <args...>
563 +niri msg action spawn-sh <shell-command>
564 +niri msg action close-window
565 +niri msg action quit skip-confirmation=true
567 +niri msg action screenshot
568 +niri msg action screenshot-screen
569 +niri msg action screenshot-window
571 +niri msg action toggle-window-rule-opacity
572 +niri msg action toggle-keyboard-shortcuts-inhibit
573 +niri msg action do-screen-transition
575 +niri msg action overview-open
576 +niri msg action overview-close
578 +niri msg action recent-windows-cycle
579 +niri msg action recent-windows-cancel
580 +niri msg action recent-windows-final
582 +niri msg action power-off-monitors
583 +niri msg action power-on-monitors
585 +niri msg action set-workspace-name <name>
586 +niri msg action unset-workspace-name
588 +# Debug actions
589 +niri msg action toggle-debug-tint
590 +niri msg action debug-toggle-opaque-regions
591 +niri msg action debug-toggle-damage
592 +```
594 +### Event stream (for bars/scripts)
596 +```bash
597 +# Watch all events as JSON (complete state, then deltas)
598 +niri msg --json event-stream
600 +# Use socat to test IPC directly
601 +socat STDIO "$NIRI_SOCKET"
602 +# Then type a request like:
603 +{"FocusWindow":null}
604 +```
606 +### Tips
608 +- Run `niri msg action` with no arguments to list ALL available actions
609 +- Use `--json` for machine-readable output (stable API)
610 +- Output names change dynamically; use `niri msg outputs` to find current names
611 +- After upgrading niri, restart it before running `niri msg` to avoid version
612 + mismatch errors
613 +- The event stream gives you full state upfront, then incremental updates — no
614 + desync
616 +## Finding window app-id and title
618 +```bash
619 +niri msg pick-window
620 +# Click any window — prints its app-id and title
621 +# Example output:
622 +# app-id: "firefox"
623 +# title: "Mozilla Firefox"
625 +# Or list all windows:
626 +niri msg windows
627 +```
629 +## Debugging
631 +- **Config errors**: `niri validate` parses the config and prints errors
632 +- **Restart niri**: If config reload fails, niri keeps running with old config
633 + and shows a notification
634 +- **IPC errors after upgrade**: Restart niri — old `niri msg` can't talk to new
635 + niri
636 +- **Journal logs**: `journalctl -ef /usr/bin/niri` for runtime errors and custom
637 + shader warnings
638 +- **Find XKB key names**: Use `wev` — press any key and it prints the XKB symbol
639 + name

pi/agent/skills/nushell/SKILL.md

Added
new file mode 100644
1 +---
2 +name: nushell
3 +description: Nushell shell and scripting — structured data pipelines, $env variables, bash-to-nushell conversion, redirection gotchas. Use when working with nushell scripts, shell commands, or converting bash patterns.
4 +license: MIT
5 +---
7 +# Nushell
9 +Modern shell with structured data pipelines. Data flows as tables/lists/records, not text.
11 +## Help First (Built-in)
13 +```nushell
14 +help # General help overview
15 +help commands # List all 460+ commands
16 +help <command> # Help for specific command
17 +help --find "keyword" # Search commands by keyword
18 +help operators # All operators and precedence
19 +help <keyword> # keywords: if, match, for, try, etc.
20 +```
22 +**Tip**: `help` output is structured data. Use `| where` to filter.
24 +```nushell
25 +# Find all filter commands
26 +help commands | where category == "filters"
28 +# Find commands with "json" in description
29 +help --find "json" | get name
30 +```
32 +## Special Variables
34 +| Variable | Purpose |
35 +|----------|---------|
36 +| `$nu` | Runtime info: config-path, env-path, current-exe, is-interactive |
37 +| `$env` | Environment variables |
38 +| `$env.config` | Configuration record |
39 +| `$in` | Current pipeline input |
40 +| `$it` | Current row element (in `where`, `each`) |
42 +**Mnemonic**: Env vars start with `$env.` because "environment is where env vars live".
44 +## Bash → Nushell Cheat Sheet
46 +| Bash | Nushell |
47 +|------|---------|
48 +| `$VAR` | `$env.VAR` |
49 +| `export VAR=val` | `$env.VAR = val` |
50 +| `$?` | `$env.LAST_EXIT_CODE` |
51 +| `$(cmd)` | `(cmd)` |
52 +| `&&` / `\|\|` | `;` |
53 +| `cat file` | `open --raw file` |
54 +| `grep pattern` | `where $it =~ pattern` |
55 +| `find . -name "*.rs"` | `ls **/*.rs` |
56 +| `[ -f file ]` | `$file | path exists` |
57 +| `basename path` | `$path | path parse | get stem` |
58 +| `2>&1` | `o+e>\|` (external only!) |
60 +## Pipeline
62 +```nushell
63 +# Filter rows
64 +ls | where size > 1mb
65 +ls | where type == dir
66 +ls | where name =~ "^nu"
68 +# Transform columns
69 +ls | select name size
70 +ls | insert big {|row| $row.size > 1mb }
71 +ls | update name { path parse | get stem }
73 +# Iterate
74 +[1 2 3] | each {|x| $x * 2 }
75 +[1 2 3] | where $it > 2
76 +[1 2 3] | reduce {|val acc| $acc + $val }
77 +```
79 +## Redirection (Critical!)
81 +```nushell
82 +# Write to file
83 +"hello" | save output.txt
84 +"hello" | save --append output.txt
86 +# Redirect stderr (EXTERNAL COMMANDS ONLY!)
87 +^external_cmd e>| ignore # stderr to /dev/null
88 +^external_cmd o+e>| ignore # both streams to /dev/null
89 +^external_cmd o+e>| error.log # both to file
91 +# For internal commands - NO stderr redirection
92 +command | ignore # discard output
93 +try { risky } catch { ... } # catch errors
94 +```
96 +**Common mistake**: `e>|` only works with `^external_cmd`, not internal commands.
98 +## Variables
100 +```nushell
101 +# Immutable (most cases)
102 +let x = 10
103 +let items = [1 2 3]
104 +let cfg = {theme: dark}
106 +# Constants (compile-time)
107 +const PI = 3.14159
109 +# Mutable (rarely needed)
110 +mut y = 0
111 +$y = 5
113 +# Env vars (mutable globally)
114 +$env.PATH = ($env.PATH | prepend "/custom")
115 +```
117 +## Strings
119 +```nushell
120 +'hello world' # literal
121 +"hello\nworld" # escapes
122 +$"hello, ($name)!" # interpolation
123 +$'raw string'# # no escapes
124 +r#'can have "quotes"# # raw with quotes
125 +```
127 +## Data Types
129 +```nushell
130 +42 # int
131 +3.14 # float
132 +true/false # bool
133 +null # nothing
134 +[1 2 3] # list
135 +{a: 1, b: 2} # record
136 +[{x: 1}, {x: 2}] # table
137 +10mb, 1gb # filesize
138 +5sec, 2min # duration
139 +1..10 # range (inclusive)
140 +1..<10 # range (exclusive)
141 +```
143 +## Functions
145 +```nushell
146 +def greet [name: string] { $"Hello, ($name)!" }
147 +def add [a: int, b: int] { $a + $b }
148 +def sum [...nums: int] { $nums | math sum }
149 +```
151 +## Control Flow
153 +```nushell
154 +if $cond { "yes" } else { "no" }
156 +match $val {
157 + 1 => "one"
158 + 2 => "two"
159 + _ => "other"
162 +for i in 1..10 { print $i }
163 +```
165 +## Error Handling
167 +```nushell
168 +try {
169 + risky_operation
170 +} catch {|err|
171 + print $err.msg
174 +error make "something failed"
175 +error make {msg: "failed", help: "try this"}
176 +```
178 +**Note**: `$err` has `msg`, `debug`, `json` fields. No direct `code` field.
180 +## External Commands
182 +```nushell
183 +^ls -la # explicit external
184 +^echo "hello"
186 +# Spread args
187 +let args = ["-la", "*.nu"]
188 +^ls ...$args
189 +```
191 +## Modules
193 +```nushell
194 +module utils {
195 + export def add [a: int, b: int] { $a + $b }
198 +use utils add
199 +add 5 3
200 +```
202 +## Files
204 +```nushell
205 +ls *.nu # glob
206 +ls **/*.rs # recursive glob
207 +open file.json # parses structured data
208 +open --raw file.txt # raw text
209 +"/tmp" | path exists # check existence
210 +```
212 +## Run Scripts
214 +```nushell
215 +nu script.nu # run file
216 +nu -c 'ls | where ...' # one-liner
217 +```
219 +## Troubleshooting
221 +### 1. Command not found?
222 +```nushell
223 +# Check if command exists
224 +help commands | where name == "cmd"
225 +which cmd # finds command location
227 +# Try external
228 +^external_cmd
229 +```
231 +### 2. Type errors?
232 +```nushell
233 +# Check what type a value is
234 +$value | describe
236 +# Check command input/output types
237 +help <command> | get input_output
238 +```
240 +### 3. Structured data issues?
241 +```nushell
242 +# Inspect any value
243 +$value | debug
245 +# Explore nested data
246 +$value | explore
247 +```
249 +### 4. Pipeline not working?
250 +```nushell
251 +# Add debug step
252 +command | debug | your_command
254 +# Check what's flowing
255 +command | first
256 +```
258 +### 5. Environment issues?
259 +```nushell
260 +# List env vars
261 +$env | transpose | sort-by column0
263 +# Check specific var
264 +$env.PATH
265 +```
267 +## Online Resources
269 +**Use built-in `help` first** - it's faster and always accurate for your version.
271 +| Resource | When to Use |
272 +|----------|-------------|
273 +| `help commands` | Find commands, check signatures |
274 +| `help <cmd>` | Command details, examples |
275 +| [nushell.sh/book](https://www.nushell.sh/book) | Conceptual overview, getting started |
276 +| [nushell.sh/commands](https://www.nushell.sh/commands/) | Full command reference |
277 +| [nushell.sh/cookbook](https://www.nushell.sh/cookbook/) | Ready-made recipes |
278 +| [nushell.sh/lang-guide](https://www.nushell.sh/lang-guide/) | Language specification |
279 +| [github.com/nushell/nu_scripts](https://github.com/nushell/nu_scripts) | Community scripts, cool one-liners |
281 +**Quick tour**: [nushell.sh/book/quick_tour.html](https://www.nushell.sh/book/quick_tour.html) - covers basics in 5 minutes.
283 +## Common Mistakes (from real nushell use)
285 +1. **`2>&1`** → `o+e>\|` (for external commands)
287 +2. **`$err.code`** → `$err.msg` (code is in `$err.json`)
289 +3. **`ls | e>| ignore`** → Internal commands don't support stderr redirection. Use `try/catch`.
291 +4. **`$variable`** when meaning env var → `$env.variable`
293 +5. **`$(cmd)`** → `(cmd)`
295 +6. **Forgetting `^`** before external command → Use `^cmd` to be explicit
297 +7. **Pipe structured data expecting strings** → `help` returns tables, not strings. Use `| get column` not `| grep`.
299 +8. **`$config`** → `$env.config` (old syntax deprecated)
301 +9. **Assigning to `$var`** → Nushell vars are immutable. Use `mut` or `$env.var`.
303 +10. **`test -f file`** → `$file | path exists`

pi/agent/skills/pastel/SKILL.md

Added
new file mode 100644
1 +---
2 +name: pastel
3 +description: "Generate, analyze, convert and manipulate colors using the `pastel` CLI — format conversion (hex/RGB/HSL/LAB/LCH/OKLCh), color mixing, gradients, distinct palettes, colorblind simulation, terminal color output with ANSI. Use when: user mentions colors, palettes, color schemes, hex codes, color conversion, color contrast, color accessibility, terminal styling, color harmonies, or picking colors."
4 +license: MIT
5 +---
7 +## Commands Overview
9 +| Command | Purpose |
10 +| --------------------------------------- | ------------------------------------------------------------------ |
11 +| `pastel format` | Convert color to hex, RGB, HSL, LAB, LCH, OKLCh, ANSI, CMYK, name… |
12 +| `pastel color` | Show detailed info about a color |
13 +| `pastel textcolor` | Get a readable foreground color for a given background |
14 +| `pastel paint` | Print colored text with ANSI escape sequences |
15 +| `pastel pick` | Interactively pick a color from the screen (pipette) |
16 +| `pastel random` | Generate random colors with strategies (vivid, gray, lch_hue…) |
17 +| `pastel distinct` | Generate a set of visually distinct colors |
18 +| `pastel gradient` | Generate interpolating color sequences |
19 +| `pastel mix` | Mix two colors (configurable colorspace) |
20 +| `pastel lighten` / `pastel darken` | Adjust lightness |
21 +| `pastel saturate` / `pastel desaturate` | Adjust saturation |
22 +| `pastel rotate` | Rotate hue by an angle |
23 +| `pastel set` | Set a specific property (lightness, hue, chroma…) |
24 +| `pastel complement` | Get the complementary color (hue +180°) |
25 +| `pastel to-gray` | Fully desaturate while preserving luminance |
26 +| `pastel sort-by` | Sort colors by hue, brightness, luminance, chroma… |
27 +| `pastel colorblind` | Simulate protanopia/deuteranopia/tritanopia |
28 +| `pastel list` | Show all named CSS/X11 colors |
30 +## Color Input Formats
32 +All commands accept colors in these formats — use whatever is most convenient:
34 +```
35 +#ff6b6b hex (3 or 6 digits, optional #)
36 +ff6b6b hex without #
37 +rgb(255,107,107)
38 +255,107,107 rgb without parentheses
39 +hsl(0,100%,71%)
40 +orchid CSS/X11 color name
41 +gray(0.5) gray tone
42 +pick launch interactive color picker
43 +- read from stdin (one color per line)
44 +```
46 +Alpha transparency: `#rrggbbaa`, `rgba(255,107,107,0.5)`, `hsla(0,100%,71%,50%)`
48 +## Format Conversion
50 +```bash
51 +# Default output is hex
52 +pastel format ff6b6b # #ff6b6b
54 +# Many output formats available
55 +pastel format rgb ff6b6b # rgb(255,107,107)
56 +pastel format hsl ff6b6b # hsl(0,100%,71%)
57 +pastel format lch ff6b6b # lch(62.78,107.56,28.65)
58 +pastel format oklch ff6b6b # oklch(0.65 0.19 27.57)
59 +pastel format lab ff6b6b # lab(62.78 47.07 -9.17)
60 +pastel format name ff6b6b # salmon2 (nearest named color)
61 +pastel format cmyk ff6b6b # cmyk(0,58,58,0)
62 +pastel format luminance ff6b6b # 0.36
63 +pastel format brightness ff6b6b # 0.67
64 +pastel format ansi-8bit ff6b6b # 204
65 +pastel format ansi-24bit ff6b6b # 38;2;255;107;107
66 +```
68 +## Analysis
70 +```bash
71 +# Show full color info
72 +pastel color ff6b6b
74 +# Get readable foreground for a background
75 +pastel textcolor ff6b6b # prints a color
76 +pastel paint "$(pastel textcolor ff6b6b)" --on ff6b6b "readable text"
78 +# Check terminal 24-bit color support
79 +pastel colorcheck
80 +```
82 +## Generation
84 +```bash
85 +# Random vivid colors
86 +pastel random -n 5
88 +# Random with specific strategy
89 +pastel random -n 5 --strategy gray # grayscale
90 +pastel random -n 5 --strategy lch_hue # fixed lightness/chroma, random hue
92 +# Visually distinct palette (maximizes perceived difference)
93 +pastel distinct 8 # 8 distinct colors
94 +pastel distinct 5 --metric CIEDE2000 # more accurate metric (slower)
96 +# Color gradient between two or more colors
97 +pastel gradient ff6b6b ffd93d -n 10 # 10 steps from red to yellow
98 +pastel gradient 555ee4 white d84341 -n 15 # multi-stop gradient
99 +pastel gradient --colorspace=HSL ffffcc fd8d3c # force colorspace
100 +```
102 +## Manipulation
104 +```bash
105 +# Lightness / Darkness
106 +pastel lighten 0.2 ff6b6b # lighten by 0.2
107 +pastel darken 0.3 ff6b6b # darken by 0.3
109 +# Saturation
110 +pastel saturate 0.2 ff6b6b # increase saturation
111 +pastel desaturate 0.5 ff6b6b # decrease saturation
113 +# Hue rotation
114 +pastel rotate 90 ff6b6b # rotate hue 90° clockwise
115 +pastel rotate -30 ff6b6b # rotate hue 30° counter-clockwise
117 +# Mix two colors (default: 50/50 in Lab space)
118 +pastel mix ff6b6b 4ecdc4 # 50% mix
119 +pastel mix ff6b6b 4ecdc4 -f 0.75 # 75% first color, 25% second
120 +pastel mix --colorspace=RGB red blue # mix in RGB (less perceptually uniform)
122 +# Set a specific property
123 +pastel set lightness 0.9 ff6b6b # set lightness to 0.9
124 +pastel set hue 180 ff6b6b # set hue to 180°
125 +pastel set chroma 50 ff6b6b # set chroma to 50
127 +# Complementary color
128 +pastel complement ff6b6b # hue + 180°
130 +# Grayscale (preserves luminance)
131 +pastel to-gray ff6b6b
132 +```
134 +## Sorting
136 +```bash
137 +pastel random -n 10 | pastel sort-by hue # sort by hue
138 +pastel random -n 10 | pastel sort-by luminance # sort by perceptual lightness
139 +pastel random -n 10 | pastel sort-by brightness # sort by relative brightness
140 +pastel random -n 10 | pastel sort-by chroma # sort by color intensity
141 +pastel random -n 10 | pastel sort-by random # shuffle
142 +pastel random -n 10 | pastel sort-by hue --reverse
143 +```
145 +## Colorblind Simulation
147 +```bash
148 +pastel colorblind prot ff6b6b # protanopia (red-blind)
149 +pastel colorblind deuter ff6b6b # deuteranopia (green-blind)
150 +pastel colorblind trit ff6b6b # tritanopia (blue-blind)
152 +# Check if a palette is distinguishable for colorblind users
153 +pastel distinct 5 | pastel colorblind deuter
154 +```
156 +## Terminal Color Output
158 +```bash
159 +# Paint text in color
160 +pastel paint ff6b6b "Hello World"
161 +pastel paint -n black --on ff6b6b --bold "ERROR" # no newline, bold, on background
163 +# ANSI escape codes for scripts
164 +pastel format ansi-24bit-escapecode ff6b6b # outputs: \e[38;2;255;107;107m
165 +pastel format ansi-8bit-escapecode ff6b6b # outputs: \e[38;5;204m
167 +# Interactive color picker
168 +pastel pick
169 +```
171 +## Piping Patterns (Key Feature)
173 +`pastel` is designed for composition — chain commands together:
175 +```bash
176 +# Generate, transform, and format in one pipeline
177 +pastel random -n 8 | pastel lighten 0.2 | pastel format hex
179 +# Create a custom mix then check it
180 +pastel color ff6b6b | pastel mix - 4ecdc4 -f 0.3 | pastel format hex
182 +# Distinct palette -> rotate each hue by 30°
183 +pastel distinct 6 | pastel rotate 30 | pastel format hex
185 +# Gradient then pick a color in the middle
186 +pastel gradient ff6b6b 4ecdc4 -n 10 | pastel format hex
188 +# Sort palette by hue then output names
189 +pastel distinct 5 | pastel sort-by hue | pastel format name
191 +# Check colorblind accessibility of a palette
192 +pastel distinct 8 | pastel colorblind deuter
193 +```
195 +## Colorspace Guide
197 +`pastel` supports: `Lab`, `LCh`, `RGB`, `HSL`, `OkLab`. Choose the right one:
199 +| Colorspace | Best for |
200 +| -------------------------------- | ------------------------------------------------------- |
201 +| `Lab` (default for mix/gradient) | Perceptually uniform mixing — colors "look right" |
202 +| `LCh` | Same as Lab but in polar form (hue + chroma) |
203 +| `OkLab` | Modern perceptually uniform space, better for gradients |
204 +| `RGB` | Bright/screen colors, less perceptually accurate |
205 +| `HSL` | Wheel-based hue interpolation, can produce muddy mids |
207 +```bash
208 +pastel mix --colorspace=Lab red blue # perceptually correct (default)
209 +pastel mix --colorspace=OkLab red blue # modern alternative
210 +pastel mix --colorspace=RGB red blue # technical but less natural
211 +pastel gradient --colorspace=OkLab c44d58 ffd93d -n 10
212 +```
214 +See `references/color-theory.md` for deeper explanation of when to use each.
216 +## Common Recipes
218 +```bash
219 +# Find readable text color for any background
220 +fg=$(pastel textcolor ff6b6b)
221 +pastel paint "$fg" --on ff6b6b "readable"
223 +# Generate N hex codes for a palette
224 +pastel distinct 5 | pastel format hex
226 +# Create a warm-to-cool gradient
227 +pastel gradient "hsl(20,100%,70%)" "hsl(200,100%,70%)" -n 8 | pastel format hex
229 +# Desaturate a color to gray preserving luminance
230 +pastel to-gray ff6b6b | pastel format hex
232 +# Rotate a palette's hue uniformly
233 +pastel distinct 5 | pastel rotate 45 | pastel format hex
235 +# Make error/warning/info styled output
236 +pastel paint -n black --on ff6b6b --bold " ERROR "
237 +pastel paint -n black --on ffd93d --bold " WARNING "
238 +pastel paint -n black --on 4ecdc4 " INFO "
239 +```
241 +## Installation
243 +If `pastel` is not installed:
245 +- macOS: `brew install pastel`
246 +- Linux (Debian): `sudo apt install pastel` or download .deb from releases
247 +- Arch: `sudo pacman -S pastel`
248 +- Nix: `nix-env --install pastel`
249 +- Via Rust: `cargo install pastel`
250 +- Windows: `scoop install pastel` or `winget install sharkdp.pastel`
252 +Check: `pastel --version`

pi/agent/skills/pastel/references/color-theory.md

Added
new file mode 100644
1 +# Color Theory for Command-Line Color Work
3 +This reference helps you understand the _why_ behind colorspace choices in
4 +`pastel`.
6 +## Color Spaces
8 +### RGB
10 +Red-Green-Blue additive color mixing. Used in screens, LEDs, and most digital
11 +displays.
13 +- **Good for:** Bright saturated colors, direct manipulation of R/G/B channels,
14 + web/CSS work
15 +- **Bad for:** Mixing or interpolation — blending in RGB space produces muddy,
16 + desaturated colors because RGB is not perceptually uniform
17 +- **Example:** `pastel mix --colorspace=RGB red blue` gives a purple, but it's
18 + not the purple your eye expects
20 +### HSL / HSV
22 +Hue-Saturation-Lightness / Hue-Saturation-Value. Cylindrical representations of
23 +RGB.
25 +- **Good for:** Intuitive hue rotation (`pastel rotate`), selecting colors by
26 + "feel"
27 +- **Bad for:** Mixing — lightness in HSL doesn't correspond to perceptual
28 + lightness, so mixes look wrong
29 +- **Hue** wraps 0–360°. Saturation is distance from gray axis. Lightness/value
30 + are vertical axes
32 +### LAB (CIELAB)
34 +A perceptually uniform color space designed so that equal numerical distances =
35 +equal perceived color differences.
37 +- **Good for:** Color mixing, gradient interpolation, any time you want colors
38 + to "look right" to humans
39 +- **Components:** L = perceptual lightness (0–100), a = green–red axis, b =
40 + blue–yellow axis
41 +- **This is the default** for `pastel mix` and `pastel gradient` — it almost
42 + always gives better results than RGB or HSL
44 +### LCh
46 +Same as LAB but in polar coordinates: Lightness, Chroma (saturation-like), Hue.
48 +- **Chroma** is like saturation but in a perceptually uniform space — more
49 + meaningful than HSL saturation
50 +- **Good for:** Adjusting saturation-like properties without hue shifts, which
51 + can happen in HSL
52 +- `pastel saturate` and `pastel desaturate` operate in LCh
54 +### OKLab / OKLCh
56 +Modern perceptually uniform color space (Björn Ottosson's work). More accurate
57 +than LAB for human perception.
59 +- **Good for:** High-quality gradient interpolation, especially for UI/digital
60 + design work
61 +- **Currently the recommended choice** for gradients when you want maximum
62 + perceptual accuracy
63 +- Use: `pastel gradient --colorspace=OkLab …` or
64 + `pastel mix --colorspace=OkLab …`
66 +## Perceptual Uniformity
68 +A color space is "perceptually uniform" if a distance of 10 units feels like the
69 +same color difference everywhere in the space — regardless of whether you're in
70 +the reds, blues, greens, darks, or lights.
72 +RGB is **not** perceptually uniform:
74 +- A difference of 10 in R means something different than a difference of 10 in G
75 +- Moving 10 units in the dark area of RGB looks more different than moving 10
76 + units in the bright area
77 +- Mixing equal amounts of colors in RGB often gives muddy browns/grays instead
78 + of clean mid-tones
80 +LAB/LCh and OKLab/OKLCh **are** perceptually uniform:
82 +- Distances correspond to perceived differences
83 +- Mixing in these spaces gives natural-looking mid-tones
85 +**Rule of thumb:** Use `Lab` or `OkLab` for any mixing or gradient work. Reserve
86 +RGB/HSL for direct channel manipulation or when you specifically need RGB
87 +output.
89 +## Lightness, Luminance, and Brightness
91 +These three are often confused but differ:
93 +| Term | Definition | pastel property |
94 +| -------------- | ------------------------------------------------------ | ----------------------------------------- |
95 +| **Luminance** | Physical light output relative to white (0–1 for sRGB) | `luminance` (output via `pastel format`) |
96 +| **Lightness** | Perceptual "lightness" in LAB/LCH (0–100) | `lightness` or `lch-lightness` |
97 +| **Brightness** | Relative brightness in HSL/HSV (0–1 or 0–100) | `brightness` (output via `pastel format`) |
99 +`pastel to-gray` preserves **luminance** (physical) but not Lightness — the
100 +perceptual result still looks evenly grayed because the conversion uses
101 +luminance-correct formulas.
103 +## Color Difference Metrics
105 +When `pastel distinct` generates visually distinct colors, it needs a metric to
106 +measure "distance" between colors:
108 +- **CIE76**: The older metric. Adequate for most uses but doesn't account for
109 + perceptual non-uniformities in certain hue regions.
110 +- **CIEDE2000**: More accurate, especially for blue hues and near-neutral tones.
111 + Slower (10–100×), but worthwhile for palettes of 5+ colors where accuracy
112 + matters.
114 +```bash
115 +# Default (faster, good for ≤10 colors)
116 +pastel distinct 8
118 +# More accurate (slower, good for design work)
119 +pastel distinct 8 --metric CIEDE2000
120 +```
122 +## Colorblind Types
124 +Three common types affect different channels:
126 +| Type | Affected channel | Who it affects |
127 +| ---------------- | ---------------- | -------------------- |
128 +| **Protanopia** | Red (L-cones) | ~1% of males |
129 +| **Deuteranopia** | Green (M-cones) | ~1% of males |
130 +| **Tritanopia** | Blue (S-cones) | ~0.01% of population |
132 +```bash
133 +# Simulate how a color looks to each type
134 +pastel colorblind prot ff6b6b # red-blind view
135 +pastel colorblind deuter ff6b6b # green-blind view
136 +pastel colorblind trit ff6b6b # blue-blind view
137 +```
139 +**Designing accessible palettes:** A palette is safe if
140 +`pastel distinct N | pastel colorblind deuter` shows clearly distinguishable
141 +colors. For critical UI, test against all three.
143 +## Contrast and Readability
145 +WCAG guidelines require contrast ratios between foreground and background:
147 +- **4.5:1** minimum for normal text
148 +- **3:1** minimum for large text (18pt+ or 14pt+ bold)
150 +```bash
151 +# Get readable foreground for a background
152 +pastel textcolor ff6b6b
154 +# Verify contrast by checking both colors
155 +pastel color ff6b6b
156 +pastel color "$(pastel textcolor ff6b6b)"
157 +```
159 +Note: `pastel textcolor` uses luminance contrast analysis to pick a foreground
160 +that maximizes readability, preferring dark-on-light or light-on-dark depending
161 +on what works better for the given background.
163 +## Named Colors
165 +`pastel` supports all CSS/X11 named colors. Use `pastel list` to see them all,
166 +or `pastel format name <color>` to find the nearest named color to any given
167 +color:
169 +```bash
170 +pastel list | head -20 # first 20 named colors
171 +pastel format name ff6b6b # nearest named color
172 +```
174 +Notable named color groups:
176 +- **X11 colors**: snow, ghostwhite, lavender, etc. (147 colors)
177 +- **CSS Extended colors**: transparent, currentColor (CSS keywords)
178 +- The full list is available via `pastel list`
180 +## Further Reading
182 +- [CIELAB color space](https://en.wikipedia.org/wiki/CIELAB_color_space) — the
183 + math behind LAB
184 +- [OKLab color space](https://bottosson.github.io/posts/oklab/) — the modern
185 + alternative
186 +- [Color difference](https://en.wikipedia.org/wiki/Color_difference) — CIE76 vs
187 + CIEDE2000
188 +- [Color blindness prevalence](https://en.wikipedia.org/wiki/Color_blindness) —
189 + demographics and types

pi/agent/skills/pi

Added
new file mode 120000
1 +../../../../../.agents/skills/pi

pi/agent/skills/presenterm/SKILL.md

Added
new file mode 100644
1 +---
2 +name: presenterm
3 +description: >
4 + Create terminal-based presentations with presenterm markdown — end_slide separators,
5 + code highlighting with braces, Mermaid/D2 diagrams, column layouts, speaker notes.
6 + Themes include catppuccin, tokyonight, gruvbox, terminal-dark/light. Use when user
7 + mentions presentations, slides, slide deck, presenterm, terminal slides, or wants
8 + a talk in markdown format.
9 +---
11 +# presenterm Skill
13 +Create terminal-based presentations using presenterm's markdown format.
15 +**Official docs**: https://mfontanini.github.io/presenterm/
17 +## Quick Reference
19 +### Slide Structure
21 +```markdown
22 +---
23 +title: "My Talk"
24 +author: "Author Name"
25 +theme:
26 + name: dark
27 +---
29 +# Slide Title
31 +Content goes here.
33 +<!-- end_slide -->
35 +# Next Slide
36 +```
38 +### Built-in Themes
40 +| Dark Themes | Light Themes |
41 +| ------------------------------------- | ---------------- |
42 +| catppuccin-{frappe, macchiato, mocha} | catppuccin-latte |
43 +| dark | light |
44 +| gruvbox-dark | terminal-light |
45 +| terminal-dark | |
46 +| tokyonight-{moon, night, storm} | tokyonight-day |
48 +### Key Bindings
50 +| Key | Action |
51 +| -------------- | ------------------- |
52 +| `j`/`l`/arrows | Next slide |
53 +| `h`/`k` | Previous slide |
54 +| `gg` | First slide |
55 +| `G` | Last slide |
56 +| `NG` | Jump to slide N |
57 +| `ctrl+p` | Slide index modal |
58 +| `?` | Key bindings modal |
59 +| `T` | Toggle visual grid |
60 +| `ctrl+e` | Execute code block |
61 +| `ctrl+r` | Reload presentation |
62 +| `q` | Quit |
64 +## Comment Commands
66 +| Command | Purpose |
67 +| ---------------------------------- | ---------------------------------- |
68 +| `<!-- end_slide -->` | End current slide |
69 +| `<!-- pause -->` | Pause for next keypress |
70 +| `<!-- new_line -->` | Insert blank line |
71 +| `<!-- new_lines: N -->` | Insert N blank lines |
72 +| `<!-- jump_to_middle -->` | Center content vertically |
73 +| `<!-- column_layout: [2, 1] -->` | Define column widths |
74 +| `<!-- column: 0 -->` | Switch to column 0 |
75 +| `<!-- reset_layout -->` | End column layout |
76 +| `<!-- incremental_lists: true -->` | Bullet points appear one at a time |
77 +| `<!-- no_footer -->` | Hide footer on this slide |
78 +| `<!-- font_size: 2 -->` | Change font size (1-7, kitty only) |
79 +| `<!-- alignment: center -->` | Align text left/center/right |
80 +| `<!-- skip_slide -->` | Exclude from presentation |
81 +| `<!-- speaker_note: Note -->` | Add speaker note |
82 +| `<!-- include: file.md -->` | Include external markdown |
83 +| `<!-- list_item_newlines: 2 -->` | Extra spacing between list items |
85 +## Column Layouts
87 +```markdown
88 +<!-- column_layout: [2, 1] -->
90 +<!-- column: 0 -->
92 +Left content (2/3 width)
94 +<!-- column: 1 -->
96 +Right content (1/3 width)
98 +<!-- reset_layout -->
99 +```
101 +**Sizing**: `[2, 1]` = total 3 units, column 0 is 2/3, column 1 is 1/3. Equal
102 +halves: `[1, 1]`. Center content: `[1, 3, 1]` with content in column 1.
104 +## Code Blocks
106 +### Selective Highlighting
108 +````markdown
109 +```rust {1,3,5-7}
110 +fn main() {
111 + let x = 10;
112 + println!("Hello");
113 + let mut q = 42;
114 + q = q * 1337;
117 +```
118 +````
120 +````
121 +### Dynamic Reveal (progressive keypresses)
123 +```markdown
124 +```rust {1-3|5-7|all}
125 +fn potato() -> u32 {
126 + println!("Hello");
127 + let mut q = 42;
128 + q = q * 1337;
131 +````
133 +````
134 +### Code Block Attributes
136 +| Attribute | Effect |
137 +| -------------- | ----------------------------------- |
138 +| `+exec` | Make executable (ctrl+e) |
139 +| `+exec_replace` | Auto-execute and show output |
140 +| `+line_numbers` | Show line numbers |
141 +| `+no_background` | Remove code block background |
142 +| `+render` | Render mermaid/d2/LaTeX as image |
143 +| `+acquire_terminal` | Give full terminal to program |
145 +### Hidden Lines (for execution)
147 +Prefix with `# ` to hide but still execute:
149 +```markdown
150 +```rust +exec
151 +# use std::thread::sleep;
152 +# use std::time::Duration;
153 +fn main() {
154 + println!("Only this line shows");
156 +````
158 +````
159 +## Diagrams
161 +### Mermaid
163 +```markdown
164 +```mermaid +render
165 +flowchart LR
166 + A[Producer] --> B[(Kafka)]
167 + B --> C[Consumer]
168 +````
170 +````
171 +See `references/mermaid-syntax.md` for full syntax.
173 +### D2
175 +```markdown
176 +```d2 +render
177 +direction: right
178 +Producer -> Broker -> Consumer
179 +````
181 +````
182 +See `references/d2-integration.md` for details and link to `d2` skill.
184 +## Images
186 +```markdown
187 +![Alt text](path/to/image.png)
188 +![image:width:50%](photo.png)
189 +![image:300](icon.png)
190 +````
192 +Supported in kitty, iterm2, wezterm, ghostty, foot, sixel terminals.
194 +## Pauses and Incremental Content
196 +```markdown
197 +First appears
199 +<!-- pause -->
201 +Then on next keypress
203 +<!-- incremental_lists: true -->
205 +- Item 1 (appears alone)
206 +- Item 2 (next keypress)
207 +- Item 3
209 +<!-- incremental_lists: false -->
210 +```
212 +## Running Presentations
214 +```bash
215 +presenterm slides.md # Development mode (hot reload)
216 +presenterm -p slides.md # Presentation mode
217 +presenterm -t catppuccin-mocha slides.md # Override theme
218 +presenterm -x slides.md # Enable code execution
219 +presenterm -P slides.md # Publish speaker notes
220 +presenterm -e slides.md -o out.pdf # Export to PDF
221 +presenterm -E slides.md # Export to HTML
222 +presenterm --validate-overflows # Check slide fits terminal
223 +```
225 +## Theme Overrides
227 +```yaml
228 +---
229 +theme:
230 + name: dark
231 + override:
232 + default:
233 + colors:
234 + foreground: "#e6e6e6"
235 + background: "#040312"
236 + code:
237 + theme_name: base16-eighties.dark
238 + footer:
239 + style: progress_bar
240 +---
241 +```
243 +## Options (in frontmatter)
245 +```yaml
246 +---
247 +options:
248 + implicit_slide_ends: true # Auto-end slides on titles
249 + end_slide_shorthand: true # Allow --- as separator
250 + h1_slide_titles: true # # header becomes slide title
251 + auto_render_languages: # Auto-render these languages
252 + - mermaid
253 +---
254 +```
256 +## Design Patterns
258 +See `references/design-patterns.md` for:
260 +- Narrative Arc (setup → confrontation → resolution)
261 +- Gradual Consistency (progressive reveals)
262 +- Cave Painting (scripted demos)
263 +- Brain Breaks (every 10-15 minutes)
264 +- Antipatterns to avoid
266 +## Generate New Presentation
268 +```bash
269 +python scripts/new-presentation.py \
270 + --title "My Talk" \
271 + --author "Name" \
272 + --theme catppuccin-mocha \
273 + --template tech-talk \
274 + --output slides.md
276 +python scripts/new-presentation.py --title "X" --author "Y" --output - # stdout
277 +```
279 +### Available Templates
281 +- `minimal` - Bare starter with 2 placeholder slides
282 +- `tech-talk` - Narrative arc: Why → Problem → Solution → Demo → Summary
284 +## Example Files
286 +See `references/example-kafka.md` for a full working presentation.

pi/agent/skills/presenterm/references/d2-integration.md

Added
new file mode 100644
1 +# D2 Integration in presenterm
3 +D2 diagrams render in presenterm with `+render` attribute:
5 +````markdown
6 +```d2 +render
7 +direction: right
8 +Producer -> Broker -> Consumer
9 +```
10 +````
12 +````
13 +## Key Differences from Standalone D2
15 +| Feature | Standalone D2 | presenterm |
16 +| ------- | -------------- | ---------- |
17 +| Syntax | Full D2 | Full D2 |
18 +| Rendering | `d2 input.d2 out.svg` | Automatic via `+render` |
19 +| Layout | CLI flag or in-file | CLI flag or in-file |
20 +| Themes | `--theme` flag | presenterm handles via slide theme |
22 +## Terminal Sizing Tips
24 +presenterm presentations have constrained viewport width:
26 +1. **Keep diagrams small** — 5-10 nodes maximum
27 +2. **Use `direction: right`** for wide diagrams, `direction: down` for tall
28 +3. **Split complex architectures** across multiple slides
29 +4. **Match diagram colors to slide theme**:
30 + - Dark slides → `style.fill: "#2A2A2A"`, `style.font-color: "#FFFFFF"`
31 + - Light slides → `style.fill: "#FFFFFF"`, `style.font-color: "#000000"`
33 +## Presenterm-Specific Notes
35 +### Theme Coordination
37 +```d2
38 +direction: right
40 +service: My Service {
41 + style.fill: ${theme_fill}
42 + style.font-color: ${theme_foreground}
45 +# Match presenterm's dark theme colors
46 +vars: {
47 + theme_fill: "#2A2A2A"
48 + theme_foreground: "#e6e6e6"
50 +````
52 +### Scale Appropriately
54 +````markdown
55 +```d2 +render
56 +direction: right
58 +# Keep it simple - max 5-7 nodes per diagram
59 +api -> db -> cache
60 +```
61 +````
63 +```
64 +## Full D2 Reference
66 +For complete D2 syntax (shapes, connections, containers, SQL tables, styling), see the **d2 skill**:
67 +```
69 +Load the d2 skill for full syntax reference including:
71 +- Shape types (rectangle, circle, diamond, cylinder, etc.)
72 +- Connection types (arrows, lines, labels, chaining)
73 +- Container/nested syntax
74 +- SQL table diagrams
75 +- UML class diagrams
76 +- Sequence diagrams
77 +- Styling (fill, stroke, font, animations)
78 +- Variables and classes
79 +- Layout engines (dagre, ELK, TALA)
81 +````
82 +## Example: Architecture Diagram
84 +```markdown
85 +```d2 +render
86 +direction: right
88 +Backend: Backend Services {
89 + api: API Server { shape: hexagon }
90 + worker: Background Worker { shape: hexagon }
91 + db: Database { shape: cylinder }
92 + api -> worker: enqueue
93 + worker -> db: persist
96 +Frontend: Web App {
97 + ui: React UI
98 + state: State Store
101 +Frontend.ui -> Backend.api: REST calls {
102 + style.stroke-dash: 3
104 +````
106 +````
107 +## Installation (for rendering)
109 +presenterm uses the `d2` CLI to render diagrams:
111 +```bash
112 +# Install D2
113 +curl -fsSL https://d2lang.com/install.sh | sh -s --
115 +# Verify
116 +d2 --version
117 +````
119 +Without `d2` installed, `+render` blocks will show as code instead of diagrams.

pi/agent/skills/presenterm/references/design-patterns.md

Added
new file mode 100644
1 +# Presentation Design Patterns
3 +These patterns are from _Presentation Patterns_ by Neal Ford, Matthew
4 +McCullough, and Nathaniel Schutta.
6 +## Structure and Storytelling
8 +### Narrative Arc
10 +Structure every talk as a story:
12 +1. **Setup** — The problem or context
13 +2. **Confrontation** — The complexity or challenge
14 +3. **Resolution** — The solution or insight
16 +Use `<!-- pause -->` and incremental reveals to build tension before the
17 +resolution.
19 +### Triad
21 +Refine the arc into three acts. The "gloomy end of the second act" creates
22 +maximum tension before your solution arrives.
24 +### The Big Why
26 +Establish in the first two minutes why the audience should care. Developer
27 +audiences are practical — they check out without clear motivation.
29 +### Bookends
31 +Match opening and closing slides with the same visual treatment and core
32 +message. Open with the problem; close by revisiting it with the solution in
33 +place.
35 +### Foreshadowing
37 +Plant hints early: "We'll see later why this choice matters." Creates forward
38 +momentum.
40 +## Building Slides
42 +### Gradual Consistency
44 +Build information step by step rather than showing everything at once. For
45 +architecture diagrams, reveal components incrementally across multiple slides.
47 +Use `<!-- pause -->` between diagram stages or create a series of slides where
48 +each adds one more component.
50 +### Charred Trail
52 +When walking through a list, highlight the current item while graying out
53 +previous ones:
55 +```markdown
56 +<!-- incremental_lists: true -->
58 +- First point
59 +- Second point <!-- this is now "hot" -->
60 +- Third point
61 +```
63 +### Traveling Highlights
65 +For code, use dynamic highlighting to direct attention:
67 +````markdown
68 +```rust {1-3|5-8|10-13|all}
69 +// Block 1: Setup
70 +Props props = new Properties();
72 +// Block 2: Create producer
73 +KafkaProducer<String, String> producer =
74 + new KafkaProducer<>(props);
76 +// Block 3: Send record
77 +producer.send(new ProducerRecord<>(
78 + "my-topic", "key", "value"
79 +));
80 +```
81 +````
83 +````
84 +### Cave Painting
86 +Script every demo step in advance like a storyboard. Know exactly what you'll type, click, and show.
88 +Use `<!-- speaker_note: ... -->` to script each step.
90 +### Crawling Code
92 +Reveal code line by line or block by block with narration. Combine `+exec` with dynamic highlighting.
94 +### Intermezzi
96 +Use clear visual dividers between major sections:
98 +```markdown
99 +<!-- end_slide -->
101 +<!-- jump_to_middle -->
103 +Next Section
104 +===
106 +<!-- end_slide -->
107 +````
109 +### Breathing Room
111 +After showing a complex architecture diagram, stop talking for 3-5 seconds. Let
112 +it sink in. Add `<!-- pause -->` after diagram slides.
114 +## Audience Engagement
116 +### Brain Breaks
118 +Insert mental pauses every 10-15 minutes of dense content. A story, a joke, a
119 +change in visual rhythm.
121 +### Expansion Joints
123 +Mark sections as cuttable in advance so you can adapt to time constraints:
125 +```markdown
126 +<!-- speaker_note: CUTTABLE -->
127 +```
129 +## Antipatterns to Avoid
131 +### Bullet-Riddled Corpse
133 +Every slide as a bullet list read aloud. Use visual slides with the presenter
134 +supplying the verbal channel.
136 +### Ant Fonts
138 +Unreadable tiny text, especially code. If it can't be read from the back of the
139 +room, remove it. Keep code blocks under 15 lines.
141 +### Dead Demo
143 +Wasting time on environment setup and tool proficiency. If the demo is mostly
144 +boilerplate, put it on slides instead.
146 +### Slideuments
148 +Trying to make slides serve as both a presentation and a standalone document.
149 +Make a presentation OR a document.
151 +### Cookie Cutter
153 +Forcing every idea into exactly one slide. Some ideas need multiple slides.
155 +### Going Meta
157 +"On this next slide I'm going to show you..." Just show it.
159 +### Fontaholic
161 +Too many fonts. Stick to 2-3 maximum. In presenterm, the terminal font is your
162 +primary.
164 +### Floodmarks
166 +Logos and branding consuming valuable slide real estate. Use footer for minimal
167 +branding.

pi/agent/skills/presenterm/references/example-kafka.md

Added
new file mode 100644
1 +---
2 +title: "**Streaming** Data with _Kafka_"
3 +sub_title: A quick introduction
4 +author: Viktor Gamov
5 +theme:
6 + name: catppuccin-mocha
7 + override:
8 + footer:
9 + style: template
10 + right: "{current_slide} / {total_slides}"
11 + height: 2
12 +---
14 +<!-- speaker_note: THE BIG WHY - establish motivation immediately -->
16 +# Why Streaming?
18 +Every business is becoming a real-time business.
20 +<!-- pause -->
22 +Batch processing means **hours of delay**. Event streaming means
23 +**milliseconds**.
25 +<!-- pause -->
27 +Let's see how Apache Kafka makes this possible.
29 +<!-- end_slide -->
31 +# What is Kafka?
33 +<!-- incremental_lists: true -->
35 +- **Producers** send events to topics
36 +- **Consumers** read events from topics
37 +- **Brokers** store and replicate the data
38 +- Events are **immutable** and **ordered** within a partition
40 +<!-- end_slide -->
42 +# Architecture
44 +```mermaid +render
45 +%%{init: {'theme': 'dark'}}%%
46 +flowchart LR
47 + subgraph Producers
48 + P1[App 1]
49 + P2[App 2]
50 + end
51 + subgraph Kafka["Kafka Cluster"]
52 + B1[(Broker 1)]
53 + B2[(Broker 2)]
54 + B3[(Broker 3)]
55 + B1 <--> B2
56 + B2 <--> B3
57 + end
58 + subgraph Consumers
59 + C1[Analytics]
60 + C2[Search Index]
61 + end
62 + P1 --> B1
63 + P2 --> B2
64 + B1 --> C1
65 + B3 --> C2
66 +```
68 +<!-- end_slide -->
70 +<!-- jump_to_middle -->
72 +# Demo Time
74 +<!-- speaker_note: Cave Painting - scripted demo steps below -->
76 +<!-- end_slide -->
78 +# Producer Code
80 +```java {1-3|5-8|10-13|all}
81 +import org.apache.kafka.clients.producer.*;
83 +Properties props = new Properties();
84 +props.put("bootstrap.servers", "localhost:9092");
86 +Producer<String, String> producer =
87 + new KafkaProducer<>(props);
89 +producer.send(new ProducerRecord<>(
90 + "my-topic", "key", "value"
91 +));
93 +producer.close();
94 +```
96 +<!-- speaker_note: Traveling Highlights - walk through each block -->
98 +<!-- end_slide -->
100 +# Data Model
102 +```d2 +render
103 +direction: right
105 +topics: Topics {
106 + shape: sql_table
107 + id: int {constraint: primary_key}
108 + name: varchar
109 + partitions: int
112 +messages: Messages {
113 + shape: sql_table
114 + id: bigint {constraint: primary_key}
115 + topic_id: int {constraint: foreign_key}
116 + key: bytea
117 + value: bytea
120 +topics.id <-> messages.topic_id
121 +```
123 +<!-- end_slide -->
125 +# Summary
127 +<!-- alignment: center -->
129 +Kafka enables real-time data streaming at scale.
131 +**Thank you!**
133 +Questions?

pi/agent/skills/presenterm/references/mermaid-syntax.md

Added
new file mode 100644
1 +# Mermaid Syntax Reference
3 +Mermaid diagrams render in presenterm with `+render` attribute:
5 +````markdown
6 +```mermaid +render
7 +flowchart LR
8 + A --> B
9 +```
10 +````
12 +````
13 +## Flowcharts
15 +### Directions
17 +| Code | Meaning |
18 +| ---- | ------- |
19 +| `LR` | Left to Right |
20 +| `RL` | Right to Left |
21 +| `TD` / `TB` | Top to Down |
22 +| `BT` | Bottom to Top |
24 +### Node Shapes
26 +| Shape | Syntax | Use Case |
27 +| ---- | ------ | -------- |
28 +| Rectangle | `A[text]` | Default |
29 +| Rounded | `B(text)` | Rounded corners |
30 +| Stadium | `C([text])` | Programs |
31 +| Cylinder | `D[(text)]` | Database |
32 +| Circle | `E((text))` | Endpoints |
33 +| Diamond | `F{text}` | Decisions |
34 +| Hexagon | `G{{text}}` | Processes |
35 +| Parallelogram | `H[/text/]` | Input/Output |
37 +### Connections
39 +```markdown
40 +A --> B # Arrow
41 +A --- B # Line
42 +A -.-> B # Dotted
43 +A ==> B # Thick
44 +A <--> B # Bidirectional
45 +A -- text --> B # Labeled
46 +````
48 +### Subgraphs
50 +```markdown
51 +subgraph producers P1[App 1] P2[App 2] end subgraph kafka[Kafka] B1[(Broker 1)]
52 +B2[(Broker 2)] end P1 --> B1 P2 --> B2
53 +```
55 +### Pitfalls
57 +- The word `end` as node name breaks flowcharts — use `e[end]`
58 +- No space between ID and bracket: `A[text]` not `A [text]`
59 +- Parentheses need HTML entities: `#40;` for `(`, `#41;` for `)`
60 +- Theme engine only accepts hex colors, not color names
62 +## Sequence Diagrams
64 +````markdown
65 +```mermaid +render
66 +sequenceDiagram
67 + participant C as Client
68 + participant G as Gateway
69 + participant S as Service
70 + participant DB as Database
72 + C->>G: HTTP Request
73 + G->>S: Forward
74 + activate S
75 + S->>DB: Query
76 + DB-->>S: Results
77 + deactivate S
78 + S-->>G: Response
79 + G-->>C: HTTP Response
80 +```
81 +````
83 +````
84 +### Arrows
86 +| Arrow | Meaning |
87 +| ----- | ------- |
88 +| `->>` | Solid |
89 +| `-->>` | Dotted |
90 +| `-x` | Cross |
91 +| `-)` | Async |
93 +### Blocks
95 +`loop`, `alt`/`else`, `opt`, `par`/`and`, `critical`, `break`
97 +### Activation
99 +`activate`/`deactivate` or `+`/`-` suffixes.
101 +## Class Diagrams
103 +```markdown
104 +```mermaid +render
105 +classDiagram
106 + class KafkaProducer {
107 + +Properties config
108 + +send(ProducerRecord) Future
109 + +close() void
111 + class ProducerRecord {
112 + +String topic
113 + +K key
114 + +V value
116 + KafkaProducer --> ProducerRecord : creates
117 +````
119 +````
120 +### Visibility
122 +| Symbol | Meaning |
123 +| ------ | ------- |
124 +| `+` | Public |
125 +| `-` | Private |
126 +| `#` | Protected |
127 +| `~` | Package |
129 +### Relationships
131 +`<|--` inheritance, `*--` composition, `o--` aggregation, `-->` association
133 +## State Diagrams
135 +```markdown
136 +```mermaid +render
137 +stateDiagram-v2
138 + [*] --> Created
139 + Created --> Running : start()
140 + Running --> Paused : pause()
141 + Paused --> Running : resume()
142 + Running --> Stopped : stop()
143 + Stopped --> [*]
144 +````
146 +````
147 +## Entity-Relationship Diagrams
149 +```markdown
150 +```mermaid +render
151 +erDiagram
152 + TOPIC ||--o{ PARTITION : contains
153 + PARTITION ||--o{ MESSAGE : stores
155 + TOPIC {
156 + string name PK
157 + int partitions
159 +````
161 +````
162 +### Cardinality
164 +| Symbol | Meaning |
165 +| ------ | ------- |
166 +| `\|\|` | Exactly one |
167 +| `o\|` | Zero or one |
168 +| `}\|` | One or more |
169 +| `o{` | Zero or more |
171 +## Gantt Charts
173 +```markdown
174 +```mermaid +render
175 +gantt
176 + title Project Schedule
177 + dateFormat YYYY-MM-DD
178 + section Design
179 + Research :done, d1, 2024-01-01, 7d
180 + Design :active, d2, after d1, 5d
181 + section Build
182 + Implementation :done, b1, after d2, 10d
183 + Testing :active, b2, after b1, 5d
184 +````
186 +````
187 +## Pie Charts
189 +```markdown
190 +```mermaid +render
191 +pie title Distribution
192 + "Category A" : 40
193 + "Category B" : 35
194 + "Category C" : 25
195 +````
197 +````
198 +## Theming
200 +### In-Block Theme
202 +```markdown
203 +```mermaid +render
204 +%%{init: {'theme': 'dark'}}%%
205 +flowchart LR
206 + A --> B
207 +````
209 +````
210 +### Built-in Themes
212 +`default`, `neutral`, `dark`, `forest`, `base`
214 +### Custom Variables (base theme)
216 +```markdown
217 +%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#ff0000'}}}%%
218 +````
220 +### Terminal Sizing Tips
222 +- Keep diagrams to 5-10 nodes
223 +- Use `LR` direction for wide terminals
224 +- Use `%%{init: {'theme': 'dark'}}%%` on dark themes

pi/agent/skills/presenterm/scripts/new-presentation.py

Added
new file mode 100644
1 +#!/usr/bin/env python3
2 +"""
3 +Generate a presenterm presentation template.
5 +Usage:
6 + python new-presentation.py --title "My Talk" --author "Me" --theme dark --template minimal --output slides.md
7 + python new-presentation.py --title "My Talk" --author "Me" --theme catppuccin-mocha --template tech-talk --output slides.md
8 + python new-presentation.py --title "X" --author "Y" --output - # write to stdout
9 +"""
11 +import argparse
12 +import sys
13 +from pathlib import Path
15 +TEMPLATES = {
16 + "minimal": """---
17 +title: "{title}"
18 +author: "{author}"
19 +theme:
20 + name: {theme}
21 +---
23 +First Slide
24 +===
26 +Your content here.
28 +<!-- end_slide -->
30 +Second Slide
31 +===
33 +More content.
35 +<!-- end_slide -->
36 +""",
37 + "tech-talk": """---
38 +title: "{title}"
39 +author: "{author}"
40 +theme:
41 + name: {theme}
42 +---
44 +<!-- speaker_note: THE BIG WHY - hook the audience immediately -->
46 +Why This Matters
47 +===
49 +[Establish motivation in 2-3 sentences]
51 +<!-- end_slide -->
53 +The Problem
54 +===
56 +[Describe the pain point]
58 +<!-- incremental_lists: true -->
60 +* Point 1
61 +* Point 2
62 +* Point 3
64 +<!-- incremental_lists: false -->
66 +<!-- end_slide -->
68 +The Solution
69 +===
71 +[Your approach]
73 +<!-- end_slide -->
75 +<!-- jump_to_middle -->
77 +Demo
78 +===
80 +[Live code or screenshots]
82 +<!-- end_slide -->
84 +Summary
85 +===
87 +[Key takeaways]
89 +**Questions?**
90 +""",
93 +VALID_THEMES = [
94 + "catppuccin-latte",
95 + "catppuccin-frappe",
96 + "catppuccin-macchiato",
97 + "catppuccin-mocha",
98 + "dark",
99 + "gruvbox-dark",
100 + "light",
101 + "terminal-dark",
102 + "terminal-light",
103 + "tokyonight-day",
104 + "tokyonight-moon",
105 + "tokyonight-night",
106 + "tokyonight-storm",
110 +def main():
111 + parser = argparse.ArgumentParser(
112 + description="Generate a presenterm presentation template",
113 + formatter_class=argparse.RawDescriptionHelpFormatter,
114 + epilog="""
115 +Examples:
116 + python new-presentation.py --title "My Talk" --author "Me" --output slides.md
117 + python new-presentation.py --title "My Talk" --author "Me" --theme catppuccin-mocha --template tech-talk --output slides.md
118 + python new-presentation.py --title "My Talk" --author "Me" --output - # stdout
120 +Available themes:
121 + catppuccin-latte, catppuccin-frappe, catppuccin-macchiato, catppuccin-mocha
122 + dark, light, gruvbox-dark
123 + terminal-dark, terminal-light
124 + tokyonight-day, tokyonight-moon, tokyonight-night, tokyonight-storm
126 +Available templates:
127 + minimal - Bare starter (2 placeholder slides)
128 + tech-talk - Narrative arc structure (Why → Problem → Solution → Demo → Summary)
129 +""",
131 + parser.add_argument(
132 + "--title",
133 + help="Presentation title",
135 + parser.add_argument(
136 + "--author",
137 + help="Author name",
139 + parser.add_argument(
140 + "--theme",
141 + default="dark",
142 + help=f"Theme name (default: dark). Use --list-themes to see options.",
144 + parser.add_argument(
145 + "--template",
146 + choices=list(TEMPLATES.keys()),
147 + default="minimal",
148 + help="Template to use (default: minimal)",
150 + parser.add_argument(
151 + "--output",
152 + default="-",
153 + help="Output file path. Use - for stdout (default: -)",
155 + parser.add_argument(
156 + "--list-themes",
157 + action="store_true",
158 + help="List available themes and exit",
161 + args = parser.parse_args()
163 + if args.list_themes:
164 + print("Available themes:")
165 + for theme in VALID_THEMES:
166 + print(f" {theme}")
167 + return 0
169 + if not args.title or not args.author:
170 + print(
171 + "Error: --title and --author are required",
172 + file=sys.stderr,
174 + return 1
176 + if args.theme not in VALID_THEMES:
177 + print(
178 + f"Error: Unknown theme '{args.theme}'",
179 + file=sys.stderr,
181 + print("Use --list-themes to see available themes.", file=sys.stderr)
182 + return 1
184 + content = TEMPLATES[args.template].format(
185 + title=args.title,
186 + author=args.author,
187 + theme=args.theme,
190 + if args.output == "-":
191 + print(content)
192 + else:
193 + output_path = Path(args.output)
194 + output_path.parent.mkdir(parents=True, exist_ok=True)
195 + output_path.write_text(content)
196 + print(f"Created: {args.output}")
198 + return 0
201 +if __name__ == "__main__":
202 + sys.exit(main())

pi/agent/skills/presenterm/templates/minimal.md

Added
new file mode 100644
1 +---
2 +title: "Presentation Title"
3 +author: "Your Name"
4 +theme:
5 + name: dark
6 +---
8 +# First Slide
10 +Your content here.
12 +<!-- end_slide -->
14 +# Second Slide
16 +More content.
18 +<!-- end_slide -->

pi/agent/skills/presenterm/templates/tech-talk.md

Added
new file mode 100644
1 +---
2 +title: "Talk Title"
3 +author: "Your Name"
4 +theme:
5 + name: catppuccin-mocha
6 +---
8 +<!-- speaker_note: THE BIG WHY - hook the audience immediately -->
10 +# Why This Matters
12 +[Establish motivation in 2-3 sentences]
14 +<!-- end_slide -->
16 +# The Problem
18 +[Describe the pain point]
20 +<!-- incremental_lists: true -->
22 +- Point 1
23 +- Point 2
24 +- Point 3
26 +<!-- incremental_lists: false -->
28 +<!-- end_slide -->
30 +# The Solution
32 +[Your approach]
34 +<!-- end_slide -->
36 +<!-- jump_to_middle -->
38 +# Demo
40 +[Live code or screenshots]
42 +<!-- end_slide -->
44 +# Summary
46 +[Key takeaways]
48 +**Questions?**

pi/agent/skills/rust-maud/SKILL.md

Added
new file mode 100644
1 +---
2 +name: rust-maud
3 +description: Write HTML in Rust using Maud — compile-time verified html! macro, component patterns, PreEscaped, Render trait, integration with Axum/Actix.
4 +license: MIT
5 +---
7 +## What I do
9 +Guide Maud template engine usage in Rust. Maud compiles templates to Rust code
10 +at compile time.
12 +## Quick Start
14 +```rust
15 +use maud::html;
17 +let name = "World";
18 +let markup = html! {
19 + h1 { "Hello, " (name) "!" }
20 +};
21 +```
23 +```toml
24 +[dependencies]
25 +maud = "*"
26 +```
28 +## Syntax
30 +### Text and Escaping
32 +```rust
33 +html! { "Oatmeal, are you crazy?" } // Literal text
34 +html! { pre { r#"Rocks, these are my rocks."# } } // Raw strings
35 +html! { (PreEscaped("<script>")) } // Disable escaping
36 +html! { (DOCTYPE) } // DOCTYPE
37 +```
39 +### Elements
41 +```rust
42 +html! {
43 + h1 { "Title" }
44 + p { strong { "Bold" } " and normal" }
45 + br; // Void elements end with ;
46 + img src="img.png";
47 + input type="text" name="user";
48 + input type="checkbox" checked; // Boolean attribute
50 +```
52 +### Classes and IDs
54 +```rust
55 +html! {
56 + div#container.main-class {
57 + "Content"
58 + }
59 + #main { "Main" } // Implicit div
60 + .tip { "Tip" }
62 +```
64 +### Splices (Values)
66 +```rust
67 +html! {
68 + p { "Hi, " (name) "!" }
69 + a href=(href) { "Link" }
70 + a href={ (base) "/users" } { "API" } // Concatenate
71 + div.#(theme)-theme { "Content" } // Splice in class
73 +```
75 +### Toggles
77 +```rust
78 +html! {
79 + div contenteditable[editable] { "Edit" }
80 + li.active[is_active] { "Active" }
81 + p title=[title] { "Optional attr" } // Option<T>
83 +```
85 +### Control Flow
87 +```rust
88 +// @if / @else
89 +@if user_logged_in {
90 + a href="/logout" { "Logout" }
91 +} @else {
92 + a href="/login" { "Login" }
95 +// @if let
96 +@if let Some(name) = username {
97 + p { "Welcome, " (name) }
100 +// @for loop
101 +@for item in &items {
102 + li { (item) }
105 +// @let
106 +@let first = user.name.chars().next();
107 +li { (first) ". " (user.name) }
109 +// @match
110 +@match status {
111 + Status::Active => { span.active { "Active" } },
112 + _ => { span { "Unknown" } }
114 +```
116 +### Partials (Composition)
118 +```rust
119 +fn header(title: &str) -> Markup {
120 + html! { head { title { (title) } } }
123 +fn page(title: &str, content: Markup) -> Markup {
124 + html! {
125 + (header(title))
126 + main { (content) }
129 +```
131 +### Render Trait
133 +```rust
134 +use maud::{html, Render};
136 +struct Button { label: &'static str, href: &'static str }
138 +impl Render for Button {
139 + fn render(&self) -> Markup {
140 + html! { a href=(self.href) class="button" { (self.label) } }
144 +html! { (Button { label: "Click", href: "/click" }) }
145 +```
147 +## Framework Integration
149 +```rust
150 +// Actix-web
151 +#[get("/")]
152 +async fn index() -> Markup { html! { h1 { "Hello!" } } }
154 +// Rocket
155 +#[get("/<name>")]
156 +fn hello(name: &str) -> Markup { html! { h1 { "Hello, " (name) "!" } } }
158 +// Axum
159 +async fn hello() -> Markup { html! { h1 { "Hello!" } } }
160 +let app = Router::new().route("/", get(hello));
161 +```
163 +## Best Practices
165 +1. Prefer functions for partials
166 +2. Implement `Render` for domain types
167 +3. Use toggles `[is_active]` over `@if`
168 +4. Push logic to Rust, not templates
169 +5. Use `PreEscaped` sparingly
171 +---
173 +Use this skill when building Rust web apps with Maud templates.

pi/agent/skills/tiger/SKILL.md

Added
new file mode 100644
1 +---
2 +name: tiger
3 +description: Tiger Beetle style - fast, aggressive, language-agnostic coding. Ultra-minimalist. Pursuit of optimal path.
4 +---
6 +# Tiger Beetle Style
8 +Fastest insect. Relative to body size. Chase prey until caught.
10 +## Core Principles
12 +### 1. SPEED
13 +- O(1) > O(log n) > O(n) > O(n²)
14 +- No loops when can recurse
15 +- No function call overhead when inline
16 +- Cache expensive operations
18 +### 2. AGGRESSION
19 +- Direct path to goal
20 +- No intermediaries
21 +- No abstraction layers unless proven necessary
22 +- Fearless complexity
24 +### 3. SHARP
25 +- Single responsibility per block
26 +- No ambiguity
27 +- Return values explicit
28 +- Error handling immediate
30 +### 4. PURSUIT
31 +- Algorithm in pursuit of solution
32 +- Never give up (retry, backtrack, parallel)
33 +- Hunt until done
35 +## Caveman Ultra Rules
37 +1. **No unnecessary state** - vars are temporary, just enough
38 +2. **No comments needed** - code says what it does
39 +3. **No frameworks** - raw primitives
40 +4. **No magic** - explicit over implicit every time
41 +5. **No premature optimization** - but when needed, go hard
43 +## Implementation
45 +### Data Structures
47 +```
48 +LANG: Use simplest structure that fits
49 +- array over set when can (faster iteration)
50 +- hashmap only when key lookups needed
51 +- avoid nested structures > 3 levels
52 +```
54 +### Control Flow
56 +```
57 +LANG: Guard clauses first
58 +- check errors, return early
59 +- happy path last
60 +- no else chains
61 +```
63 +### Functions
65 +```
66 +LANG: Small, focused, named for what it does
67 +- one thing per function
68 +- params ≤ 3
69 +- if > 20 lines, split
70 +```
72 +### Error Handling
74 +```
75 +LANG: Fail fast, fail loud
76 +- validate input immediately
77 +- crash on invalid state
78 +- no silent defaults
79 +```
81 +## Examples
83 +### Find element
85 +```
86 +❌ Verbose:
87 +function findUser(users, id):
88 + for user in users:
89 + if user.id == id:
90 + return user
91 + return null
93 +✅ Tiger Beetle:
94 +users[id] # direct hash lookup, O(1)
95 +```
97 +### Validate then process
99 +```
100 +❌ Verbose:
101 +function update(user, data):
102 + if (user exists):
103 + if (data valid):
104 + user = merge(user, data)
105 + save(user)
106 + return ok
107 + return error
109 +✅ Tiger Beetle:
110 +validate(data) || crash()
111 +user = merge(user, data)
112 +save(user)
113 +```
115 +## Anti-Patterns
117 +- YAGNI violations
118 +- Clever one-liners that obscure
119 +- Premature abstraction
120 +- State when you can compute
121 +- Loops when you can map
122 +- try/catch masking bugs
124 +## When to Apply
126 +- Performance critical paths
127 +- Hot loops
128 +- Data pipelines
129 +- Parsers/transforms
130 +- Anything touching I/O
132 +## When NOT to Apply
134 +- One-off scripts
135 +- Prototypes
136 +- Team code without consensus
137 +- Readability-critical shared code
139 +## Tiger Test
141 +1. Is there a faster algorithm? If yes, use it.
142 +2. Can this state be computed instead? If yes, compute.
143 +3. Can this abstraction be removed? If yes, remove.
144 +4. Is this comment necessary? If code explains itself, no.
145 +5. Would caveman understand this? If no, simplify.

pi/agent/skills/twelve-factor/SKILL.md

Added
new file mode 100644
1 +---
2 +name: twelve-factor
3 +description: Twelve-factor app methodology for cloud-native SaaS — codebase, config, backing services, stateless processes, port binding, disposability. Use when architecting new cloud applications, microservices, or container deployments.
4 +license: MIT
5 +---
7 +## What I do
9 +Guide twelve-factor app design. Use when architecting cloud-native applications.
11 +## The Twelve Factors
13 +- I Codebase: One codebase, many deploys
14 +- II Dependencies: Explicitly declare and isolate
15 +- III Config: Store config in environment vars
16 +- IV Backing Services: Treat external services as resources
17 +- V Build/Release: Strictly separate stages
18 +- VI Processes: Stateless, share-nothing
19 +- VII Port Binding: Export services via port
20 +- VIII Concurrency: Scale via process model
21 +- IX Disposability: Fast startup, graceful shutdown
22 +- X Dev/Prod: Keep environments similar
23 +- XI Logs: Treat logs as event streams
24 +- XII Admin: Run admin as one-off processes
26 +---
28 +## I. Codebase
30 +One codebase tracked in version control, many deploys.
32 +- Single Git repository
33 +- Same codebase → dev, staging, production
34 +- Each deploy runs specific version
36 +---
38 +## II. Dependencies
40 +Explicitly declare and isolate. Never rely on implicit system packages.
42 +**Always use dependency manifest**:
44 +```toml
45 +# Rust: Cargo.toml
46 +[dependencies]
47 +serde = "1.0"
49 +# Node: package.json
50 +{ "dependencies": { "express": "^4.18" } }
51 +```
53 +**Never**:
55 +```python
56 +import requests # Hopes it's installed globally
57 +```
59 +---
61 +## III. Config
63 +Store config in environment variables. Separate config from code.
65 +```rust
66 +let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
67 +let log_level = env::var("LOG_LEVEL").unwrap_or("info");
68 +```
70 +**What goes in env vars**: Database URLs, API keys, feature flags, service
71 +endpoints.
73 +**Not in env vars**: Application logic, static config.
75 +---
77 +## IV. Backing Services
79 +Treat external services as attached resources—accessed via URL in config.
81 +```bash
82 +# Swap services without code changes
83 +DATABASE_URL=postgres://localhost:5432/dev # dev
84 +DATABASE_URL=postgres://prod:5432/prod # prod
85 +```
87 +Resources: Database, Cache, Queue, Email, Storage, External APIs.
89 +---
91 +## V. Build, Release, Run
93 +Strictly separate stages:
95 +```
96 +BUILD (code → artifact) → RELEASE (artifact + config) → RUN (execute)
97 +```
99 +- CI/CD pipeline handles this
100 +- Releases are immutable
101 +- Rollback by deploying previous release
103 +---
105 +## VI. Processes
107 +Stateless, share-nothing. Any persistent state in backing service.
109 +```rust
110 +// Bad: State in memory
111 +static mut CACHE: Option<HashMap<_, _>> = None;
113 +// Good: Stateless, state in Redis
114 +fn get_data(key: &str) -> Option<Vec<u8>> {
115 + redis_client.get(key).ok()
117 +```
119 +- No sticky sessions
120 +- Filesystem only for temporary cache
122 +---
124 +## VII. Port Binding
126 +Self-contained app exports HTTP by binding to port.
128 +```rust
129 +let port = env::var("PORT").unwrap_or("8080").parse()?;
130 +HttpServer::new(...).bind(("0.0.0.0", port))?
131 +```
133 +- Port from environment
134 +- Self-contained
135 +- Service accessible via HTTP
137 +---
139 +## VIII. Concurrency
141 +Scale via Unix process model. Different workloads = different process types.
143 +```yaml
144 +services:
145 + web:
146 + command: ./bin/server
147 + replicas: 3
148 + worker:
149 + command: ./bin/worker
150 + replicas: 5
151 +```
153 +Scale by adding processes, not bigger processes.
155 +---
157 +## IX. Disposability
159 +Fast startup, graceful shutdown.
161 +**Fast startup**: Minimize startup time, lazy initialization.
163 +**Graceful shutdown** (SIGTERM):
165 +1. Stop accepting new requests
166 +2. Finish current requests
167 +3. Close backing service connections
168 +4. Exit
170 +**Crash-only**: State is in backing services, sudden death is safe.
172 +---
174 +## X. Dev/Prod Parity
176 +Keep development, staging, production similar.
178 +- Gap Time: Solution → Deploy hours after coding
179 +- Gap People: Solution → Developers deploy their code
180 +- Gap Tools: Solution → Same tools everywhere
182 +Use Docker/containers locally same as production.
184 +---
186 +## XI. Logs
188 +Treat logs as event streams. Write to stdout.
190 +```rust
191 +println!(r#"{"timestamp":"{}","level":"INFO","msg":"Request"}"#, now());
192 +```
194 +- Write to stdout
195 +- Environment handles routing (Docker, Kubernetes)
196 +- Include correlation IDs
198 +---
200 +## XII. Admin Processes
202 +Run admin tasks as one-off processes, same environment as regular.
204 +```bash
205 +docker run myapp:v1.2.3 ./bin/migrate
206 +kubectl exec deployment/myapp -- ./bin/migrate
207 +```
209 +Examples: Migrations, REPL inspection, data cleanup.
211 +---
213 +## Quick Checklist
215 +- [ ] Single codebase
216 +- [ ] Dependencies explicit
217 +- [ ] Config in env vars
218 +- [ ] External services as resources
219 +- [ ] Build/Release/Run separated
220 +- [ ] Stateless processes
221 +- [ ] Port from environment
222 +- [ ] Horizontal scaling
223 +- [ ] Fast startup/shutdown
224 +- [ ] Dev/Prod parity
225 +- [ ] Logs to stdout
226 +- [ ] Admin same environment
228 +---
230 +Use this skill when building cloud-native applications.

pi/agent/skills/uuid-generator/SKILL.md

Added
new file mode 100644
1 +---
2 +name: uuid-generator
3 +description: "Generate UUIDs/GUIDs in various formats and versions. Use when: generating database keys, API IDs, session tokens, bulk UUIDs, namespace-based deterministic UUIDs (UUID5), format conversion (hyphenated/compact/URN/uppercase), or validating UUID strings."
4 +---
6 +# UUID Generator
8 +Generate universally unique identifiers (UUIDs) in various formats for distributed systems, databases, and APIs.
10 +## CLI Usage
12 +```bash
13 +# Generate single UUID4 (random, default)
14 +python scripts/uuid_generator.py
16 +# Generate specific version
17 +python scripts/uuid_generator.py --version 1 # time-based
18 +python scripts/uuid_generator.py --version 4 # random (default)
19 +python scripts/uuid_generator.py --version 5 # namespace-based
21 +# Bulk generation
22 +python scripts/uuid_generator.py --count 100
23 +python scripts/uuid_generator.py --count 1000 --output uuids.txt
25 +# Format options
26 +python scripts/uuid_generator.py --format compact # no hyphens
27 +python scripts/uuid_generator.py --format urn # urn:uuid:...
28 +python scripts/uuid_generator.py --format uppercase # uppercase hex
30 +# Namespace UUID (UUID5 - deterministic)
31 +python scripts/uuid_generator.py --namespace dns --name example.com
32 +python scripts/uuid_generator.py --namespace url --name "https://foo.com/bar"
34 +# Validate a UUID
35 +python scripts/uuid_generator.py --validate "a1b2c3d4-e5f6-4789-abcd-ef0123456789"
37 +# Export formats
38 +python scripts/uuid_generator.py --count 10 --format json # JSON array
39 +python scripts/uuid_generator.py --count 10 --format csv # CSV with header
40 +```
42 +## Programmatic Usage
44 +```python
45 +from uuid_generator import UUIDGenerator
47 +gen = UUIDGenerator()
49 +# Single UUID
50 +uuid = gen.generate() # UUID4 (random)
51 +uuid = gen.generate(version=1) # UUID1 (time-based)
52 +uuid = gen.generate(version=5, namespace='dns', name='example.com') # UUID5
54 +# Bulk generation
55 +uuids = gen.generate_bulk(count=100)
56 +uuids = gen.generate_bulk(count=100, version=4)
58 +# Format output
59 +uuid = gen.generate(format='compact') # no hyphens
60 +uuid = gen.generate(format='urn') # urn:uuid:...
61 +uuid = gen.generate(format='uppercase') # uppercase
63 +# Validate
64 +gen.validate("a1b2c3d4-e5f6-4789-abcd-ef0123456789") # True/False
65 +```
67 +## Quick Reference
69 +| Version | Use Case | Deterministic |
70 +|---------|---------------------------------------|---------------|
71 +| UUID1 | Time-ordered, MAC address disclosure | No |
72 +| UUID4 | Random, privacy-preserving | No |
73 +| UUID5 | Namespace-based, reproducible | Yes |
75 +| Namespace | Typical Use |
76 +|-----------|-------------------------------|
77 +| dns | Domain names |
78 +| url | URLs |
79 +| oid | ISO OID |
80 +| x500 | X.500 Distinguished Names |

pi/agent/skills/uuid-generator/scripts/requirements.txt

Added
new file mode 100644
1 +# Standard library only - no external dependencies

pi/agent/skills/uuid-generator/scripts/uuid_generator.py

Added
new file mode 100644
1 +#!/usr/bin/env python3
2 +"""UUID Generator - Generate and validate UUIDs in various formats."""
4 +import argparse
5 +import uuid
6 +import sys
7 +import json
8 +import csv
9 +from typing import List, Optional
12 +class UUIDGenerator:
13 + VALID_FORMATS = {"hyphenated", "compact", "urn", "uppercase"}
14 + VALID_VERSIONS = {1, 4, 5}
15 + VALID_NAMESPACES = {"dns", "url", "oid", "x500"}
17 + def __init__(self):
18 + self.last_result: List[str] = []
20 + def generate(
21 + self,
22 + version: int = 4,
23 + namespace: Optional[str] = None,
24 + name: Optional[str] = None,
25 + format: str = "hyphenated",
26 + ) -> str:
27 + if format not in self.VALID_FORMATS:
28 + raise ValueError(
29 + f"Invalid format: {format}. Choose from {self.VALID_FORMATS}"
30 + )
31 + if version not in self.VALID_VERSIONS:
32 + raise ValueError(
33 + f"Invalid version: {version}. Choose from {self.VALID_VERSIONS}"
34 + )
36 + u: uuid.UUID = uuid.uuid4()
37 + if version == 1:
38 + u = uuid.uuid1()
39 + elif version == 4:
40 + u = uuid.uuid4()
41 + elif version == 5:
42 + if not namespace or not name:
43 + raise ValueError("UUID5 requires --namespace and --name")
44 + if namespace not in self.VALID_NAMESPACES:
45 + raise ValueError(
46 + f"Invalid namespace: {namespace}. Choose from {self.VALID_NAMESPACES}"
47 + )
48 + ns = getattr(uuid, f"NAMESPACE_{namespace.upper()}", uuid.NAMESPACE_DNS)
49 + u = uuid.uuid5(ns, name)
51 + return self._format(u, format)
53 + def _format(self, u: uuid.UUID, format: str) -> str:
54 + if format == "hyphenated":
55 + return str(u)
56 + elif format == "compact":
57 + return u.hex
58 + elif format == "urn":
59 + return str(u.urn)
60 + elif format == "uppercase":
61 + return str(u).upper()
62 + return str(u)
64 + def generate_bulk(
65 + self, count: int, version: int = 4, format: str = "hyphenated"
66 + ) -> List[str]:
67 + return [self.generate(version=version, format=format) for _ in range(count)]
69 + def validate(self, value: str) -> bool:
70 + try:
71 + uuid.UUID(value)
72 + return True
73 + except (ValueError, AttributeError):
74 + return False
77 +def main():
78 + parser = argparse.ArgumentParser(description="Generate UUIDs")
79 + parser.add_argument(
80 + "--version",
81 + "-v",
82 + type=int,
83 + default=4,
84 + choices=[1, 4, 5],
85 + help="UUID version (1=time, 4=random, 5=namespace)",
86 + )
87 + parser.add_argument(
88 + "--count", "-c", type=int, default=1, help="Number of UUIDs to generate"
89 + )
90 + parser.add_argument(
91 + "--namespace", choices=["dns", "url", "oid", "x500"], help="Namespace for UUID5"
92 + )
93 + parser.add_argument("--name", "-n", help="Name for UUID5")
94 + parser.add_argument("--output", "-o", help="Output file path")
95 + parser.add_argument(
96 + "--format",
97 + "-f",
98 + default="hyphenated",
99 + choices=["hyphenated", "compact", "urn", "uppercase"],
100 + help="Output format",
102 + parser.add_argument("--validate", metavar="UUID", help="Validate a UUID string")
103 + parser.add_argument(
104 + "--export", choices=["json", "csv"], help="Export format for bulk output"
107 + args = parser.parse_args()
109 + gen = UUIDGenerator()
111 + if args.validate:
112 + result = gen.validate(args.validate)
113 + print(f"{args.validate}: {'valid' if result else 'invalid'}")
114 + sys.exit(0 if result else 1)
116 + if args.count == 1:
117 + uid = gen.generate(
118 + version=args.version,
119 + namespace=args.namespace,
120 + name=args.name,
121 + format=args.format,
123 + print(uid)
124 + else:
125 + uuids = gen.generate_bulk(
126 + count=args.count, version=args.version, format=args.format
128 + gen.last_result = uuids
130 + if args.output:
131 + if args.export == "json":
132 + with open(args.output, "w") as f:
133 + json.dump(uuids, f, indent=2)
134 + elif args.export == "csv":
135 + with open(args.output, "w", newline="") as f:
136 + writer = csv.writer(f)
137 + writer.writerow(["uuid"])
138 + for u in uuids:
139 + writer.writerow([u])
140 + else:
141 + with open(args.output, "w") as f:
142 + f.write("\n".join(uuids))
143 + print(f"Generated {args.count} UUIDs -> {args.output}")
144 + else:
145 + if args.export == "json":
146 + print(json.dumps(uuids, indent=2))
147 + elif args.export == "csv":
148 + print("uuid")
149 + for u in uuids:
150 + print(u)
151 + else:
152 + for uid in uuids:
153 + print(uid)
156 +if __name__ == "__main__":
157 + main()

pi/agent/skills/wezterm/SKILL.md

Added
new file mode 100644
1 +---
2 +name: wezterm
3 +description: WezTerm terminal emulator configuration — Lua config, panes, tabs, multiplexer (SSH/WSL domains), key bindings, CLI, and appearance. Use when configuring WezTerm, writing ~/.wezterm.lua, building key bindings, using mux workspaces, or automating the CLI.
4 +---
6 +# WezTerm Skill
8 +WezTerm is a Rust-based GPU-accelerated terminal emulator with a built-in
9 +multiplexer, cross-platform (Linux/macOS/Windows/FreeBSD/NetBSD). Configuration
10 +uses **Lua 5.4** in `~/.wezterm.lua` or `~/.config/wezterm/wezterm.lua`.
12 +**Config file discovery order:** CLI `--config-file` > `$WEZTERM_CONFIG_FILE` >
13 +Windows exe dir > `$XDG_CONFIG_HOME/wezterm/wezterm.lua` >
14 +`~/.config/wezterm/wezterm.lua` > `~/.wezterm.lua`
16 +**Auto-reload:** enabled by default (`automatically_reload_config = true`).
17 +Changes take effect without restart.
19 +## Basic Config
21 +```lua
22 +local wezterm = require 'wezterm'
23 +local config = wezterm.config_builder()
25 +config.font = wezterm.font 'JetBrains Mono'
26 +config.font_size = 11
27 +config.color_scheme = 'nord'
28 +config.enable_tab_bar = false
30 +return config
31 +```
33 +## Config File Location
35 +| Priority | Path |
36 +| -------- | -------------------------------------------------- |
37 +| 1 | `--config-file` CLI argument |
38 +| 2 | `$WEZTERM_CONFIG_FILE` env var |
39 +| 3 | Windows: exe directory (portable/thumb drive mode) |
40 +| 4 | `$XDG_CONFIG_HOME/wezterm/wezterm.lua` |
41 +| 5 | `~/.config/wezterm/wezterm.lua` |
42 +| 6 | `~/.wezterm.lua` |
44 +**Key config options:**
46 +```lua
47 +config.automatically_reload_config = true -- default
48 +config.config_file = 'path/to/wezterm.lua' -- explicit path
49 +```
51 +## Colors & Appearance
53 +```lua
54 +-- Use a built-in color scheme
55 +config.color_scheme = 'nord' -- see wezterm.color.get_builtin_schemes()
57 +-- Fully custom colors
58 +config.colors = {
59 + foreground = '#cccccc',
60 + background = '#1e1e1e',
61 + cursor_bg = '#ffffff',
62 + cursor_border = '#ffffff',
63 + cursor_fg = '#1e1e1e',
64 + selection_bg = '#264f78',
65 + tab_bar = { background = '#0d1117', active_tab = { bg_color = '#161b22', fg_color = '#cccccc' } },
66 + ansi = { '#484848', '#cc4444', '#44cc44', '#cccc44', '#4444cc', '#cc44cc', '#44cccc', '#cccccc' },
67 + brightness = { '#303030', '#e06060', '#60e060', '#e0e060', '#6060e0', '#e060e0', '#60e0e0', '#e0e0e0' },
69 +```
71 +**Background layers** (multiple can be combined):
73 +```lua
74 +-- Solid background color
75 +config.background = { { source = 'solid_color', color = '#0d1117' } }
77 +-- Vertical gradient
78 +config.background = {
79 + { source = 'linear_gradient', orientation = 'Vertical', colors = { '#0d1117', '#161b22' } },
82 +-- Radial gradient
83 +config.background = {
84 + { source = 'radial_gradient', anchor = 'bottom', colors = { '#0d1117', '#161b22' } },
87 +-- Background image
88 +config.background = {
89 + { source = 'image', path = '/path/to/image.png', hscan = 'Flip', vscan = 'Tile' },
90 + { source = 'solid_color', color = '#0d1117', alpha = 0.7 }, -- overlay
92 +```
94 +**Window chrome:**
96 +```lua
97 +config.window_decorations = 'RESIZE' -- 'RESIZE' | 'MACOS_BORDERLESS' | 'NONE' | 'ALWAYS_FORCE_OPAQUE'
98 +config.window_background_opacity = 0.95
99 +config.window_padding = { left = 8, right = 8, top = 0, bottom = 0 }
100 +config.hide_tab_bar_if_only_one_tab = true
101 +config.use_fancy_tab_bar = false
102 +config.tab_bar_at_bottom = false
103 +```
105 +## Fonts
107 +```lua
108 +-- Single font
109 +config.font = wezterm.font 'JetBrains Mono'
111 +-- With fallback chain
112 +config.font = wezterm.font_with_fallback { 'JetBrains Mono', 'Fira Code', 'Noto Sans' }
114 +-- Font with size and line height
115 +config.font_size = 12
116 +config.line_height = 1.2
117 +config.font_rules = {
118 + { italic = true, font = wezterm.font('JetBrains Mono', { italic = true }) },
119 + { weight = 'Bold', font = wezterm.font('JetBrains Mono', { weight = 'Bold' }) },
121 +```
123 +**Harfbuzz shaping features:**
125 +```lua
126 +config.font_rules = {
128 + intensity = 'Bold',
129 + font = wezterm.font('JetBrains Mono', { weight = 'Bold' }),
130 + },
132 + italic = true,
133 + font = wezterm.font('JetBrains Mono', { italic = true }),
134 + },
136 +```
138 +## Key Bindings
140 +```lua
141 +config.keys = {
142 + -- Basic keybinding
143 + { key = 't', mods = 'CTRL|SHIFT', action = wezterm.action.SpawnTab 'CurrentPaneDomain' },
145 + -- With multiple modifiers
146 + { key = 'Enter', mods = 'ALT', action = wezterm.action.ToggleFullScreen },
148 + -- Send string (type text)
149 + { key = 'w', mods = 'CTRL|SHIFT', action = wezterm.action.SpawnWindow },
151 + -- Encode special keys
152 + { key = 'LeftArrow', mods = 'ALT', action = wezterm.action.EmitEvent 'noop' },
155 +config.leader = { key = 'a', mods = 'CTRL' } -- chord: Ctrl-a then key
156 +```
158 +**Modifier names:** `CTRL`, `SHIFT`, `ALT`, `SUPER` (macOS Cmd), `CMD`, `META`,
159 +`SUPER`
161 +**Key names:** single chars, `Enter`, `Escape`, `Space`, `Backspace`, `Tab`,
162 +`F1`–`F12`, `LeftArrow`, `RightArrow`, `UpArrow`, `DownArrow`, `Home`, `End`,
163 +`PageUp`, `PageDown`, `Insert`, `Delete`
165 +**Key tables** for mode switching:
167 +```lua
168 +config.key_tables = {
169 + copy_mode = {
170 + { key = 'Escape', mods = 'NONE', action = wezterm.action.ActivateCopyMode 'Prev' },
171 + { key = 'q', mods = 'NONE', action = wezterm.action.ActivateCopyMode 'Close' },
172 + { key = 'g', mods = 'NONE', action = 'ScrollByPage', args = { -1 } },
173 + { key = 'G', mods = 'SHIFT', action = 'ScrollToBottom' },
174 + { key = 'j', mods = 'NONE', action = 'ScrollByLine', args = { 1 } },
175 + { key = 'k', mods = 'NONE', action = 'ScrollByLine', args = { -1 } },
176 + { key = 'v', mods = 'NONE', action = wezterm.action.CopyMode 'Select' },
177 + { key = 'V', mods = 'SHIFT', action = wezterm.action.CopyMode 'SelectLine' },
178 + { key = 'y', mods = 'NONE', action = wezterm.action.CopyTo 'Clipboard' },
179 + { key = '/', mods = 'NONE', action = wezterm.action.Search { Regex = '', mode = 'CopyMode' } },
180 + },
182 +```
184 +## Key Actions Reference
186 +### Pane Operations
188 +```lua
189 +wezterm.action.SplitHorizontal { domain = 'CurrentPaneDomain' }
190 +wezterm.action.SplitVertical { domain = 'CurrentPaneDomain' }
191 +wezterm.action.SplitPane { program = '/bin/bash', cwd = '/home', domain = 'CurrentPaneDomain' }
192 +wezterm.action.CloseCurrentPane { confirm = true }
193 +wezterm.action.AdjustPaneSize { direction = 'Down', amount = 3 }
194 +wezterm.action.TogglePaneZoomState
195 +wezterm.action.PaneSelect { mode = 'Swap' } -- 'Activate' | 'Swap' | 'ForceSelected' | 'Reset'
196 +```
198 +### Tab Operations
200 +```lua
201 +wezterm.action.SpawnTab 'CurrentPaneDomain'
202 +wezterm.action.SpawnTab { domain = 'CurrentPaneDomain', program = '/bin/bash', cwd = '/home' }
203 +wezterm.action.CloseCurrentTab { confirm = true }
204 +wezterm.action.ActivateTab 2
205 +wezterm.action.MoveTab 3
206 +wezterm.action.ShowTabNavigator
207 +```
209 +### Window Operations
211 +```lua
212 +wezterm.action.SpawnWindow
213 +wezterm.action.ActivateWindow 0
214 +wezterm.action.SwitchToWorkspace { name = 'main', spawn = { 'wezterm', 'start' } }
215 +wezterm.action.ToggleFullScreen
216 +wezterm.action.Maximize
217 +```
219 +### Navigation
221 +```lua
222 +wezterm.action.ActivatePaneDirection 'Down'
223 +wezterm.action.ActivatePaneDirection 'Left'
224 +wezterm.action.ActivatePaneDirection 'Right'
225 +wezterm.action.ActivatePaneDirection 'Up'
226 +wezterm.action.ActivatePaneByIndex 0 -- 0-indexed
227 +wezterm.action.PaneSelect -- interactive
228 +wezterm.action.PaneSelect { mode = 'Activate' }
229 +```
231 +### Text Operations
233 +```lua
234 +wezterm.action.SendString 'hello'
235 +wezterm.action.SendKey { key = 'Enter' }
236 +wezterm.action.Paste 'Clipboard'
237 +wezterm.action.CompleteSelection 'Clipboard'
238 +wezterm.action.CopyTo 'Clipboard'
239 +```
241 +### Copy Mode
243 +```lua
244 +wezterm.action.ActivateCopyMode 'CopyMode'
245 +wezterm.action.CopyMode { preset = 'vim' } -- vim or emacs
246 +wezterm.action.ScrollByPage -1
247 +wezterm.action.ScrollByLine 5
248 +wezterm.action.Search { Regex = 'pattern', mode = 'CopyMode' }
249 +wezterm.action.QuickSelect
250 +```
252 +### UI / Overlay
254 +```lua
255 +wezterm.action.ShowLauncher { titles = {}, cli_labels = {} }
256 +wezterm.action.ShowDebugOverlay
257 +wezterm.action.PromptInputLine {
258 + description = 'Enter command',
259 + action = wezterm.action_callback(function(window, pane, line)
260 + if line then window:perform_action(wezterm.action.SendString(line), pane) end
261 + end),
263 +wezterm.action.InputSelector {
264 + description = 'Select option',
265 + choices = { { label = 'opt1', id = '1' } },
266 + action = wezterm.action_callback(function(window, pane, id, label) end),
268 +```
270 +### Multiple / Chaining
272 +```lua
273 +wezterm.action.Multiple {
274 + wezterm.action.SplitHorizontal { domain = 'CurrentPaneDomain' },
275 + wezterm.action.ActivatePaneDirection 'Right',
277 +```
279 +### Other Actions
281 +```lua
282 +wezterm.action.EmitEvent 'my-event-name'
283 +wezterm.action.ReloadConfiguration
284 +wezterm.action.QuitApplication
285 +wezterm.action.CharSelect { copy_on_select = true, }
286 +```
288 +## Lua API Modules
290 +### wezterm module
292 +```lua
293 +wezterm.action(action_obj) -- perform an action
294 +wezterm.action_callback(fn) -- callback(fn(window, pane, ...)) -> action
295 +wezterm.config_builder() -- returns config table
296 +wezterm.default_hyperlink_rules() -- returns hyperlink rules
297 +wezterm.font(name, opts) -- font with optional weight/italic/slant
298 +wezterm.font_with_fallback({'Font1', 'Font2'})
299 +wezterm.format({ { Foreground = { Color = 'red' }, Text = 'hello' } })
300 +wezterm.glob(pattern) -- glob expansion
301 +wezterm.json_encode(val) -- JSON string
302 +wezterm.json_parse(str) -- parse JSON
303 +wezterm.log_error(msg)
304 +wezterm.log_info(msg)
305 +wezterm.log_warn(msg)
306 +wezterm.nerdfonts -- table of icon names
307 +wezterm.now() -- Unix timestamp
308 +wezterm.on('event', fn) -- register event handler
309 +wezterm.read_dir(dir) -- list directory entries
310 +wezterm.reload_configuration()
311 +wezterm.run_child_process(cmd) -- returns { stdout, stderr, exit_code }
312 +wezterm.sleep_ms(ms)
313 +wezterm.strftime(fmt, ts) -- format timestamp
314 +```
316 +**Programmatic config reload:**
318 +```lua
319 +wezterm.on('window-config-reloaded', function(window)
320 + wezterm.log_info('config reloaded for ' .. window:panel():get_title())
321 +end)
322 +```
324 +### wezterm.color
326 +```lua
327 +wezterm.color.parse('#ff0000') -- returns { r=1, g=0, b=0, a=1 }
328 +wezterm.color.from_hsla(180, 0.5, 0.5, 1.0) -- returns Color
329 +wezterm.color.gradient({'#red', 'blue'}, 'horizontal', 10) -- interpolate colors
330 +wezterm.color.get_builtin_schemes() -- list all built-in schemes
331 +wezterm.color.load_scheme('nord') -- load scheme as color table
332 +wezterm.color.extract_colors_from_image('/path/to/image.png') -- extract palette
333 +```
335 +### wezterm.gui
337 +```lua
338 +wezterm.gui.get_appearance() -- 'Dark' | 'Light' | 'Unknown'
339 +wezterm.gui.screens() -- list screens: { { width, height, xscale, yscale, name } }
340 +wezterm.gui.enumerate_gpus() -- list available GPUs
341 +wezterm.gui.default_keys() -- default keybindings as table
342 +wezterm.gui.default_key_tables() -- default key tables (copy mode, etc.)
343 +wezterm.gui.gui_windows() -- all GUI windows
344 +```
346 +**Dark/light mode switching:**
348 +```lua
349 +wezterm.on('update-status', function(window, pane)
350 + local appearance = wezterm.gui.get_appearance()
351 + local scheme = appearance == 'Dark' and 'nord' or 'nord-light'
352 + window:configure_actions({
353 + { SetColorScheme = scheme },
354 + })
355 +end)
356 +```
358 +### wezterm.mux
360 +```lua
361 +wezterm.mux.spawn_window({ domain = 'local', workspace = 'main', cwd = '/home' })
362 +wezterm.mux.get_active_workspace() -- current workspace name
363 +wezterm.mux.all_windows() -- all mux windows
364 +wezterm.mux.rename_workspace(old_name, new_name)
365 +wezterm.mux.set_active_workspace(name)
366 +```
368 +**Window/Pane objects:**
370 +```lua
371 +window:gui_window() -- GuiWindow
372 +window:mux_window() -- MuxWindow
373 +pane:split({ program = '/bin/bash', domain = 'CurrentPaneDomain' })
374 +pane:send_text('text\n')
375 +pane:paste()
376 +pane:get_title()
377 +pane:get_current_working_dir() -- returns Path or nil
378 +pane:get_foreground_process_info() -- returns ProcessInfo { pid, name, cwd }
379 +pane:get_text_from_region(0, 0, 100, 200) -- get text rectangle
380 +pane:inject_output('text\n')
381 +```
383 +### wezterm.plugin
385 +```lua
386 +wezterm.plugin.require('github.com/path/to/plugin') -- load plugin
387 +wezterm.plugin.list() -- list loaded plugins
388 +wezterm.plugin.update_all() -- update all plugins
389 +```
391 +## Events
393 +| Event | Callback |
394 +| ------------------------ | ------------------------------------- |
395 +| `gui-startup` | `fn(window)` |
396 +| `gui-attached` | `fn(window)` |
397 +| `mux-startup` | `fn()` |
398 +| `format-tab-title` | `fn(tab, tabs, panes, config, hover)` |
399 +| `format-window-title` | `fn(window)` |
400 +| `update-status` | `fn(window, pane)` |
401 +| `update-right-status` | `fn(window, pane)` |
402 +| `window-config-reloaded` | `fn(window)` |
403 +| `window-focus-changed` | `fn(window, bool)` |
404 +| `window-resized` | `fn(window, size)` |
405 +| `bell` | `fn(window, pane)` |
406 +| `open-uri` | `fn(uri, action)` |
407 +| `user-var-changed` | `fn(pane, name, value)` |
409 +**Example — dynamic tab titles:**
411 +```lua
412 +wezterm.on('format-tab-title', function(tab, tabs, panes, config, hover)
413 + return tab.tab_index + 1 .. ': ' .. tab.active_pane.title
414 +end)
415 +```
417 +**Example — status line:**
419 +```lua
420 +wezterm.on('update-right-status', function(window, pane)
421 + window:set_right_status(wezterm.format {
422 + { Text = wezterm.strftime('%H:%M:%S') },
423 + })
424 +end)
425 +```
427 +## Multiplexing & Domains
429 +```lua
430 +config.unix_domains = { { name = 'unix', socket_dir = '/tmp/wezterm' } }
431 +config.ssh_domains = {
433 + name = 'prod-server',
434 + host = 'example.com',
435 + username = 'me',
436 + port = 22,
437 + -- or use SSH config: remote_addr = 'example.com'
438 + ssh_option = 'value',
439 + },
441 +config.wsl_domains = { { name = 'WSL:Ubuntu', distribution = 'Ubuntu' } }
442 +config.tls_domains = { { name = 'tls-server', host = 'example.com', port = 443 } }
443 +```
445 +**Spawning in domains:**
447 +```lua
448 +{ key = 'c', mods = 'CTRL|SHIFT', action = wezterm.action.SpawnCommandInDomain { domain = 'unix', program = '/bin/bash' } }
449 +```
451 +## CLI Reference
453 +```bash
454 +# Launch GUI
455 +wezterm start
456 +wezterm start --config-file ~/.wezterm.lua
457 +wezterm start --prefix-search 'ssh'
459 +# SSH
460 +wezterm ssh user@host
461 +wezterm ssh user@host --domian-name prod
463 +# Connect to domain
464 +wezterm connect domain-name
466 +# Pane management
467 +wezterm cli split-pane --right -- /bin/bash
468 +wezterm cli split-pane --down --weight 0.3 -- bash -c 'top'
469 +wezterm cli list # list panes/windows/tabs
470 +wezterm cli activate-pane-direction Left
471 +wezterm cli activate-pane 2
472 +wezterm cli zoom-pane
474 +# Send text
475 +wezterm cli send-text --pane-id 1 "echo hello\n"
477 +# Read text
478 +wezterm cli get-text --pane-id 1 --start-cell 0,0 --end-cell 100,50
480 +# Titles
481 +wezterm cli set-tab-title --pane-id 1 "My Tab"
482 +wezterm cli set-window-title --window-id 0 "My Window"
483 +wezterm cli rename-workspace --name main
485 +# Status
486 +wezterm cli list --format json
488 +# Utilities
489 +wezterm show-keys --help # key sequence explorer
490 +wezterm ls-fonts # list available fonts
491 +wezterm imgcat /path/to/image.png # display image
492 +wezterm serial /dev/ttyUSB0 115200
493 +wezterm record --label "session" # record session
494 +wezterm replay /path/to/recording # replay
495 +```
497 +**CLI flags for `wezterm start`:**
499 +```bash
500 +wezterm start --config-file FILE
501 +wezterm start --cwd DIR
502 +wezterm start --position X,Y
503 +wezterm start --size WIDTH,HEIGHT
504 +wezterm start --domain SOCKET_DIR
505 +wezterm start --workspace NAME
506 +```
508 +## Common Patterns
510 +**Dark/light mode colors:**
512 +```lua
513 +local function get_colors()
514 + local appearance = wezterm.gui.get_appearance()
515 + local scheme = appearance == 'Dark' and 'nord' or 'nord-bright'
516 + return wezterm.color.load_scheme(scheme)
517 +end
519 +wezterm.on('update-status', function(window, pane)
520 + local colors = get_colors()
521 + pane:set_config_overrides {
522 + colors = { foreground = colors.foreground, background = colors.background },
524 +end)
525 +```
527 +**Gradient background with overlay:**
529 +```lua
530 +config.background = {
531 + { source = 'linear_gradient', orientation = 'Vertical', colors = { '#0d1117', '#161b22' } },
532 + { source = 'solid_color', color = '#000000', width = '100%', opacity = 0.3, fill = 'Gradient' },
534 +```
536 +**Workspace-aware status:**
538 +```lua
539 +wezterm.on('format-window-title', function(window)
540 + local workspace = wezterm.mux.get_active_workspace()
541 + return workspace .. ' — ' .. window:gui_window().title
542 +end)
543 +```
545 +**Conditional action with callback:**
547 +```lua
548 +wezterm.on('update-status', function(window, pane)
549 + local has_jobs = #pane:get_foreground_process_info() > 0
550 + window:perform_action(
551 + has_jobs and wezterm.action.ShowTabNavigator()
552 + or wezterm.action_callback(function() end),
553 + pane
555 +end)
556 +```
558 +## URL Reference
560 +| Topic | URL |
561 +| --------------------- | --------------------------------------------- |
562 +| Main docs | https://wezterm.org/ |
563 +| Config overview | https://wezterm.org/config/ |
564 +| Lua config options | https://wezterm.org/config/lua/config/ |
565 +| Lua API reference | https://wezterm.org/config/lua/wezterm/ |
566 +| Color module | https://wezterm.org/config/lua/wezterm.color/ |
567 +| GUI module | https://wezterm.org/config/lua/wezterm.gui/ |
568 +| Mux module | https://wezterm.org/config/lua/wezterm.mux/ |
569 +| KeyAssignment actions | https://wezterm.org/config/lua/keyassignment/ |
570 +| Window events | https://wezterm.org/config/lua/window-events/ |
571 +| GUI events | https://wezterm.org/config/lua/gui-events/ |
572 +| CLI reference | https://wezterm.org/cli/cli/ |
573 +| Key binding config | https://wezterm.org/config/keys.html |
574 +| Key tables | https://wezterm.org/config/key-tables.html |
575 +| Default keys | https://wezterm.org/config/default-keys.html |
576 +| Launching programs | https://wezterm.org/config/launch.html |
577 +| Plugin system | https://wezterm.org/config/plugins.html |
578 +| Mouse bindings | https://wezterm.org/config/mouse.html |
579 +| Color schemes | https://wezterm.org/config/colors.html |