Merge upstream v2.40.0 with local fork additions preserved
Incorporates 163 upstream commits (origin/main) while preserving all local skills, agents, and commands. Metadata descriptions updated to reflect actual component counts (30 agents, 56 skills, 7 commands). file-todos/SKILL.md merged with both upstream command rename and local assessment fields. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
---
|
||||
name: excalidraw-png-export
|
||||
description: "This skill should be used when creating diagrams, architecture visuals, or flowcharts and exporting them as PNG files. It uses the Excalidraw MCP to render hand-drawn style diagrams locally and Playwright to export them to PNG without sending data to any remote server. Triggers on requests like 'create a diagram', 'make an architecture diagram', 'draw a flowchart and export as PNG', or any request that needs a visual diagram delivered as an image file."
|
||||
---
|
||||
|
||||
# Excalidraw PNG Export
|
||||
|
||||
Create hand-drawn style diagrams with the Excalidraw MCP and export them locally to PNG files. All rendering happens on the local machine. Diagram data never leaves the user's computer.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### First-Time Setup
|
||||
|
||||
Run the setup script once per machine to install Playwright and Chromium headless:
|
||||
|
||||
```bash
|
||||
bash <skill-path>/scripts/setup.sh
|
||||
```
|
||||
|
||||
This creates a `.export-runtime` directory inside `scripts/` with the Node.js dependencies. The setup is idempotent and skips installation if already present.
|
||||
|
||||
### Required MCP
|
||||
|
||||
The Excalidraw MCP server must be configured. Verify availability by checking for `mcp__excalidraw__create_view` and `mcp__excalidraw__read_checkpoint` tools.
|
||||
|
||||
## File Location Convention
|
||||
|
||||
Save diagram source files alongside their PNG exports in the project's image directory. This enables re-exporting diagrams when content or styling changes.
|
||||
|
||||
**Standard pattern:**
|
||||
```
|
||||
docs/images/my-diagram.excalidraw # source (commit this)
|
||||
docs/images/my-diagram.png # rendered output (commit this)
|
||||
```
|
||||
|
||||
**When updating an existing diagram**, look for a `.excalidraw` file next to the PNG. If one exists, edit it and re-export rather than rebuilding from scratch.
|
||||
|
||||
**Temporary files** (raw checkpoint JSON) go in `/tmp/excalidraw-export/` and are discarded after conversion.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Design the Diagram Elements
|
||||
|
||||
Translate the user's request into Excalidraw element JSON. Load [excalidraw-element-format.md](./references/excalidraw-element-format.md) for the full element specification, color palette, and sizing guidelines.
|
||||
|
||||
Key design decisions:
|
||||
- Choose appropriate colors from the palette to distinguish different components
|
||||
- Use `label` on shapes instead of separate text elements
|
||||
- Use `roundness: { type: 3 }` for rounded corners on rectangles
|
||||
- Include `cameraUpdate` as the first element to frame the view (MCP rendering only)
|
||||
- Use arrow bindings (`startBinding`/`endBinding`) to connect shapes
|
||||
|
||||
### Step 2: Render with Excalidraw MCP
|
||||
|
||||
Call `mcp__excalidraw__create_view` with the element JSON array. This renders an interactive preview in the Claude Code UI.
|
||||
|
||||
```
|
||||
mcp__excalidraw__create_view({ elements: "<JSON array string>" })
|
||||
```
|
||||
|
||||
The response includes a `checkpointId` for retrieving the rendered state.
|
||||
|
||||
### Step 3: Extract the Checkpoint Data
|
||||
|
||||
Call `mcp__excalidraw__read_checkpoint` with the checkpoint ID to get the full element JSON back.
|
||||
|
||||
```
|
||||
mcp__excalidraw__read_checkpoint({ id: "<checkpointId>" })
|
||||
```
|
||||
|
||||
### Step 4: Convert Checkpoint to .excalidraw File
|
||||
|
||||
Use the `convert.mjs` script to transform raw MCP checkpoint JSON into a valid `.excalidraw` file. This handles all the tedious parts automatically:
|
||||
|
||||
- Filters out pseudo-elements (`cameraUpdate`, `delete`, `restoreCheckpoint`)
|
||||
- Adds required Excalidraw defaults (`seed`, `version`, `fontFamily`, etc.)
|
||||
- Expands `label` properties on shapes/arrows into proper bound text elements
|
||||
|
||||
```bash
|
||||
# Save checkpoint JSON to a temp file, then convert to the project's image directory:
|
||||
node <skill-path>/scripts/convert.mjs /tmp/excalidraw-export/raw.json docs/images/my-diagram.excalidraw
|
||||
```
|
||||
|
||||
The input JSON should be the raw checkpoint data from `mcp__excalidraw__read_checkpoint` (the `{"elements": [...]}` object). The output `.excalidraw` file goes in the project's image directory (see File Location Convention above).
|
||||
|
||||
**For batch exports**: Write each checkpoint to a separate raw JSON file, then convert each one:
|
||||
```bash
|
||||
node <skill-path>/scripts/convert.mjs raw1.json diagram1.excalidraw
|
||||
node <skill-path>/scripts/convert.mjs raw2.json diagram2.excalidraw
|
||||
```
|
||||
|
||||
**Manual alternative**: If you need to write the `.excalidraw` file by hand (e.g., without the convert script), each element needs these defaults:
|
||||
|
||||
```
|
||||
angle: 0, roughness: 1, opacity: 100, groupIds: [], seed: <unique int>,
|
||||
version: 1, versionNonce: <unique int>, isDeleted: false,
|
||||
boundElements: null, link: null, locked: false
|
||||
```
|
||||
|
||||
Text elements also need: `fontFamily: 1, textAlign: "left", verticalAlign: "top", baseline: 14, containerId: null, originalText: "<same as text>"`
|
||||
|
||||
Bound text (labels on shapes/arrows) needs: `containerId: "<parent-id>"`, `textAlign: "center"`, `verticalAlign: "middle"`, and the parent needs `boundElements: [{"id": "<text-id>", "type": "text"}]`.
|
||||
|
||||
### Step 5: Export to PNG
|
||||
|
||||
Run the export script. Determine the runtime path relative to this skill's scripts directory:
|
||||
|
||||
```bash
|
||||
cd <skill-path>/scripts/.export-runtime && node <skill-path>/scripts/export_png.mjs docs/images/my-diagram.excalidraw docs/images/my-diagram.png
|
||||
```
|
||||
|
||||
The script:
|
||||
1. Starts a local HTTP server serving the `.excalidraw` file and an HTML page
|
||||
2. Launches headless Chromium via Playwright
|
||||
3. The HTML page loads the Excalidraw library from esm.sh (library code only, not user data)
|
||||
4. Calls `exportToBlob` on the local diagram data
|
||||
5. Extracts the base64 PNG and writes it to disk
|
||||
6. Cleans up temp files and exits
|
||||
|
||||
The script prints the output path on success. Verify the result with `file <output.png>`.
|
||||
|
||||
### Step 5.5: Validate and Iterate
|
||||
|
||||
Run the validation script on the `.excalidraw` file to catch spatial issues:
|
||||
|
||||
```bash
|
||||
node <skill-path>/scripts/validate.mjs docs/images/my-diagram.excalidraw
|
||||
```
|
||||
|
||||
Then read the exported PNG back using the Read tool to visually inspect:
|
||||
|
||||
1. All label text fits within its container (no overflow/clipping)
|
||||
2. No arrows cross over text labels
|
||||
3. Spacing between elements is consistent
|
||||
4. Legend and titles are properly positioned
|
||||
|
||||
If the validation script or visual inspection reveals issues:
|
||||
1. Identify the specific elements that need adjustment
|
||||
2. Edit the `.excalidraw` file (adjust coordinates, box sizes, or arrow waypoints)
|
||||
3. Re-run the export script (Step 5)
|
||||
4. Re-validate
|
||||
|
||||
### Step 6: Deliver the Result
|
||||
|
||||
Read the PNG file to display it to the user. Provide the file path so the user can access it directly.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Setup fails**: Verify Node.js v18+ is installed (`node --version`). Ensure npm has network access for the initial Playwright/Chromium download.
|
||||
|
||||
**Export times out**: The HTML page has a 30-second timeout. If it fails, check browser console output in the script's error messages. Common cause: esm.sh CDN is temporarily slow on first load.
|
||||
|
||||
**Blank PNG**: Ensure elements include all required properties (see Step 4 defaults). Missing `seed`, `version`, or `fontFamily` on text elements can cause silent render failures.
|
||||
|
||||
**"READY" never fires**: The `exportToBlob` call requires valid elements. Filter out `cameraUpdate` and other pseudo-elements before writing the `.excalidraw` file.
|
||||
@@ -0,0 +1,149 @@
|
||||
# Excalidraw Element Format Reference
|
||||
|
||||
This reference documents the element JSON format accepted by the Excalidraw MCP `create_view` tool and the `export_png.mjs` script.
|
||||
|
||||
## Color Palette
|
||||
|
||||
### Primary Colors
|
||||
| Name | Hex | Use |
|
||||
|------|-----|-----|
|
||||
| Blue | `#4a9eed` | Primary actions, links |
|
||||
| Amber | `#f59e0b` | Warnings, highlights |
|
||||
| Green | `#22c55e` | Success, positive |
|
||||
| Red | `#ef4444` | Errors, negative |
|
||||
| Purple | `#8b5cf6` | Accents, special |
|
||||
| Pink | `#ec4899` | Decorative |
|
||||
| Cyan | `#06b6d4` | Info, secondary |
|
||||
|
||||
### Fill Colors (pastel, for shape backgrounds)
|
||||
| Color | Hex | Good For |
|
||||
|-------|-----|----------|
|
||||
| Light Blue | `#a5d8ff` | Input, sources, primary |
|
||||
| Light Green | `#b2f2bb` | Success, output |
|
||||
| Light Orange | `#ffd8a8` | Warning, pending |
|
||||
| Light Purple | `#d0bfff` | Processing, middleware |
|
||||
| Light Red | `#ffc9c9` | Error, critical |
|
||||
| Light Yellow | `#fff3bf` | Notes, decisions |
|
||||
| Light Teal | `#c3fae8` | Storage, data |
|
||||
|
||||
## Element Types
|
||||
|
||||
### Required Fields (all elements)
|
||||
`type`, `id` (unique string), `x`, `y`, `width`, `height`
|
||||
|
||||
### Defaults (skip these)
|
||||
strokeColor="#1e1e1e", backgroundColor="transparent", fillStyle="solid", strokeWidth=2, roughness=1, opacity=100
|
||||
|
||||
### Shapes
|
||||
|
||||
**Rectangle**: `{ "type": "rectangle", "id": "r1", "x": 100, "y": 100, "width": 200, "height": 100 }`
|
||||
- `roundness: { type: 3 }` for rounded corners
|
||||
- `backgroundColor: "#a5d8ff"`, `fillStyle: "solid"` for filled
|
||||
|
||||
**Ellipse**: `{ "type": "ellipse", "id": "e1", "x": 100, "y": 100, "width": 150, "height": 150 }`
|
||||
|
||||
**Diamond**: `{ "type": "diamond", "id": "d1", "x": 100, "y": 100, "width": 150, "height": 150 }`
|
||||
|
||||
### Labels
|
||||
|
||||
**Labeled shape (preferred)**: Add `label` to any shape for auto-centered text.
|
||||
```json
|
||||
{ "type": "rectangle", "id": "r1", "x": 100, "y": 100, "width": 200, "height": 80, "label": { "text": "Hello", "fontSize": 20 } }
|
||||
```
|
||||
|
||||
**Standalone text** (titles, annotations only):
|
||||
```json
|
||||
{ "type": "text", "id": "t1", "x": 150, "y": 138, "text": "Hello", "fontSize": 20 }
|
||||
```
|
||||
|
||||
### Arrows
|
||||
|
||||
```json
|
||||
{ "type": "arrow", "id": "a1", "x": 300, "y": 150, "width": 200, "height": 0, "points": [[0,0],[200,0]], "endArrowhead": "arrow" }
|
||||
```
|
||||
|
||||
**Bindings** connect arrows to shapes:
|
||||
```json
|
||||
"startBinding": { "elementId": "r1", "fixedPoint": [1, 0.5] }
|
||||
```
|
||||
fixedPoint: top=[0.5,0], bottom=[0.5,1], left=[0,0.5], right=[1,0.5]
|
||||
|
||||
**Labeled arrow**: `"label": { "text": "connects" }`
|
||||
|
||||
### Camera (MCP only, not exported to PNG)
|
||||
|
||||
```json
|
||||
{ "type": "cameraUpdate", "width": 800, "height": 600, "x": 0, "y": 0 }
|
||||
```
|
||||
|
||||
Camera sizes must be 4:3 ratio. The export script filters these out automatically.
|
||||
|
||||
## Sizing Rules
|
||||
|
||||
### Container-to-text ratios
|
||||
- Box width >= estimated_text_width * 1.4 (40% horizontal margin)
|
||||
- Box height >= estimated_text_height * 1.5 (50% vertical margin)
|
||||
- Minimum box size: 150x60 for single-line labels, 200x80 for multi-line
|
||||
|
||||
### Font size constraints
|
||||
- Labels inside containers: max fontSize 14
|
||||
- Service/zone titles: fontSize 18-22
|
||||
- Standalone annotations: fontSize 12-14
|
||||
- Never exceed fontSize 16 inside a box smaller than 300px wide
|
||||
|
||||
### Padding
|
||||
- Minimum 15px padding on each side between text and container edge
|
||||
- For multi-line text, add 8px vertical padding per line beyond the first
|
||||
|
||||
### General
|
||||
- Leave 20-30px gaps between elements
|
||||
|
||||
## Label Content Guidelines
|
||||
|
||||
### Keep labels short
|
||||
- Maximum 2 lines per label inside shapes
|
||||
- Maximum 25 characters per line
|
||||
- If label needs 3+ lines, split: short name in box, details as annotation below
|
||||
|
||||
### Label patterns
|
||||
- Service box: "Service Name" (1 line) or "Service Name\nBrief role" (2 lines)
|
||||
- Component box: "Component Name" (1 line)
|
||||
- Detail text: Use standalone text elements positioned below/beside the box
|
||||
|
||||
### Bad vs Good
|
||||
BAD: label "Auth-MS\nOAuth tokens, credentials\n800-1K req/s, <100ms" (3 lines, 30+ chars)
|
||||
GOOD: label "Auth-MS\nOAuth token management" (2 lines, 22 chars max)
|
||||
+ standalone text below: "800-1K req/s, <100ms p99"
|
||||
|
||||
## Arrow Routing Rules
|
||||
|
||||
### Gutter-based routing
|
||||
- Define horizontal and vertical gutters (20-30px gaps between service zones)
|
||||
- Route arrows through gutters, never over content areas
|
||||
- Use right-angle waypoints along zone edges
|
||||
|
||||
### Waypoint placement
|
||||
- Start/end points: attach to box edges using fixedPoint bindings
|
||||
- Mid-waypoints: offset 20px from nearest box edge
|
||||
- For crossing traffic: stagger parallel arrows by 10px
|
||||
|
||||
### Vertical vs horizontal preference
|
||||
- Prefer horizontal arrows for same-tier connections
|
||||
- Prefer vertical arrows for cross-tier flows (consumer -> service -> external)
|
||||
- Diagonal arrows only when routing around would add 3+ waypoints
|
||||
|
||||
### Label placement on arrows
|
||||
- Arrow labels should sit in empty space, not over boxes
|
||||
- For vertical arrows: place label to the left or right, offset 15px
|
||||
- For horizontal arrows: place label above, offset 10px
|
||||
|
||||
## Example: Two Connected Boxes
|
||||
|
||||
```json
|
||||
[
|
||||
{ "type": "cameraUpdate", "width": 800, "height": 600, "x": 50, "y": 50 },
|
||||
{ "type": "rectangle", "id": "b1", "x": 100, "y": 100, "width": 200, "height": 100, "roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid", "label": { "text": "Start", "fontSize": 20 } },
|
||||
{ "type": "rectangle", "id": "b2", "x": 450, "y": 100, "width": 200, "height": 100, "roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid", "label": { "text": "End", "fontSize": 20 } },
|
||||
{ "type": "arrow", "id": "a1", "x": 300, "y": 150, "width": 150, "height": 0, "points": [[0,0],[150,0]], "endArrowhead": "arrow", "startBinding": { "elementId": "b1", "fixedPoint": [1, 0.5] }, "endBinding": { "elementId": "b2", "fixedPoint": [0, 0.5] } }
|
||||
]
|
||||
```
|
||||
2
plugins/compound-engineering/skills/excalidraw-png-export/scripts/.gitignore
vendored
Normal file
2
plugins/compound-engineering/skills/excalidraw-png-export/scripts/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
.export-runtime/
|
||||
.export-tmp/
|
||||
178
plugins/compound-engineering/skills/excalidraw-png-export/scripts/convert.mjs
Executable file
178
plugins/compound-engineering/skills/excalidraw-png-export/scripts/convert.mjs
Executable file
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Convert raw Excalidraw MCP checkpoint JSON into a valid .excalidraw file.
|
||||
* Filters pseudo-elements, adds required defaults, expands labels into bound text.
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { createRequire } from 'module';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const runtimeRequire = createRequire(join(__dirname, '.export-runtime', 'package.json'));
|
||||
|
||||
// Canvas-based text measurement with graceful fallback to heuristic.
|
||||
// Excalidraw renders with Virgil (hand-drawn font); system sans-serif
|
||||
// is a reasonable proxy. The 1.1x multiplier accounts for Virgil being wider.
|
||||
let measureText;
|
||||
try {
|
||||
const canvas = runtimeRequire('canvas');
|
||||
const { createCanvas } = canvas;
|
||||
const cvs = createCanvas(1, 1);
|
||||
const ctx = cvs.getContext('2d');
|
||||
measureText = (text, fontSize) => {
|
||||
ctx.font = `${fontSize}px sans-serif`;
|
||||
const lines = text.split('\n');
|
||||
const widths = lines.map(line => ctx.measureText(line).width * 1.1);
|
||||
return {
|
||||
width: Math.max(...widths),
|
||||
height: lines.length * (fontSize * 1.25),
|
||||
};
|
||||
};
|
||||
} catch {
|
||||
console.warn('WARN: canvas not available, using heuristic text sizing (install canvas for accurate measurement)');
|
||||
measureText = (text, fontSize) => {
|
||||
const lines = text.split('\n');
|
||||
return {
|
||||
width: Math.max(...lines.map(l => l.length)) * fontSize * 0.55,
|
||||
height: lines.length * (fontSize + 4),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const [,, inputFile, outputFile] = process.argv;
|
||||
if (!inputFile || !outputFile) {
|
||||
console.error('Usage: node convert.mjs <input.json> <output.excalidraw>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const raw = JSON.parse(readFileSync(inputFile, 'utf8'));
|
||||
const elements = raw.elements || raw;
|
||||
|
||||
let seed = 1000;
|
||||
const nextSeed = () => seed++;
|
||||
|
||||
const processed = [];
|
||||
|
||||
for (const el of elements) {
|
||||
if (['cameraUpdate', 'delete', 'restoreCheckpoint'].includes(el.type)) continue;
|
||||
|
||||
const base = {
|
||||
angle: 0,
|
||||
roughness: 1,
|
||||
opacity: el.opacity ?? 100,
|
||||
groupIds: [],
|
||||
seed: nextSeed(),
|
||||
version: 1,
|
||||
versionNonce: nextSeed(),
|
||||
isDeleted: false,
|
||||
boundElements: null,
|
||||
link: null,
|
||||
locked: false,
|
||||
strokeColor: el.strokeColor || '#1e1e1e',
|
||||
backgroundColor: el.backgroundColor || 'transparent',
|
||||
fillStyle: el.fillStyle || 'solid',
|
||||
strokeWidth: el.strokeWidth ?? 2,
|
||||
strokeStyle: el.strokeStyle || 'solid',
|
||||
};
|
||||
|
||||
if (el.type === 'text') {
|
||||
const fontSize = el.fontSize || 16;
|
||||
const measured = measureText(el.text, fontSize);
|
||||
processed.push({
|
||||
...base,
|
||||
type: 'text',
|
||||
id: el.id,
|
||||
x: el.x,
|
||||
y: el.y,
|
||||
width: measured.width,
|
||||
height: measured.height,
|
||||
text: el.text,
|
||||
fontSize, fontFamily: 1,
|
||||
textAlign: 'left',
|
||||
verticalAlign: 'top',
|
||||
baseline: fontSize,
|
||||
containerId: null,
|
||||
originalText: el.text,
|
||||
});
|
||||
} else if (el.type === 'arrow') {
|
||||
const arrowEl = {
|
||||
...base,
|
||||
type: 'arrow',
|
||||
id: el.id,
|
||||
x: el.x,
|
||||
y: el.y,
|
||||
width: el.width || 0,
|
||||
height: el.height || 0,
|
||||
points: el.points || [[0, 0]],
|
||||
startArrowhead: el.startArrowhead || null,
|
||||
endArrowhead: el.endArrowhead ?? 'arrow',
|
||||
startBinding: el.startBinding ? { ...el.startBinding, focus: 0, gap: 5 } : null,
|
||||
endBinding: el.endBinding ? { ...el.endBinding, focus: 0, gap: 5 } : null,
|
||||
roundness: { type: 2 },
|
||||
boundElements: [],
|
||||
};
|
||||
processed.push(arrowEl);
|
||||
|
||||
if (el.label) {
|
||||
const labelId = el.id + '_label';
|
||||
const text = el.label.text || '';
|
||||
const fontSize = el.label.fontSize || 14;
|
||||
const { width: w, height: h } = measureText(text, fontSize);
|
||||
const midPt = el.points[Math.floor(el.points.length / 2)] || [0, 0];
|
||||
|
||||
processed.push({
|
||||
...base,
|
||||
type: 'text', id: labelId,
|
||||
x: el.x + midPt[0] - w / 2,
|
||||
y: el.y + midPt[1] - h / 2 - 12,
|
||||
width: w, height: h,
|
||||
text, fontSize, fontFamily: 1,
|
||||
textAlign: 'center', verticalAlign: 'middle',
|
||||
baseline: fontSize, containerId: el.id, originalText: text,
|
||||
strokeColor: el.strokeColor || '#1e1e1e',
|
||||
backgroundColor: 'transparent',
|
||||
});
|
||||
arrowEl.boundElements = [{ id: labelId, type: 'text' }];
|
||||
}
|
||||
} else if (['rectangle', 'ellipse', 'diamond'].includes(el.type)) {
|
||||
const shapeEl = {
|
||||
...base,
|
||||
type: el.type, id: el.id,
|
||||
x: el.x, y: el.y, width: el.width, height: el.height,
|
||||
roundness: el.roundness || null,
|
||||
boundElements: [],
|
||||
};
|
||||
processed.push(shapeEl);
|
||||
|
||||
if (el.label) {
|
||||
const labelId = el.id + '_label';
|
||||
const text = el.label.text || '';
|
||||
const fontSize = el.label.fontSize || 16;
|
||||
const { width: w, height: h } = measureText(text, fontSize);
|
||||
|
||||
processed.push({
|
||||
...base,
|
||||
type: 'text', id: labelId,
|
||||
x: el.x + (el.width - w) / 2,
|
||||
y: el.y + (el.height - h) / 2,
|
||||
width: w, height: h,
|
||||
text, fontSize, fontFamily: 1,
|
||||
textAlign: 'center', verticalAlign: 'middle',
|
||||
baseline: fontSize, containerId: el.id, originalText: text,
|
||||
strokeColor: el.strokeColor || '#1e1e1e',
|
||||
backgroundColor: 'transparent',
|
||||
});
|
||||
shapeEl.boundElements = [{ id: labelId, type: 'text' }];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeFileSync(outputFile, JSON.stringify({
|
||||
type: 'excalidraw', version: 2, source: 'claude-code',
|
||||
elements: processed,
|
||||
appState: { exportBackground: true, viewBackgroundColor: '#ffffff' },
|
||||
files: {},
|
||||
}, null, 2));
|
||||
|
||||
console.log(`Wrote ${processed.length} elements to ${outputFile}`);
|
||||
@@ -0,0 +1,61 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body { margin: 0; background: white; }
|
||||
#root { width: 900px; height: 400px; }
|
||||
</style>
|
||||
<script>
|
||||
window.EXCALIDRAW_ASSET_PATH = "https://esm.sh/@excalidraw/excalidraw/dist/prod/";
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"react": "https://esm.sh/react@18",
|
||||
"react-dom": "https://esm.sh/react-dom@18",
|
||||
"react-dom/client": "https://esm.sh/react-dom@18/client",
|
||||
"react/jsx-runtime": "https://esm.sh/react@18/jsx-runtime",
|
||||
"@excalidraw/excalidraw": "https://esm.sh/@excalidraw/excalidraw@0.18.0?external=react,react-dom"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="module">
|
||||
import { exportToBlob } from "@excalidraw/excalidraw";
|
||||
|
||||
async function run() {
|
||||
const resp = await fetch("./diagram.excalidraw");
|
||||
const data = await resp.json();
|
||||
|
||||
const validTypes = ["rectangle","ellipse","diamond","text","arrow","line","freedraw","image","frame"];
|
||||
const elements = data.elements.filter(el => validTypes.includes(el.type));
|
||||
|
||||
const blob = await exportToBlob({
|
||||
elements,
|
||||
appState: {
|
||||
exportBackground: true,
|
||||
viewBackgroundColor: data.appState?.viewBackgroundColor || "#ffffff",
|
||||
exportWithDarkMode: data.appState?.exportWithDarkMode || false,
|
||||
},
|
||||
files: data.files || {},
|
||||
getDimensions: (w, h) => ({ width: w * 2, height: h * 2, scale: 2 }),
|
||||
});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
window.__PNG_DATA__ = reader.result;
|
||||
document.title = "READY";
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
}
|
||||
|
||||
run().catch(e => {
|
||||
console.error("EXPORT ERROR:", e);
|
||||
document.title = "ERROR:" + e.message;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Export an Excalidraw JSON file to PNG using Playwright + the official Excalidraw library.
|
||||
*
|
||||
* Usage: node export_png.mjs <input.excalidraw> [output.png]
|
||||
*
|
||||
* All rendering happens locally. Diagram data never leaves the machine.
|
||||
* The Excalidraw JS library is fetched from esm.sh CDN (code only, not user data).
|
||||
*/
|
||||
|
||||
import { createRequire } from "module";
|
||||
import { readFileSync, writeFileSync, copyFileSync } from "fs";
|
||||
import { createServer } from "http";
|
||||
import { join, extname, dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const RUNTIME_DIR = join(__dirname, ".export-runtime");
|
||||
const HTML_PATH = join(__dirname, "export.html");
|
||||
|
||||
// Resolve playwright from the runtime directory, not the script's location
|
||||
const require = createRequire(join(RUNTIME_DIR, "node_modules", "playwright", "index.mjs"));
|
||||
const { chromium } = await import(join(RUNTIME_DIR, "node_modules", "playwright", "index.mjs"));
|
||||
|
||||
const inputPath = process.argv[2];
|
||||
if (!inputPath) {
|
||||
console.error("Usage: node export_png.mjs <input.excalidraw> [output.png]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const outputPath = process.argv[3] || inputPath.replace(/\.excalidraw$/, ".png");
|
||||
|
||||
// Set up a temp serving directory
|
||||
const SERVE_DIR = join(__dirname, ".export-tmp");
|
||||
const { mkdirSync, rmSync } = await import("fs");
|
||||
mkdirSync(SERVE_DIR, { recursive: true });
|
||||
copyFileSync(HTML_PATH, join(SERVE_DIR, "export.html"));
|
||||
copyFileSync(inputPath, join(SERVE_DIR, "diagram.excalidraw"));
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html",
|
||||
".json": "application/json",
|
||||
".excalidraw": "application/json",
|
||||
};
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const file = join(SERVE_DIR, req.url === "/" ? "export.html" : req.url);
|
||||
try {
|
||||
const data = readFileSync(file);
|
||||
res.writeHead(200, { "Content-Type": MIME[extname(file)] || "application/octet-stream" });
|
||||
res.end(data);
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end("Not found");
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(0, "127.0.0.1", async () => {
|
||||
const port = server.address().port;
|
||||
|
||||
let browser;
|
||||
try {
|
||||
browser = await chromium.launch({ headless: true });
|
||||
const page = await browser.newPage();
|
||||
|
||||
page.on("pageerror", err => console.error("Page error:", err.message));
|
||||
|
||||
await page.goto(`http://127.0.0.1:${port}`);
|
||||
|
||||
await page.waitForFunction(
|
||||
() => document.title.startsWith("READY") || document.title.startsWith("ERROR"),
|
||||
{ timeout: 30000 }
|
||||
);
|
||||
|
||||
const title = await page.title();
|
||||
if (title.startsWith("ERROR")) {
|
||||
console.error("Export failed:", title);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const dataUrl = await page.evaluate(() => window.__PNG_DATA__);
|
||||
const base64 = dataUrl.replace(/^data:image\/png;base64,/, "");
|
||||
writeFileSync(outputPath, Buffer.from(base64, "base64"));
|
||||
console.log(outputPath);
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
server.close();
|
||||
rmSync(SERVE_DIR, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
37
plugins/compound-engineering/skills/excalidraw-png-export/scripts/setup.sh
Executable file
37
plugins/compound-engineering/skills/excalidraw-png-export/scripts/setup.sh
Executable file
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
# First-time setup for excalidraw-png-export skill.
|
||||
# Installs playwright and chromium headless into a dedicated directory.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
EXPORT_DIR="$SCRIPT_DIR/.export-runtime"
|
||||
|
||||
if [ -d "$EXPORT_DIR/node_modules/playwright" ]; then
|
||||
echo "Runtime already installed at $EXPORT_DIR"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Installing excalidraw-png-export runtime..."
|
||||
mkdir -p "$EXPORT_DIR"
|
||||
cd "$EXPORT_DIR"
|
||||
|
||||
# Initialize package.json with ESM support
|
||||
cat > package.json << 'PACKAGEEOF'
|
||||
{
|
||||
"name": "excalidraw-export-runtime",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"private": true
|
||||
}
|
||||
PACKAGEEOF
|
||||
|
||||
npm install playwright 2>&1
|
||||
npx playwright install chromium 2>&1
|
||||
|
||||
# canvas provides accurate text measurement for convert.mjs.
|
||||
# Requires Cairo native library: brew install pkg-config cairo pango libpng jpeg giflib librsvg
|
||||
# Falls back to heuristic sizing if unavailable.
|
||||
npm install canvas 2>&1 || echo "WARN: canvas install failed (missing Cairo?). Heuristic text sizing will be used."
|
||||
|
||||
echo "Setup complete. Runtime installed at $EXPORT_DIR"
|
||||
173
plugins/compound-engineering/skills/excalidraw-png-export/scripts/validate.mjs
Executable file
173
plugins/compound-engineering/skills/excalidraw-png-export/scripts/validate.mjs
Executable file
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Spatial validation for .excalidraw files.
|
||||
* Checks text overflow, arrow-text collisions, and element overlap.
|
||||
* Usage: node validate.mjs <input.excalidraw>
|
||||
*/
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const MIN_PADDING = 15;
|
||||
|
||||
const inputFile = process.argv[2];
|
||||
if (!inputFile) {
|
||||
console.error('Usage: node validate.mjs <input.excalidraw>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const data = JSON.parse(readFileSync(inputFile, 'utf8'));
|
||||
const elements = data.elements || data;
|
||||
|
||||
// Build element map
|
||||
const elMap = new Map();
|
||||
for (const el of elements) {
|
||||
if (el.isDeleted) continue;
|
||||
elMap.set(el.id, el);
|
||||
}
|
||||
|
||||
let warnings = 0;
|
||||
let errors = 0;
|
||||
const checked = elements.filter(el => !el.isDeleted).length;
|
||||
|
||||
// --- Check 1: Text overflow within containers ---
|
||||
// Skip arrow-bound labels — arrows are lines, not spatial containers.
|
||||
for (const el of elements) {
|
||||
if (el.isDeleted || el.type !== 'text' || !el.containerId) continue;
|
||||
const parent = elMap.get(el.containerId);
|
||||
if (!parent || parent.type === 'arrow') continue;
|
||||
|
||||
const textRight = el.x + el.width;
|
||||
const textBottom = el.y + el.height;
|
||||
const parentRight = parent.x + parent.width;
|
||||
const parentBottom = parent.y + parent.height;
|
||||
|
||||
const paddingLeft = el.x - parent.x;
|
||||
const paddingRight = parentRight - textRight;
|
||||
const paddingTop = el.y - parent.y;
|
||||
const paddingBottom = parentBottom - textBottom;
|
||||
|
||||
const overflows = [];
|
||||
if (paddingLeft < MIN_PADDING) overflows.push(`left=${paddingLeft.toFixed(1)}px (need ${MIN_PADDING}px)`);
|
||||
if (paddingRight < MIN_PADDING) overflows.push(`right=${paddingRight.toFixed(1)}px (need ${MIN_PADDING}px)`);
|
||||
if (paddingTop < MIN_PADDING) overflows.push(`top=${paddingTop.toFixed(1)}px (need ${MIN_PADDING}px)`);
|
||||
if (paddingBottom < MIN_PADDING) overflows.push(`bottom=${paddingBottom.toFixed(1)}px (need ${MIN_PADDING}px)`);
|
||||
|
||||
if (overflows.length > 0) {
|
||||
const label = (el.text || '').replace(/\n/g, '\\n');
|
||||
const truncated = label.length > 40 ? label.slice(0, 37) + '...' : label;
|
||||
console.log(`WARN: text "${truncated}" (id=${el.id}) tight/overflow in container (id=${el.containerId})`);
|
||||
console.log(` text_bbox=[${el.x.toFixed(0)},${el.y.toFixed(0)}]->[${textRight.toFixed(0)},${textBottom.toFixed(0)}]`);
|
||||
console.log(` container_bbox=[${parent.x.toFixed(0)},${parent.y.toFixed(0)}]->[${parentRight.toFixed(0)},${parentBottom.toFixed(0)}]`);
|
||||
console.log(` insufficient padding: ${overflows.join(', ')}`);
|
||||
console.log();
|
||||
warnings++;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Check 2: Arrow-text collisions ---
|
||||
|
||||
/** Check if line segment (p1->p2) intersects axis-aligned rectangle. */
|
||||
function segmentIntersectsRect(p1, p2, rect) {
|
||||
// rect = {x, y, w, h} -> min/max
|
||||
const rxMin = rect.x;
|
||||
const rxMax = rect.x + rect.w;
|
||||
const ryMin = rect.y;
|
||||
const ryMax = rect.y + rect.h;
|
||||
|
||||
// Cohen-Sutherland-style clipping
|
||||
let [x1, y1] = [p1[0], p1[1]];
|
||||
let [x2, y2] = [p2[0], p2[1]];
|
||||
|
||||
function outcode(x, y) {
|
||||
let code = 0;
|
||||
if (x < rxMin) code |= 1;
|
||||
else if (x > rxMax) code |= 2;
|
||||
if (y < ryMin) code |= 4;
|
||||
else if (y > ryMax) code |= 8;
|
||||
return code;
|
||||
}
|
||||
|
||||
let code1 = outcode(x1, y1);
|
||||
let code2 = outcode(x2, y2);
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
if (!(code1 | code2)) return true; // both inside
|
||||
if (code1 & code2) return false; // both outside same side
|
||||
|
||||
const codeOut = code1 || code2;
|
||||
let x, y;
|
||||
if (codeOut & 8) { y = ryMax; x = x1 + (x2 - x1) * (ryMax - y1) / (y2 - y1); }
|
||||
else if (codeOut & 4) { y = ryMin; x = x1 + (x2 - x1) * (ryMin - y1) / (y2 - y1); }
|
||||
else if (codeOut & 2) { x = rxMax; y = y1 + (y2 - y1) * (rxMax - x1) / (x2 - x1); }
|
||||
else { x = rxMin; y = y1 + (y2 - y1) * (rxMin - x1) / (x2 - x1); }
|
||||
|
||||
if (codeOut === code1) { x1 = x; y1 = y; code1 = outcode(x1, y1); }
|
||||
else { x2 = x; y2 = y; code2 = outcode(x2, y2); }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Collect text bounding boxes (excluding arrow-bound labels for their own arrow)
|
||||
const textBoxes = [];
|
||||
for (const el of elements) {
|
||||
if (el.isDeleted || el.type !== 'text') continue;
|
||||
textBoxes.push({
|
||||
id: el.id,
|
||||
containerId: el.containerId,
|
||||
text: (el.text || '').replace(/\n/g, '\\n'),
|
||||
rect: { x: el.x, y: el.y, w: el.width, h: el.height },
|
||||
});
|
||||
}
|
||||
|
||||
for (const el of elements) {
|
||||
if (el.isDeleted || el.type !== 'arrow') continue;
|
||||
if (!el.points || el.points.length < 2) continue;
|
||||
|
||||
// Compute absolute points
|
||||
const absPoints = el.points.map(p => [el.x + p[0], el.y + p[1]]);
|
||||
|
||||
for (const tb of textBoxes) {
|
||||
// Skip this arrow's own label
|
||||
if (tb.containerId === el.id) continue;
|
||||
|
||||
for (let i = 0; i < absPoints.length - 1; i++) {
|
||||
if (segmentIntersectsRect(absPoints[i], absPoints[i + 1], tb.rect)) {
|
||||
const truncated = tb.text.length > 30 ? tb.text.slice(0, 27) + '...' : tb.text;
|
||||
const seg = `[${absPoints[i].map(n => n.toFixed(0)).join(',')}]->[${absPoints[i + 1].map(n => n.toFixed(0)).join(',')}]`;
|
||||
console.log(`WARN: arrow (id=${el.id}) segment ${seg} crosses text "${truncated}" (id=${tb.id})`);
|
||||
console.log(` text_bbox=[${tb.rect.x.toFixed(0)},${tb.rect.y.toFixed(0)}]->[${(tb.rect.x + tb.rect.w).toFixed(0)},${(tb.rect.y + tb.rect.h).toFixed(0)}]`);
|
||||
console.log();
|
||||
warnings++;
|
||||
break; // one warning per arrow-text pair
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Check 3: Element overlap (non-child, same depth) ---
|
||||
const topLevel = elements.filter(el =>
|
||||
!el.isDeleted && !el.containerId && el.type !== 'text' && el.type !== 'arrow'
|
||||
);
|
||||
|
||||
for (let i = 0; i < topLevel.length; i++) {
|
||||
for (let j = i + 1; j < topLevel.length; j++) {
|
||||
const a = topLevel[i];
|
||||
const b = topLevel[j];
|
||||
|
||||
const aRight = a.x + a.width;
|
||||
const aBottom = a.y + a.height;
|
||||
const bRight = b.x + b.width;
|
||||
const bBottom = b.y + b.height;
|
||||
|
||||
if (a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y) {
|
||||
const overlapX = Math.min(aRight, bRight) - Math.max(a.x, b.x);
|
||||
const overlapY = Math.min(aBottom, bBottom) - Math.max(a.y, b.y);
|
||||
console.log(`WARN: overlap between (id=${a.id}) and (id=${b.id}): ${overlapX.toFixed(0)}x${overlapY.toFixed(0)}px`);
|
||||
console.log();
|
||||
warnings++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Summary ---
|
||||
console.log(`OK: ${checked} elements checked, ${warnings} warning(s), ${errors} error(s)`);
|
||||
process.exit(warnings > 0 ? 1 : 0);
|
||||
221
plugins/compound-engineering/skills/fastapi-style/SKILL.md
Normal file
221
plugins/compound-engineering/skills/fastapi-style/SKILL.md
Normal file
@@ -0,0 +1,221 @@
|
||||
---
|
||||
name: fastapi-style
|
||||
description: This skill should be used when writing Python and FastAPI code following opinionated best practices. It applies when building APIs, creating Pydantic models, working with SQLAlchemy, or any FastAPI application. Triggers on FastAPI code generation, API design, refactoring requests, code review, or when discussing async Python patterns. Embodies thin routers, rich Pydantic models, dependency injection, async-first design, and the "explicit is better than implicit" philosophy.
|
||||
---
|
||||
|
||||
<objective>
|
||||
Apply opinionated FastAPI conventions to Python API code. This skill provides comprehensive domain expertise for building maintainable, performant FastAPI applications following established patterns from production codebases.
|
||||
</objective>
|
||||
|
||||
<essential_principles>
|
||||
## Core Philosophy
|
||||
|
||||
"Explicit is better than implicit. Simple is better than complex."
|
||||
|
||||
**The FastAPI Way:**
|
||||
- Thin routers, rich Pydantic models with validation
|
||||
- Dependency injection for everything
|
||||
- Async-first with SQLAlchemy 2.0
|
||||
- Type hints everywhere - let the tools help you
|
||||
- Settings via pydantic-settings, not raw env vars
|
||||
- Database-backed solutions where possible
|
||||
|
||||
**What to deliberately avoid:**
|
||||
- Flask patterns (global request context)
|
||||
- Django ORM in FastAPI (use SQLAlchemy 2.0)
|
||||
- Synchronous database calls (use async)
|
||||
- Manual JSON serialization (Pydantic handles it)
|
||||
- Global state (use dependency injection)
|
||||
- `*` imports (explicit imports only)
|
||||
- Circular imports (proper module structure)
|
||||
|
||||
**Development Philosophy:**
|
||||
- Type everything - mypy should pass
|
||||
- Fail fast with descriptive errors
|
||||
- Write-time validation over read-time checks
|
||||
- Database constraints complement Pydantic validation
|
||||
- Tests are documentation
|
||||
</essential_principles>
|
||||
|
||||
<intake>
|
||||
What are you working on?
|
||||
|
||||
1. **Routers** - Route organization, dependency injection, response models
|
||||
2. **Models** - Pydantic schemas, SQLAlchemy models, validation patterns
|
||||
3. **Database** - SQLAlchemy 2.0 async, Alembic migrations, transactions
|
||||
4. **Testing** - pytest, httpx TestClient, fixtures, async testing
|
||||
5. **Security** - OAuth2, JWT, permissions, CORS, rate limiting
|
||||
6. **Background Tasks** - Celery, ARQ, or FastAPI BackgroundTasks
|
||||
7. **Code Review** - Review code against FastAPI best practices
|
||||
8. **General Guidance** - Philosophy and conventions
|
||||
|
||||
**Specify a number or describe your task.**
|
||||
</intake>
|
||||
|
||||
<routing>
|
||||
|
||||
| Response | Reference to Read |
|
||||
|----------|-------------------|
|
||||
| 1, router, route, endpoint | [routers.md](./references/routers.md) |
|
||||
| 2, model, pydantic, schema, sqlalchemy | [models.md](./references/models.md) |
|
||||
| 3, database, db, alembic, migration, transaction | [database.md](./references/database.md) |
|
||||
| 4, test, testing, pytest, fixture | [testing.md](./references/testing.md) |
|
||||
| 5, security, auth, oauth, jwt, permission | [security.md](./references/security.md) |
|
||||
| 6, background, task, celery, arq, queue | [background_tasks.md](./references/background_tasks.md) |
|
||||
| 7, review | Read all references, then review code |
|
||||
| 8, general task | Read relevant references based on context |
|
||||
|
||||
**After reading relevant references, apply patterns to the user's code.**
|
||||
</routing>
|
||||
|
||||
<quick_reference>
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
app/
|
||||
├── main.py # FastAPI app creation, middleware
|
||||
├── config.py # Settings via pydantic-settings
|
||||
├── dependencies.py # Shared dependencies
|
||||
├── database.py # Database session, engine
|
||||
├── models/ # SQLAlchemy models
|
||||
│ ├── __init__.py
|
||||
│ ├── base.py # Base model class
|
||||
│ └── user.py
|
||||
├── schemas/ # Pydantic models
|
||||
│ ├── __init__.py
|
||||
│ └── user.py
|
||||
├── routers/ # API routers
|
||||
│ ├── __init__.py
|
||||
│ └── users.py
|
||||
├── services/ # Business logic (if needed)
|
||||
├── utils/ # Shared utilities
|
||||
└── tests/
|
||||
├── conftest.py # Fixtures
|
||||
└── test_users.py
|
||||
```
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
**Pydantic Schemas:**
|
||||
- `UserCreate` - input for creation
|
||||
- `UserUpdate` - input for updates (all fields Optional)
|
||||
- `UserRead` - output representation
|
||||
- `UserInDB` - internal with hashed password
|
||||
|
||||
**SQLAlchemy Models:** Singular nouns (`User`, `Item`, `Order`)
|
||||
|
||||
**Routers:** Plural resource names (`users.py`, `items.py`)
|
||||
|
||||
**Dependencies:** Verb phrases (`get_current_user`, `get_db_session`)
|
||||
|
||||
## Type Hints
|
||||
|
||||
```python
|
||||
# Always type function signatures
|
||||
async def get_user(
|
||||
user_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
...
|
||||
|
||||
# Use Annotated for dependency injection
|
||||
from typing import Annotated
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
DBSession = Annotated[AsyncSession, Depends(get_db)]
|
||||
```
|
||||
|
||||
## Response Patterns
|
||||
|
||||
```python
|
||||
# Explicit response_model
|
||||
@router.get("/users/{user_id}", response_model=UserRead)
|
||||
async def get_user(user_id: int, db: DBSession) -> User:
|
||||
...
|
||||
|
||||
# Status codes
|
||||
@router.post("/users", status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(...) -> UserRead:
|
||||
...
|
||||
|
||||
# Multiple response types
|
||||
@router.get("/users/{user_id}", responses={404: {"model": ErrorResponse}})
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
# Specific exceptions
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="User not found",
|
||||
)
|
||||
|
||||
# Custom exception handlers
|
||||
@app.exception_handler(ValidationError)
|
||||
async def validation_exception_handler(request, exc):
|
||||
return JSONResponse(status_code=422, content={"detail": exc.errors()})
|
||||
```
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
```python
|
||||
# Simple dependency
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session() as session:
|
||||
yield session
|
||||
|
||||
# Parameterized dependency
|
||||
def get_pagination(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
) -> dict:
|
||||
return {"skip": skip, "limit": limit}
|
||||
|
||||
# Class-based dependency
|
||||
class CommonQueryParams:
|
||||
def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
|
||||
self.q = q
|
||||
self.skip = skip
|
||||
self.limit = limit
|
||||
```
|
||||
</quick_reference>
|
||||
|
||||
<reference_index>
|
||||
## Domain Knowledge
|
||||
|
||||
All detailed patterns in `references/`:
|
||||
|
||||
| File | Topics |
|
||||
|------|--------|
|
||||
| [routers.md](./references/routers.md) | Route organization, dependency injection, response models, middleware, versioning |
|
||||
| [models.md](./references/models.md) | Pydantic schemas, SQLAlchemy models, validation, serialization, mixins |
|
||||
| [database.md](./references/database.md) | SQLAlchemy 2.0 async, Alembic migrations, transactions, connection pooling |
|
||||
| [testing.md](./references/testing.md) | pytest, httpx TestClient, fixtures, async testing, mocking patterns |
|
||||
| [security.md](./references/security.md) | OAuth2, JWT, permissions, CORS, rate limiting, secrets management |
|
||||
| [background_tasks.md](./references/background_tasks.md) | FastAPI BackgroundTasks, Celery, ARQ, task patterns |
|
||||
</reference_index>
|
||||
|
||||
<success_criteria>
|
||||
Code follows FastAPI best practices when:
|
||||
- Routers are thin, focused on HTTP concerns only
|
||||
- Pydantic models handle all validation and serialization
|
||||
- SQLAlchemy 2.0 async patterns used correctly
|
||||
- Dependencies injected, not imported as globals
|
||||
- Type hints on all function signatures
|
||||
- Settings via pydantic-settings
|
||||
- Tests use pytest with async support
|
||||
- Error handling is explicit and informative
|
||||
- Security follows OAuth2/JWT standards
|
||||
- Background tasks use appropriate tool for the job
|
||||
</success_criteria>
|
||||
|
||||
<credits>
|
||||
Based on FastAPI best practices from the official documentation, real-world production patterns, and the Python community's collective wisdom.
|
||||
|
||||
**Key Resources:**
|
||||
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy 2.0 Documentation](https://docs.sqlalchemy.org/)
|
||||
- [Pydantic V2 Documentation](https://docs.pydantic.dev/)
|
||||
</credits>
|
||||
@@ -45,6 +45,7 @@ Each todo is a markdown file with YAML frontmatter and structured sections. Use
|
||||
|
||||
**Required sections:**
|
||||
- **Problem Statement** - What is broken, missing, or needs improvement?
|
||||
- **Assessment (Pressure Test)** - For code review findings: verification results and engineering judgment
|
||||
- **Findings** - Investigation results, root cause, key discoveries
|
||||
- **Proposed Solutions** - Multiple options with pros/cons, effort, risk
|
||||
- **Recommended Action** - Clear plan (filled during triage)
|
||||
@@ -56,6 +57,12 @@ Each todo is a markdown file with YAML frontmatter and structured sections. Use
|
||||
- **Resources** - Links to errors, tests, PRs, documentation
|
||||
- **Notes** - Additional context or decisions
|
||||
|
||||
**Assessment section fields (for code review findings):**
|
||||
- Assessment: Clear & Correct | Unclear | Likely Incorrect | YAGNI
|
||||
- Recommended Action: Fix now | Clarify | Push back | Skip
|
||||
- Verified: Code, Tests, Usage, Prior Decisions (Yes/No with details)
|
||||
- Technical Justification: Why this finding is valid or should be skipped
|
||||
|
||||
**YAML frontmatter fields:**
|
||||
```yaml
|
||||
---
|
||||
|
||||
@@ -19,6 +19,22 @@ What is broken, missing, or needs improvement? Provide clear context about why t
|
||||
- Email service is missing proper error handling for rate-limit scenarios
|
||||
- Documentation doesn't cover the new authentication flow
|
||||
|
||||
## Assessment (Pressure Test)
|
||||
|
||||
*(For findings from code review or automated agents)*
|
||||
|
||||
| Criterion | Result |
|
||||
|-----------|--------|
|
||||
| **Assessment** | Clear & Correct / Unclear / Likely Incorrect / YAGNI |
|
||||
| **Recommended Action** | Fix now / Clarify / Push back / Skip |
|
||||
| **Verified Code?** | Yes/No - [what was checked] |
|
||||
| **Verified Tests?** | Yes/No - [existing coverage] |
|
||||
| **Verified Usage?** | Yes/No - [how code is used] |
|
||||
| **Prior Decisions?** | Yes/No - [any intentional design] |
|
||||
|
||||
**Technical Justification:**
|
||||
[If pushing back or marking YAGNI, provide specific technical reasoning. Reference codebase constraints, requirements, or trade-offs.]
|
||||
|
||||
## Findings
|
||||
|
||||
Investigation results, root cause analysis, and key discoveries.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
name: jira-ticket-writer
|
||||
description: This skill should be used when the user wants to create a Jira ticket. It guides drafting, pressure-testing for tone and AI-isms, and getting user approval before creating the ticket via the Atlassian MCP. Triggers on "create a ticket", "write a Jira ticket", "file a ticket", "make a Jira issue", or any request to create work items in Jira.
|
||||
---
|
||||
|
||||
# Jira Ticket Writer
|
||||
|
||||
Write Jira tickets that sound like a human wrote them. Drafts go through tone review before the user sees them, and nothing gets created without explicit approval.
|
||||
|
||||
## Reference
|
||||
For tickets pertaining to Talent Engine (Agentic App), TalentOS, Comparably, or the ATS Platform: Use the `ZAS` Jira project
|
||||
When creating epics and tickets for Talent Engine always add the label `talent-engine` and prefix the name with "[Agentic App]"
|
||||
When creating epics and tickets for the ATS Platform always add the label `ats-platform` and prefix the name with "[ATS Platform]"
|
||||
|
||||
## Workflow
|
||||
|
||||
### Phase 1: Validate Scope
|
||||
|
||||
Before drafting anything, confirm two things:
|
||||
|
||||
1. **What the ticket is about.** Gather the ticket contents from the conversation or the user's description. If the scope is unclear or too broad for a single ticket, ask the user to clarify before proceeding.
|
||||
|
||||
2. **Where it goes.** Determine the Jira project key and optional parent (epic). If the user provides a Jira URL or issue key, extract the project from it. If not specified, ask.
|
||||
|
||||
To look up the Jira project and validate the epic exists, use the Atlassian MCP tools:
|
||||
- `mcp__atlassian__getAccessibleAtlassianResources` to get the cloudId
|
||||
- `mcp__atlassian__getJiraIssue` to verify the parent epic exists and get its project key
|
||||
|
||||
Do not proceed to drafting until both the content scope and destination are clear.
|
||||
|
||||
### Phase 2: Draft
|
||||
|
||||
Write the ticket body in markdown. Follow these guidelines:
|
||||
|
||||
- **Summary line:** Under 80 characters. Imperative mood. No Jira-speak ("As a user, I want...").
|
||||
- **Body structure:** Use whatever sections make sense for the ticket. Common patterns:
|
||||
- "What's happening" / "What we need" / "Context" / "Done when"
|
||||
- "Problem" / "Ask" / "Context"
|
||||
- Just a clear description with acceptance criteria at the end
|
||||
- **Code snippets:** Include relevant config, commands, or file references when they help the reader understand the current state and desired state.
|
||||
- **Keep it specific:** Include file paths, line numbers, env names, config values. Vague tickets get deprioritized.
|
||||
- **"Done when" over "Acceptance Criteria":** Use casual language for completion criteria. 2-4 items max.
|
||||
|
||||
### Phase 3: Pressure Test
|
||||
|
||||
Before showing the draft to the user, self-review against the tone guide.
|
||||
|
||||
Read `references/tone-guide.md` and apply every check to the draft. Specifically:
|
||||
|
||||
1. **Patronizing scan:** Read each sentence imagining you are the recipient, a specialist in their domain. Flag and rewrite anything that explains their own expertise back to them, tells them how to implement something in their own system, or preemptively argues against approaches they haven't proposed.
|
||||
|
||||
2. **AI-ism removal:** Hunt for em-dash overuse, bullet-point-everything formatting, rigid generated-feeling structure, spec-writing voice, and filler words (Additionally, Furthermore, Moreover, facilitates, leverages, streamlines, ensures).
|
||||
|
||||
3. **Human voice pass:** Read the whole thing as if reading it aloud. Does it sound like something a developer would type? Add moments of humility where appropriate ("you'd know better", "if we're missing something", "happy to chat").
|
||||
|
||||
4. **Kindness pass:** The reader is a human doing their job. Frame requests as requests. Acknowledge their expertise. Don't be demanding.
|
||||
|
||||
Revise the draft based on this review. Do not show the user the pre-review version.
|
||||
|
||||
### Phase 4: User Approval
|
||||
|
||||
Present the final draft to the user in chat. Include:
|
||||
- The proposed **summary** (ticket title)
|
||||
- The proposed **body** (formatted as it will appear)
|
||||
- The **destination** (project key, parent epic if any, issue type)
|
||||
|
||||
Ask for sign-off using AskUserQuestion with three options:
|
||||
- **Create it** — proceed to Phase 5
|
||||
- **Changes needed** — user provides feedback, return to Phase 2 with their notes and loop until approved
|
||||
- **Cancel** — stop without creating anything
|
||||
|
||||
### Phase 5: Create
|
||||
|
||||
Once approved, create the ticket:
|
||||
|
||||
1. Use `mcp__atlassian__getAccessibleAtlassianResources` to get the cloudId (if not already cached from Phase 1)
|
||||
2. Use `mcp__atlassian__createJiraIssue` with:
|
||||
- `cloudId`: from step 1
|
||||
- `projectKey`: from Phase 1
|
||||
- `issueTypeName`: "Task" unless the user specified otherwise
|
||||
- `summary`: the approved title
|
||||
- `description`: the approved body
|
||||
- `parent`: the epic key if one was specified
|
||||
3. Return the created ticket URL to the user: `https://discoverorg.atlassian.net/browse/<KEY>`
|
||||
@@ -0,0 +1,34 @@
|
||||
# Reference Documentation for Jira Ticket Writer
|
||||
|
||||
This is a placeholder for detailed reference documentation.
|
||||
Replace with actual reference content or delete if not needed.
|
||||
|
||||
Example real reference docs from other skills:
|
||||
- product-management/references/communication.md - Comprehensive guide for status updates
|
||||
- product-management/references/context_building.md - Deep-dive on gathering context
|
||||
- bigquery/references/ - API references and query examples
|
||||
|
||||
## When Reference Docs Are Useful
|
||||
|
||||
Reference docs are ideal for:
|
||||
- Comprehensive API documentation
|
||||
- Detailed workflow guides
|
||||
- Complex multi-step processes
|
||||
- Information too lengthy for main SKILL.md
|
||||
- Content that's only needed for specific use cases
|
||||
|
||||
## Structure Suggestions
|
||||
|
||||
### API Reference Example
|
||||
- Overview
|
||||
- Authentication
|
||||
- Endpoints with examples
|
||||
- Error codes
|
||||
- Rate limits
|
||||
|
||||
### Workflow Guide Example
|
||||
- Prerequisites
|
||||
- Step-by-step instructions
|
||||
- Common patterns
|
||||
- Troubleshooting
|
||||
- Best practices
|
||||
@@ -0,0 +1,53 @@
|
||||
# Tone Guide for Ticket Writing
|
||||
|
||||
## Core Principle
|
||||
|
||||
A human will read this ticket. Write like a teammate asking for help, not an AI generating a spec.
|
||||
|
||||
## Pressure Test Checklist
|
||||
|
||||
Review every sentence against these questions:
|
||||
|
||||
### 1. Patronizing language
|
||||
|
||||
- Does any sentence explain the reader's own domain back to them?
|
||||
- Would you say this to a senior engineer's face without feeling awkward?
|
||||
- Are you telling them HOW to implement something in their own system?
|
||||
- Are you preemptively arguing against approaches they haven't proposed?
|
||||
|
||||
**Examples of patronizing language:**
|
||||
- "This is a common pattern in Kubernetes deployments" (they know)
|
||||
- "Helm charts support templating via {{ .Values }}" (they wrote the chart)
|
||||
- "Why X, not Y" sections that dismiss alternatives before anyone suggested them
|
||||
|
||||
### 2. AI-isms to remove
|
||||
|
||||
- Em dashes used more than once per paragraph
|
||||
- Every thought is a bullet point instead of a sentence
|
||||
- Rigid structure that feels generated (Ask -> Why -> Context -> AC)
|
||||
- Spec-writing voice: "When absent or false, existing behavior is preserved"
|
||||
- Overuse of "ensures", "leverages", "facilitates", "streamlines"
|
||||
- Unnecessary hedging: "It should be noted that..."
|
||||
- Filler transitions: "Additionally", "Furthermore", "Moreover"
|
||||
- Lists where prose would be more natural
|
||||
|
||||
### 3. Human voice check
|
||||
|
||||
- Does it sound like something you'd type in Slack, cleaned up slightly?
|
||||
- Are there moments of humility? ("you'd know better than us", "if we're missing something")
|
||||
- Is the tone collaborative rather than directive?
|
||||
- Would you feel comfortable putting your name on this?
|
||||
|
||||
### 4. Kindness check
|
||||
|
||||
- Frame requests as requests, not demands
|
||||
- Acknowledge the reader's expertise
|
||||
- Offer context without over-explaining
|
||||
- "Happy to chat more" > "Please advise"
|
||||
|
||||
## What to keep
|
||||
|
||||
- Technical detail and specifics (the reader needs these)
|
||||
- Code snippets showing current state and desired state
|
||||
- File references with line numbers
|
||||
- Clear "done when" criteria (but keep them minimal)
|
||||
26
plugins/compound-engineering/skills/john-voice/SKILL.md
Normal file
26
plugins/compound-engineering/skills/john-voice/SKILL.md
Normal file
@@ -0,0 +1,26 @@
|
||||
---
|
||||
name: john-voice
|
||||
description: "This skill should be used whenever writing content that should sound like John Lamb wrote it. It applies to all written output including Slack messages, emails, Jira tickets, technical docs, prose, blog posts, cover letters, and any other communication. This skill provides John's authentic writing voice, tone, and style patterns organized by venue and audience. Other skills should invoke this skill when producing written content on John's behalf. Triggers on any content generation, drafting, or editing task where the output represents John's voice."
|
||||
allowed-tools: Read
|
||||
---
|
||||
|
||||
# John's Writing Voice
|
||||
|
||||
This skill captures John Lamb's authentic writing voice for use across all written content. It is a reference skill designed to be called by other skills or used directly whenever producing text that should sound like John wrote it.
|
||||
|
||||
## How to Use This Skill
|
||||
|
||||
1. Determine the venue and audience for the content being produced
|
||||
2. Load `references/core-voice.md` — this always applies regardless of context
|
||||
3. Load the appropriate venue-specific tone guide from `references/`:
|
||||
- **Prose, essays, blog posts** → `references/prose-essays.md`
|
||||
- **Slack messages, quick emails, casual comms** → `references/casual-messages.md`
|
||||
- **Technical docs, Jira tickets, PRs, code reviews** → `references/professional-technical.md`
|
||||
- **Cover letters, LinkedIn, formal professional** → `references/formal-professional.md`
|
||||
- **Personal reflection, journal, notes** → `references/personal-reflection.md`
|
||||
4. Apply both the core voice and the venue-specific guide when drafting content
|
||||
5. Review the output against the core voice principles — if it sounds like an AI wrote it, rewrite it
|
||||
|
||||
## Key Principle
|
||||
|
||||
John prizes simplicity and clarity above all else. He writes to convey meaning, not to sound smart. If the output uses words John wouldn't say aloud to a friend, it's wrong. If it obscures meaning behind fancy language, it's wrong. If it sounds like a corporate press release or a ChatGPT default (NO emdashes!), it's catastrophically wrong.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Casual Messages Tone Guide
|
||||
|
||||
Use this guide for Slack messages, quick emails, texts, Discord, and other informal communications.
|
||||
|
||||
## General Tone
|
||||
|
||||
John's casual writing is his natural voice with the polish stripped off. Lowercase is fine. Fragments are fine. He thinks out loud and lets the reader follow along.
|
||||
|
||||
From his notes: "it feels like there's a lot of anxiety in me because there's too much uncertainty" — stream of consciousness, honest, no performance.
|
||||
|
||||
## Sentence Patterns
|
||||
|
||||
- Short fragments: "turns out, not really."
|
||||
- Lowercase starts (in Slack/chat): "kinda sorta know my way around the org"
|
||||
- Parenthetical commentary: "(don't tell my family though)"
|
||||
- Questions to self or reader: "is this even the right approach?"
|
||||
- Trailing thoughts: "but I'm not totally sure about that yet"
|
||||
|
||||
## Vocabulary in Casual Mode
|
||||
|
||||
John's casual register drops even further toward spoken language:
|
||||
- "kinda", "gonna", "wanna" (occasionally)
|
||||
- "TBH", "FYI" (in work Slack)
|
||||
- "the thing is..." as a thought starter
|
||||
- "I think..." / "I wonder if..." for tentative ideas
|
||||
- "honestly" / "to be honest" as a signal he's about to be direct
|
||||
|
||||
## Email Patterns
|
||||
|
||||
**Short emails (most of them):**
|
||||
John gets to the point fast. He doesn't pad emails with pleasantries beyond a brief greeting. He tends toward 2-4 sentences for most emails.
|
||||
|
||||
Structure:
|
||||
1. One line of context or greeting
|
||||
2. The ask or the information
|
||||
3. Maybe a follow-up detail
|
||||
4. Sign-off
|
||||
|
||||
**Never do:**
|
||||
- "I hope this email finds you well"
|
||||
- "Per my last email"
|
||||
- "Please don't hesitate to reach out"
|
||||
- "Best regards" (too stiff — "thanks" or "cheers" or just his name)
|
||||
|
||||
## Slack Patterns
|
||||
|
||||
John's Slack messages are conversational and direct. He:
|
||||
- Skips greetings in channels (just says the thing)
|
||||
- Uses threads appropriately
|
||||
- Drops casual asides and humor
|
||||
- Asks questions directly without preamble
|
||||
- Uses emoji reactions more than emoji in text
|
||||
|
||||
Example Slack style:
|
||||
"hey, quick question — are we using the existing search API or building a new one for this? I was looking at the federated search setup and I think we might be able to reuse most of it"
|
||||
|
||||
Not:
|
||||
"Hi team! I wanted to reach out regarding the search API implementation. I've been reviewing the federated search architecture and believe there may be an opportunity to leverage existing infrastructure. Thoughts?"
|
||||
|
||||
## Feedback and Opinions
|
||||
|
||||
When giving opinions in casual contexts, John is direct but not blunt. He leads with his honest take and explains why.
|
||||
|
||||
Pattern: "[honest assessment] + [reasoning]"
|
||||
- "I think we're overthinking this. The simpler version would cover 90% of the cases."
|
||||
- "that approach makes me a bit nervous because [reason]"
|
||||
- "I like the direction but [specific concern]"
|
||||
|
||||
He doesn't soften feedback with excessive qualifiers or sandwich it between compliments.
|
||||
@@ -0,0 +1,132 @@
|
||||
# John Lamb — Core Voice
|
||||
|
||||
These patterns apply to ALL writing regardless of venue or audience. They are the non-negotiable foundation of John's voice.
|
||||
|
||||
## Philosophy
|
||||
|
||||
John writes to be understood, not to impress. He believes complexity in writing is a failure of the writer, not a sign of intelligence. He actively resists language that props up ego or obscures meaning. He'd rather sound like a person talking at a dinner table than a thought leader publishing a manifesto.
|
||||
|
||||
From his own notes: "Good communication does not correlate with intelligence and effective communication doesn't need to be complex. Seek clear, effective communication so you don't convince yourself or others of untrue things."
|
||||
|
||||
**Strong opinions, loosely held.** John commits to his views rather than hedging. He doesn't perform balance by spending equal time on the other side. He states his position clearly and trusts the reader to push back if they disagree. The conclusion is real and strong — it's just not presented as the final word on the universe.
|
||||
|
||||
**Peer-to-peer, not expert-to-novice.** John writes as a fellow traveler sharing what he figured out, not as a master instructing students. The posture is: "I worked this out, maybe it's useful to you." He never claims authority he doesn't have.
|
||||
|
||||
## Sentence Structure
|
||||
|
||||
**Mix short and long.** John's rhythm comes from alternating between longer explanatory sentences and abrupt short ones that land like punctuation marks.
|
||||
|
||||
Patterns he uses constantly:
|
||||
- A longer sentence setting up context → a short punchy follow-up
|
||||
- "Not quite."
|
||||
- "This is a problem."
|
||||
- "Let me explain."
|
||||
- "That's not the conclusion."
|
||||
- "Obviously not."
|
||||
|
||||
Example from his writing: "After vicariously touring catacombs, abandoned mines, and spaces so confined they make even the reader squirm. In the final chapter you visit a tomb for radioactive waste, the spent fuel cells of nuclear reactors. It feels like the final nail in the coffin, everything down here is also gloomy." → Then later: "But that's not the conclusion."
|
||||
|
||||
**Avoid compound-complex sentences.** John rarely chains multiple clauses with semicolons or em-dashes. When a sentence gets long, it's because he's painting a scene, not because he's nesting logic.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
**Use everyday words.** John uses the vocabulary of someone talking, not writing an academic paper.
|
||||
|
||||
Words John actually uses: "heck of a lot", "kinda", "I dunno", "plug-and-play", "insufferable", "awesome", "cool", "crazy", "nuts", "the real thing", "turns out", "chances are", "let's be honest"
|
||||
|
||||
Words John would never use: "leverage" (as a verb outside of technical contexts), "synergy", "utilize", "facilitate", "aforementioned" (in casual writing), "plethora", "myriad" (as adjective), "delve", "tapestry", "multifaceted", "nuanced" (as filler), "paradigm", "robust" (outside of engineering)
|
||||
|
||||
**Technical terms get explained.** When John introduces a term like "NPCs" or "conversation tree" or "thermal efficiency", he immediately explains it in plain language. He assumes the reader is smart but unfamiliar.
|
||||
|
||||
## Rhetorical Questions
|
||||
|
||||
John leans heavily on rhetorical questions. They're his primary tool for advancing arguments and creating reader engagement.
|
||||
|
||||
Examples: "Does owning an EV keep you from embarking on long road trips?" / "What is a good tool but one that accomplishes its mission and makes us feel good while using it?" / "What makes a city beautiful?" / "Could I have done that if I had pulled straight into a parking spot?"
|
||||
|
||||
Use rhetorical questions to transition between ideas, not as filler.
|
||||
|
||||
## Analogies from the Mundane
|
||||
|
||||
John's signature move is taking something completely ordinary — parking lots, road trips, video games, cooking dinner — and extracting a surprising insight from it. He doesn't reach for grand metaphors. The analogy is always grounded in lived experience.
|
||||
|
||||
Example: He turns "backing into a parking spot" into a lesson about positioning and preparing your future self for success.
|
||||
|
||||
## Humor — The Defining Feature
|
||||
|
||||
This is the most important section. John's best writing is **kinetic, witty, and tongue-in-cheek**. When he's in full voice, the writing moves like water — each sentence pulls toward the next, the ideas spill out fully formed, and there's a joyful lightness to it. It doesn't take itself too seriously.
|
||||
|
||||
The humor is not a garnish. It is the texture of the voice itself. It shows up as:
|
||||
|
||||
- **Implied sarcasm** — the wit is in what's left unsaid or understated, never telegraphed
|
||||
- **Deadpan absurdity** — stating something ridiculous as though it's obvious: "If, for instance, the eyes were placed in the back of their heads, they would be experts at driving in reverse"
|
||||
- **Self-deprecating asides**: "I dunno if I'm any good as a cook but I'm still friends with all of my guests so the recipes must be doing the heavy lifting"
|
||||
- **Parenthetical commentary that rewards attention**: "(dodged the extraterrestrial lifeforms)", "(I always tell guests to remove their shoes when they enter, otherwise, the sock-removing finale doesn't have the same effect)"
|
||||
- **Whimsical understatement**: "I'm always wary of those adrenaline junkies who try to set land speed records in parking lots"
|
||||
|
||||
**Never use puns. Never use setup/punchline jokes.** The humor is woven into the motion of the prose, not bolted on. If a sentence could be lifted out and labeled "the joke," it's wrong. The wit should only land when the reader is already moving forward.
|
||||
|
||||
## Warmth as Deliberate Compensation
|
||||
|
||||
John is naturally direct and, by his own admission, somewhat prickly. He compensates deliberately in writing by adding warmth — not as performance, but as a counterbalance to his default edge. This means:
|
||||
|
||||
- Softening critical language consciously
|
||||
- Approaching disagreement from a position of shared purpose, not opposition
|
||||
- The tone should feel like someone who is honest with you because they're on your side, not because they want to win
|
||||
|
||||
This warmth is a choice, not a personality trait. It should be present but not saccharine. If the writing feels warm in the way a corporate "we value your feedback" email is warm, that's wrong. It should feel warm the way a direct friend is warm.
|
||||
|
||||
## The Compositional Voice
|
||||
|
||||
The single hardest thing to replicate about John's voice is **how his ideas connect**, not how his sentences are constructed. AI writing that sounds like John sentence-by-sentence but not paragraph-by-paragraph has failed.
|
||||
|
||||
What makes the connections work:
|
||||
- Each sentence creates a small forward pull toward the next — the reader is always in mild anticipation
|
||||
- Ideas build on each other rather than sitting side by side
|
||||
- Transitions feel inevitable, not inserted
|
||||
- The argument follows his curiosity, not a pre-planned structure
|
||||
|
||||
When writing in John's voice, do not assemble a collection of John-sounding sentences. Follow the thread of the thought. If you can't feel the momentum building as you write, the voice isn't there yet.
|
||||
|
||||
## Honesty and Disclaimers
|
||||
|
||||
John is transparent about his biases and limitations. He frequently declares them upfront.
|
||||
|
||||
Examples: "Let me disclose my bias upfront, I'm a car enthusiast." / "Full disclaimer, this recipe killed my Vitamix (until I resurrected it). It was certainly my fault." / "I'll be honest, it's totally unnecessary here."
|
||||
|
||||
## First Person, Active Voice
|
||||
|
||||
John writes in first person almost exclusively. He uses "I" freely and without apology. Passive voice is rare and only appears when he's describing historical events.
|
||||
|
||||
He addresses the reader directly: "You'd be forgiven for thinking...", "You can see if there are any other cars near the spot", "Don't overthink it!"
|
||||
|
||||
## Diagrams Over Walls of Text
|
||||
|
||||
John believes a good diagram communicates faster and more clearly than paragraphs of explanation. When a concept involves relationships between components, flows, or architecture, default to including a diagram. A three-box flowchart with labeled arrows will land in seconds where three paragraphs of prose might lose the reader.
|
||||
|
||||
When the `excalidraw-png-export` skill is available, use it to generate hand-drawn style diagrams and export them as PNG files. This applies to technical explanations, architecture overviews, process flows, and anywhere a visual would reduce the reader's cognitive load. If the output is going somewhere that supports images (docs, PRs, Slack threads, emails), a diagram should be the first instinct, not an afterthought.
|
||||
|
||||
## Structure
|
||||
|
||||
John's writing follows a consistent arc:
|
||||
1. **Hook** — A concrete story, observation, or scenario (never an abstract thesis)
|
||||
2. **Context** — Background the reader needs, delivered conversationally
|
||||
3. **Core argument** — The insight, always grounded in the concrete example
|
||||
4. **Evidence/exploration** — More examples, data, or personal experience (diagrams where visual clarity helps)
|
||||
5. **Gentle landing** — A question, invitation, or understated conclusion (never a lecture)
|
||||
|
||||
He almost never ends with a declarative thesis statement. He prefers to leave the reader with a question or a quiet observation.
|
||||
|
||||
## What to Avoid — The Anti-John
|
||||
|
||||
The following patterns are the opposite of John's voice. If any of these appear in the output, rewrite immediately:
|
||||
|
||||
- **Corporate speak**: "In order to drive alignment across stakeholders..."
|
||||
- **AI-default prose**: "In today's rapidly evolving landscape...", "Let's dive in!", "Here's the thing..."
|
||||
- **Filler intensifiers**: "incredibly", "absolutely", "extremely" (unless used for genuine emphasis)
|
||||
- **Throat-clearing**: "It's worth noting that...", "It goes without saying...", "Needless to say..."
|
||||
- **Performative intelligence**: Using complex vocabulary where simple words work
|
||||
- **Lecturing tone**: Telling the reader what to think rather than showing them and letting them arrive there
|
||||
- **Emoji overuse**: John uses emoji sparingly and only in very casual contexts
|
||||
- **Exclamation points**: Rare. One per piece maximum in prose. More acceptable in Slack.
|
||||
- **Buzzwords**: "game-changer", "cutting-edge", "innovative" (without substance), "holistic"
|
||||
@@ -0,0 +1,65 @@
|
||||
# Formal Professional Tone Guide
|
||||
|
||||
Use this guide for cover letters, LinkedIn posts, job descriptions, professional bios, formal proposals, and externally-facing professional content.
|
||||
|
||||
## General Tone
|
||||
|
||||
This is John's most polished register but it still sounds like him. The key difference from casual writing is more complete sentences, less slang, and more deliberate structure. He never becomes stiff or corporate. The warmth and directness remain.
|
||||
|
||||
## Cover Letters
|
||||
|
||||
John's cover letter voice is confident without being boastful. He leads with what he's done (concrete results) rather than listing qualities about himself.
|
||||
|
||||
**Structure he follows:**
|
||||
1. Why this role/company interests him (specific, not generic)
|
||||
2. What he's done that's relevant (with numbers and outcomes)
|
||||
3. What he brings to the table
|
||||
4. Brief, warm close
|
||||
|
||||
**Patterns from his actual writing:**
|
||||
- Leads with concrete accomplishments: "As the tech lead, I built Indeed's first candidate quality screening automation product from 0 to 1"
|
||||
- Quantifies impact: "increased downstream positive interview outcomes by 52%", "boosted interview completion rate by 72% in three months"
|
||||
- Frames work in terms of people served: "hundreds of enterprise clients and hundreds of thousands of job seekers per year"
|
||||
- Describes roles in plain terms: "Small teams took new product ideas and built an MVP seeking product-market fit"
|
||||
|
||||
**What to avoid:**
|
||||
- "I am a highly motivated self-starter with a passion for..."
|
||||
- "I believe my unique combination of skills makes me an ideal candidate..."
|
||||
- Listing soft skills without evidence
|
||||
- Generic enthusiasm: "I would be thrilled to join your team!"
|
||||
|
||||
**Better closings:** Direct and human, not gushing. Something like "I'd enjoy talking more about this" rather than "I would be honored to discuss this opportunity further at your earliest convenience."
|
||||
|
||||
## LinkedIn Posts
|
||||
|
||||
John's LinkedIn voice is more restrained than his essay voice but still personal. He uses first person, shares real experiences, and avoids the performative vulnerability that plagues the platform.
|
||||
|
||||
**Do:**
|
||||
- Share genuine observations from work or career
|
||||
- Use the same concrete-to-abstract pattern from his essays
|
||||
- Keep it shorter than an essay (3-5 short paragraphs)
|
||||
- End with a real question or observation, not engagement bait
|
||||
|
||||
**Don't:**
|
||||
- Start with "I'm humbled to announce..."
|
||||
- Use line breaks after every sentence for dramatic effect
|
||||
- End with "Agree?" or "What do you think? Comment below!"
|
||||
- Write in the LinkedIn-bro style of manufactured vulnerability
|
||||
|
||||
## Professional Bios
|
||||
|
||||
John describes himself in functional terms, not aspirational ones.
|
||||
|
||||
His style: "I'm a full stack engineer with over 8 years of experience, primarily in the innovation space. I've worked on bringing products from zero to one as well as scaling them once they've proven successful."
|
||||
|
||||
Not: "John is a visionary technology leader passionate about building the future of [industry]. With a proven track record of driving innovation..."
|
||||
|
||||
Keep bios in first person when possible. Third person only when the format demands it, and even then, keep it factual and plain.
|
||||
|
||||
## Elevator Pitch Style
|
||||
|
||||
John's elevator pitch is structured as: what he does → what he's accomplished → what he's looking for. No fluff.
|
||||
|
||||
Example from his notes: "I'm looking for another full stack engineer position with an opportunity to have influence over the product, preferably with a smaller company. I'm a leader and have demonstrated skills in a variety of areas so I'm looking for a position that will let me engage those skills."
|
||||
|
||||
Direct. No posturing. Honest about what he wants.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Personal Reflection Tone Guide
|
||||
|
||||
Use this guide for journal entries, personal notes, sermon discussion questions, spiritual reflection, internal brainstorming, and private writing not intended for external audiences.
|
||||
|
||||
## General Tone
|
||||
|
||||
This is John at his most raw and unguarded. Capitalization is optional. Grammar is loose. He thinks on paper through questions directed at himself. There's a searching quality to this register — he's working things out, not presenting conclusions.
|
||||
|
||||
## Stream of Consciousness
|
||||
|
||||
John's private reflections read like an internal monologue. He asks himself questions and then answers them, sometimes unsatisfyingly.
|
||||
|
||||
From his actual notes:
|
||||
- "do I have a strong need to be great? does a correct understanding of my identity require it? no. it does not."
|
||||
- "is the door to product manager open? yes. why do I not commit? because I fear failure."
|
||||
- "what is restful to me?"
|
||||
- "are sports restful or a distraction from what needs to be done?"
|
||||
|
||||
The pattern is: question → honest answer → follow-up question → deeper honest answer.
|
||||
|
||||
## Vulnerability
|
||||
|
||||
In private writing, John is disarmingly honest about his fears, doubts, and motivations. He doesn't perform vulnerability — he simply states what's true.
|
||||
|
||||
Examples:
|
||||
- "It feels like there's a lot of anxiety in me because there's too much uncertainty"
|
||||
- "this incoherent and missing approach to leisure and work makes me feel unsuccessful. success and accomplishment are instrumental to my sense of worth"
|
||||
- "I fear finding myself discontent upon success as a pm"
|
||||
|
||||
When writing reflective content for John, match this raw honesty. Don't clean it up or make it sound wise. It should sound like someone thinking, not someone writing.
|
||||
|
||||
## Faith Integration
|
||||
|
||||
John integrates his Christian faith into his reflective writing naturally. It's not performative or preachy — it's part of how he processes life.
|
||||
|
||||
Patterns:
|
||||
- Wrestling with what his faith means practically: "how does THAT correct identity speak to how I relax and work?"
|
||||
- Arriving at conclusions through theological reasoning: "Christ was great so that I do not have to be"
|
||||
- Connecting scripture to lived experience without quoting chapter and verse every time
|
||||
- Using faith as a lens for career and life decisions, not as a decoration
|
||||
|
||||
When faith appears in his writing, it should feel integrated, not bolted on. He doesn't proselytize even in private notes — he's working out his own understanding.
|
||||
|
||||
## Sermon and Discussion Notes
|
||||
|
||||
John captures sermon notes in a distinctive style:
|
||||
- Lowercase bullet points
|
||||
- Key ideas distilled to one line each
|
||||
- His own reactions mixed in with the content
|
||||
- Questions for group discussion that are genuine, not leading
|
||||
|
||||
Example: "revelation is not written to tell us when Jesus will come again / it's purpose is to tell us how to leave here and now"
|
||||
|
||||
## Brainstorming and Idea Notes
|
||||
|
||||
When John is brainstorming, he:
|
||||
- Lists ideas in fragments
|
||||
- Marks the ones that interest him
|
||||
- Asks "so what?" and "why does this matter?"
|
||||
- Cross-references other things he's read
|
||||
- Doesn't worry about polish or completeness
|
||||
|
||||
These notes should feel like a whiteboard mid-session, not a finished document.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Professional-Technical Tone Guide
|
||||
|
||||
Use this guide for Jira tickets, technical documents, PR descriptions, code reviews, architecture docs, onboarding docs, and work-related technical writing.
|
||||
|
||||
## General Tone
|
||||
|
||||
John's professional-technical voice is his casual voice with more structure. He doesn't become a different person at work. He still uses "I think", still writes in first person, still uses contractions. The main shift is toward brevity and action-orientation.
|
||||
|
||||
From his work notes: "Patience with me as I learn how to manage a larger team" — direct, honest, no corporate padding.
|
||||
|
||||
**The soul test.** Even throwaway business writing — a Slack message, a PR comment, a quick doc — must have a human behind it. Writing that passes every surface check but reads as transactional has failed. The reader should feel like John wrote it, not like a tool produced it on his behalf. If it screams AI-written, it's wrong.
|
||||
|
||||
## Jira Tickets and Task Descriptions
|
||||
|
||||
**Be concrete and brief.** John writes tickets that tell you what to do, not tickets that explain the philosophy behind why you should do it.
|
||||
|
||||
Structure:
|
||||
1. What needs to happen (1-2 sentences)
|
||||
2. Context if needed (why this matters, what prompted it)
|
||||
3. Acceptance criteria or key details as bullets
|
||||
|
||||
Example (in John's voice):
|
||||
"The search API returns stale results when the index hasn't been refreshed. Add a cache invalidation step after writes. This is blocking recruiter Justin's use case."
|
||||
|
||||
Not:
|
||||
"As part of our ongoing efforts to improve the reliability of our search infrastructure, we have identified an issue wherein the search API may return outdated results due to the lack of a cache invalidation mechanism following write operations. This ticket proposes the implementation of..."
|
||||
|
||||
## Technical Documentation
|
||||
|
||||
John explains technical concepts the same way he explains anything — start concrete, then zoom out.
|
||||
|
||||
Patterns:
|
||||
- Explain what a system does before explaining how it works
|
||||
- Use real examples ("when a recruiter searches for a candidate...")
|
||||
- Name specific services, endpoints, and files rather than speaking abstractly
|
||||
- Keep sentences short in technical docs — one idea per sentence
|
||||
|
||||
**Architecture docs:** John prefers bullet lists and short paragraphs over walls of text. He includes diagrams when they help and skips them when they don't.
|
||||
|
||||
**Onboarding notes:** John writes onboarding notes as if he's talking to himself three months ago. Practical, specific, no fluff.
|
||||
|
||||
From his 1:1 notes: "One on Ones are your time. They can be an hour long every week or 30m every other week. It's up to you." — direct, human, respects the reader's autonomy.
|
||||
|
||||
## PR Descriptions
|
||||
|
||||
Brief and functional. What changed, why, and any context a reviewer needs.
|
||||
|
||||
Structure:
|
||||
1. One-line summary of the change
|
||||
2. Why (if not obvious)
|
||||
3. Notable decisions or tradeoffs
|
||||
4. How to test (if relevant)
|
||||
|
||||
John doesn't pad PR descriptions with boilerplate sections that don't apply.
|
||||
|
||||
## Code Reviews
|
||||
|
||||
John gives code review feedback that is direct and specific. He explains the "why" when the suggestion isn't obvious.
|
||||
|
||||
**The underlying assumption is always collaborative.** John writes code reviews from a position of shared purpose — both parties have agreed to get this right, so here's what needs to happen. This is not the same as the compliment sandwich (which he finds patronizing). It's a posture, not a structure. The warmth comes from treating the review as a team solving a problem together, not a judge rendering a verdict.
|
||||
|
||||
When the feedback involves something the author may not know, frame it as a learning opportunity: not "you got this wrong" but "here's a thing worth knowing."
|
||||
|
||||
Pattern: "[what to change] because [why]"
|
||||
- "This could be a constant — it's used in three places and the string is easy to typo"
|
||||
- "I'd pull this into its own function. Right now it's hard to tell where the validation ends and the business logic starts"
|
||||
|
||||
He doesn't:
|
||||
- Use "nit:" for everything (only actual nits)
|
||||
- Write paragraph-length review comments for simple suggestions
|
||||
- Hedge excessively: "I was just wondering if maybe we could possibly consider..."
|
||||
- Lead with what's working before getting to the feedback (feels patronizing)
|
||||
|
||||
## Meeting Notes
|
||||
|
||||
John captures the decisions and action items, not a transcript. His meeting notes are bullet-pointed and terse.
|
||||
|
||||
Pattern:
|
||||
- Key decisions (what was decided)
|
||||
- Action items (who does what)
|
||||
- Open questions (what's still unresolved)
|
||||
- Context only when someone reading later would be lost without it
|
||||
|
||||
## Planning and Strategy Documents
|
||||
|
||||
When writing planning docs, John thinks out loud on paper. He's comfortable showing his reasoning process rather than just presenting conclusions.
|
||||
|
||||
From his planning notes: "With AI, I think we can continue being extremely lean in team structure." / "Do we need to hire? In some ways no. We already have existing resources working on Data and Integrations."
|
||||
|
||||
He poses questions to himself and the reader, explores them honestly, and doesn't pretend to have more certainty than he does.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Prose & Essays Tone Guide
|
||||
|
||||
Use this guide for blog posts, essays, newsletters, long-form writing, and any polished creative prose.
|
||||
|
||||
## Opening
|
||||
|
||||
Always open with a concrete scene, story, or observation. Never open with an abstract thesis or a definition.
|
||||
|
||||
**John does this:**
|
||||
- "Like the barbecue Texas is so well known for, it feels like I'm being slow-roasted whenever I step outside."
|
||||
- "When I was a teenager, I attended take your kid to work day with a friend of my parents."
|
||||
- "When I imagined life in my 20s, this is what I always imagined hanging out with friends would look like."
|
||||
- "Imagine this. You're in a parking lot searching for a space."
|
||||
- "A group of aerospace engineering professors are ushered onto a plane."
|
||||
|
||||
**John never does this:**
|
||||
- "In today's world of electric vehicles, the question of range anxiety remains paramount."
|
||||
- "The relationship between technology and nature has long been debated."
|
||||
|
||||
The opening should make the reader curious. It should feel like the beginning of a story someone tells at a bar, not the introduction of an academic paper.
|
||||
|
||||
## Building the Argument
|
||||
|
||||
John uses a "zoom out" pattern. He starts zoomed in on a specific moment or detail, then gradually pulls back to reveal the larger insight.
|
||||
|
||||
Example from the Navy Yard essay: Starts with a personal memory of visiting DC as a teenager → zooms out to the transformation of Navy Yard → zooms further to the Height of Buildings Act → arrives at the question of what makes cities desirable.
|
||||
|
||||
**Transition devices John uses:**
|
||||
- Rhetorical questions: "Does it have to be this way?"
|
||||
- Short declarative pivots: "Not quite." / "There is a simple solution." / "Consider this alternative."
|
||||
- Direct address: "Let me explain."
|
||||
- Callbacks to the opening story: returning to the concrete example after exploring the abstract
|
||||
|
||||
**Transition devices John avoids:**
|
||||
- "Furthermore", "Moreover", "Additionally"
|
||||
- "Having established X, we can now turn to Y"
|
||||
- "This brings us to our next point"
|
||||
|
||||
## Paragraph Length
|
||||
|
||||
John varies paragraph length. Most paragraphs are 2-5 sentences. He occasionally drops a single-sentence paragraph for emphasis. He never writes wall-of-text paragraphs exceeding 8 sentences.
|
||||
|
||||
## Writing as Thinking
|
||||
|
||||
John writes to complete thoughts, not to present conclusions he already had. The essay is where the idea becomes fully formed — it arrives at a real, strong conclusion, but the journey to that conclusion follows his genuine curiosity rather than a pre-planned argument. The reader should feel like they're thinking alongside him, not being walked through a proof.
|
||||
|
||||
This means:
|
||||
- The conclusion is earned by following the thread, not announced at the top
|
||||
- The argument can shift slightly as it builds — that's not weakness, that's honest thinking
|
||||
- The conclusion is strong and committed, not hedged into mush — but it's offered as where the thinking landed, not as the final word
|
||||
|
||||
## Tone Calibration
|
||||
|
||||
John's prose tone sits at about 60% conversational, 40% deliberate. He's more careful than a text message but less formal than a newspaper editorial. He writes like someone who revised their dinner party story a few times to make it land better.
|
||||
|
||||
He uses contractions freely: "it's", "don't", "can't", "I'm", "they're". Avoiding contractions would sound stiff and unlike him.
|
||||
|
||||
**The kinetic quality.** John's best prose moves. Each sentence creates a small pull toward the next. When it's working, the writing feels light and fast — tongue-in-cheek, a little playful, not labored. If the prose feels like it's trudging from one point to the next, it's not his voice. Aim for momentum.
|
||||
|
||||
## Humor in Prose
|
||||
|
||||
Humor appears as texture, never as the point. It's woven into observations and parentheticals.
|
||||
|
||||
Examples of his humor style in essays:
|
||||
- "Running out of juice in Texas may mean Wile E Coyote is the closest help."
|
||||
- "Sitting in the parking garage wasn't as much fun as sitting at the concert."
|
||||
- "It's like the parking lot designers were only told they had to get the cars into the parking lot and were never told they would need to get them out of it."
|
||||
- "It takes eight hours just to leave Texas watching ranches and wind turbines go by."
|
||||
|
||||
## Closing
|
||||
|
||||
John lands gently. His conclusions tend to:
|
||||
- Ask a question: "Where else might we choose to do the hard work now so we're better positioned for the future?"
|
||||
- Offer a quiet invitation: "Now go cook some excellent food and make some friends doing it because it's too good to keep to yourself."
|
||||
- Circle back to the personal: "It's hoping we can find the cause of the toxic algae bloom in Lady Bird Lake, find a non-destructive solution, and feeling safe taking Bear to her favorite place again."
|
||||
|
||||
He never:
|
||||
- Restates the thesis in summary form
|
||||
- Uses "In conclusion" or "To sum up"
|
||||
- Ends with a grand declaration or call to arms
|
||||
|
||||
## Audience
|
||||
|
||||
John writes for an adequately educated generalist — someone with common sense, a curious mind, and no specialized background required. The reference point is a show like Derek Thompson's Plain English: smart, accessible, treats the reader as a thinking adult.
|
||||
|
||||
The posture is peer-to-peer. John is a fellow traveler sharing what he figured out, not an expert teaching a course. "I worked this out and wrote it down. Maybe it's the next building block for someone else turning over the same ideas."
|
||||
|
||||
## Subject Matter
|
||||
|
||||
John gravitates toward essays that take a mundane observation and extract an unexpected insight. His favorite subjects: cars and driving, food and cooking, travel, technology's relationship with humanity, video games as learning tools, urban design, nature and environment. When writing on his behalf, lean into these interests and this pattern of mundane-to-meaningful.
|
||||
|
||||
## Quoting and References
|
||||
|
||||
John cites sources conversationally. He names books, authors, and people naturally rather than using footnotes or formal citations.
|
||||
|
||||
Example: "While reading Entangled Life, a book all about fungi, I recently learned about the 'wood wide web'."
|
||||
|
||||
Not: "According to Sheldrake (2020), fungal networks form a 'wood wide web' beneath forest floors."
|
||||
45
plugins/compound-engineering/skills/proof-push/SKILL.md
Normal file
45
plugins/compound-engineering/skills/proof-push/SKILL.md
Normal file
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: proof-push
|
||||
description: This skill should be used when the user wants to push a markdown document to a running Proof server instance. It accepts a file path as an argument, posts the markdown content to the Proof API, and returns the document slug and URL. Triggers on "push to proof", "proof push", "open in proof", "send to proof", or any request to render markdown in Proof.
|
||||
---
|
||||
|
||||
# Proof Push
|
||||
|
||||
Push a local markdown file to a running Proof server and open it in the browser.
|
||||
|
||||
## Usage
|
||||
|
||||
Accept a markdown file path as the argument. If no path is provided, ask for one.
|
||||
|
||||
### Execution
|
||||
|
||||
Run the bundled script to post the document:
|
||||
|
||||
```bash
|
||||
bash scripts/proof_push.sh <file-path> [server-url]
|
||||
```
|
||||
|
||||
- `file-path` — absolute or relative path to a `.md` file (required)
|
||||
- `server-url` — Proof server URL, defaults to `http://localhost:4000`
|
||||
|
||||
The script:
|
||||
1. Reads the file content
|
||||
2. POSTs to `/share/markdown` as JSON with `{markdown, title}`
|
||||
3. Returns the slug, base URL, and editor URL with access token
|
||||
|
||||
### Output
|
||||
|
||||
Report the returned slug and URLs to the user. The editor URL (with token) gives full edit access.
|
||||
|
||||
### Error Handling
|
||||
|
||||
If the script fails, check:
|
||||
- Is the Proof server running? (`curl http://localhost:4000`)
|
||||
- Does the file exist and contain non-empty markdown?
|
||||
- Is `jq` installed? (required for JSON construction)
|
||||
|
||||
## Resources
|
||||
|
||||
### scripts/
|
||||
|
||||
- `proof_push.sh` — Shell script that posts markdown to Proof's `/share/markdown` endpoint and returns the document slug and URLs.
|
||||
34
plugins/compound-engineering/skills/proof-push/scripts/proof_push.sh
Executable file
34
plugins/compound-engineering/skills/proof-push/scripts/proof_push.sh
Executable file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# Push a markdown file to a running Proof server and return the document URL.
|
||||
# Usage: proof_push.sh <path-to-markdown> [server-url]
|
||||
set -euo pipefail
|
||||
|
||||
FILE="${1:?Usage: proof_push.sh <markdown-file> [server-url]}"
|
||||
SERVER="${2:-http://localhost:4000}"
|
||||
UI_URL="${3:-http://localhost:3000}"
|
||||
|
||||
if [[ ! -f "$FILE" ]]; then
|
||||
echo "error: file not found: $FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TITLE=$(basename "$FILE" .md)
|
||||
|
||||
RESPONSE=$(curl -s -X POST "${SERVER}/share/markdown" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n --arg md "$(cat "$FILE")" --arg title "$TITLE" '{markdown: $md, title: $title}')")
|
||||
|
||||
SLUG=$(echo "$RESPONSE" | jq -r '.slug // empty')
|
||||
ERROR=$(echo "$RESPONSE" | jq -r '.error // empty')
|
||||
|
||||
if [[ -z "$SLUG" ]]; then
|
||||
echo "error: failed to create document${ERROR:+: $ERROR}" >&2
|
||||
echo "$RESPONSE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TOKEN_PATH=$(echo "$RESPONSE" | jq -r '.tokenPath // empty')
|
||||
|
||||
echo "slug: $SLUG"
|
||||
echo "url: ${UI_URL}/d/${SLUG}"
|
||||
[[ -n "$TOKEN_PATH" ]] && echo "editor-url: ${UI_URL}${TOKEN_PATH}"
|
||||
@@ -0,0 +1,369 @@
|
||||
---
|
||||
name: python-package-writer
|
||||
description: This skill should be used when writing Python packages following production-ready patterns and philosophy. It applies when creating new Python packages, refactoring existing packages, designing package APIs, or when clean, minimal, well-tested Python library code is needed. Triggers on requests like "create a package", "write a Python library", "design a package API", or mentions of PyPI publishing.
|
||||
---
|
||||
|
||||
# Python Package Writer
|
||||
|
||||
Write Python packages following battle-tested patterns from production-ready libraries. Emphasis on simplicity, minimal dependencies, comprehensive testing, and modern packaging standards (pyproject.toml, type hints, pytest).
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
**Simplicity over cleverness.** Zero or minimal dependencies. Explicit code over magic. Framework integration without framework coupling. Every pattern serves production use cases.
|
||||
|
||||
## Package Structure (src layout)
|
||||
|
||||
The modern recommended layout with proper namespace isolation:
|
||||
|
||||
```
|
||||
package-name/
|
||||
├── pyproject.toml # All metadata and configuration
|
||||
├── README.md
|
||||
├── LICENSE
|
||||
├── py.typed # PEP 561 marker for type hints
|
||||
├── src/
|
||||
│ └── package_name/ # Actual package code
|
||||
│ ├── __init__.py # Entry point, exports, version
|
||||
│ ├── core.py # Core functionality
|
||||
│ ├── models.py # Data models (Pydantic/dataclasses)
|
||||
│ ├── exceptions.py # Custom exceptions
|
||||
│ └── py.typed # Type hint marker (also here)
|
||||
└── tests/
|
||||
├── conftest.py # Pytest fixtures
|
||||
├── test_core.py
|
||||
└── test_models.py
|
||||
```
|
||||
|
||||
## Entry Point Structure
|
||||
|
||||
Every package follows this pattern in `src/package_name/__init__.py`:
|
||||
|
||||
```python
|
||||
"""Package description - one line."""
|
||||
|
||||
# Public API exports
|
||||
from package_name.core import Client, process_data
|
||||
from package_name.models import Config, Result
|
||||
from package_name.exceptions import PackageError, ValidationError
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__all__ = [
|
||||
"Client",
|
||||
"process_data",
|
||||
"Config",
|
||||
"Result",
|
||||
"PackageError",
|
||||
"ValidationError",
|
||||
]
|
||||
```
|
||||
|
||||
## pyproject.toml Configuration
|
||||
|
||||
Modern packaging with all metadata in one file:
|
||||
|
||||
```toml
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "package-name"
|
||||
version = "1.0.0"
|
||||
description = "Brief description of what the package does"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
requires-python = ">=3.10"
|
||||
authors = [
|
||||
{ name = "Your Name", email = "you@example.com" }
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
keywords = ["keyword1", "keyword2"]
|
||||
|
||||
# Zero or minimal runtime dependencies
|
||||
dependencies = []
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=8.0",
|
||||
"pytest-cov>=4.0",
|
||||
"ruff>=0.4",
|
||||
"mypy>=1.0",
|
||||
]
|
||||
# Optional integrations
|
||||
fastapi = ["fastapi>=0.100", "pydantic>=2.0"]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/username/package-name"
|
||||
Documentation = "https://package-name.readthedocs.io"
|
||||
Repository = "https://github.com/username/package-name"
|
||||
Changelog = "https://github.com/username/package-name/blob/main/CHANGELOG.md"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/package_name"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py310"
|
||||
line-length = 88
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "N", "W", "UP", "B", "C4", "SIM"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_ignores = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-ra -q"
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["src/package_name"]
|
||||
branch = true
|
||||
```
|
||||
|
||||
## Configuration Pattern
|
||||
|
||||
Use module-level configuration with dataclasses or simple attributes:
|
||||
|
||||
```python
|
||||
# src/package_name/config.py
|
||||
from dataclasses import dataclass, field
|
||||
from os import environ
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
"""Package configuration with sensible defaults."""
|
||||
|
||||
timeout: int = 30
|
||||
retries: int = 3
|
||||
api_key: str | None = field(default=None)
|
||||
debug: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Environment variable fallbacks
|
||||
if self.api_key is None:
|
||||
self.api_key = environ.get("PACKAGE_API_KEY")
|
||||
|
||||
|
||||
# Module-level singleton (optional)
|
||||
_config: Config | None = None
|
||||
|
||||
|
||||
def get_config() -> Config:
|
||||
"""Get or create the global config instance."""
|
||||
global _config
|
||||
if _config is None:
|
||||
_config = Config()
|
||||
return _config
|
||||
|
||||
|
||||
def configure(**kwargs: Any) -> Config:
|
||||
"""Configure the package with custom settings."""
|
||||
global _config
|
||||
_config = Config(**kwargs)
|
||||
return _config
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Simple hierarchy with informative messages:
|
||||
|
||||
```python
|
||||
# src/package_name/exceptions.py
|
||||
class PackageError(Exception):
|
||||
"""Base exception for all package errors."""
|
||||
pass
|
||||
|
||||
|
||||
class ConfigError(PackageError):
|
||||
"""Invalid configuration."""
|
||||
pass
|
||||
|
||||
|
||||
class ValidationError(PackageError):
|
||||
"""Data validation failed."""
|
||||
|
||||
def __init__(self, message: str, field: str | None = None) -> None:
|
||||
self.field = field
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class APIError(PackageError):
|
||||
"""External API error."""
|
||||
|
||||
def __init__(self, message: str, status_code: int | None = None) -> None:
|
||||
self.status_code = status_code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
# Validate early with ValueError
|
||||
def process(data: bytes) -> str:
|
||||
if not data:
|
||||
raise ValueError("Data cannot be empty")
|
||||
if len(data) > 1_000_000:
|
||||
raise ValueError(f"Data too large: {len(data)} bytes (max 1MB)")
|
||||
return data.decode("utf-8")
|
||||
```
|
||||
|
||||
## Type Hints
|
||||
|
||||
Always use type hints with modern syntax (Python 3.10+):
|
||||
|
||||
```python
|
||||
# Use built-in generics, not typing module
|
||||
from collections.abc import Callable, Iterator, Mapping, Sequence
|
||||
|
||||
def process_items(
|
||||
items: list[str],
|
||||
transform: Callable[[str], str] | None = None,
|
||||
*,
|
||||
batch_size: int = 100,
|
||||
) -> Iterator[str]:
|
||||
"""Process items with optional transformation."""
|
||||
for item in items:
|
||||
if transform:
|
||||
yield transform(item)
|
||||
else:
|
||||
yield item
|
||||
|
||||
|
||||
# Use | for unions, not Union
|
||||
def get_value(key: str) -> str | None:
|
||||
return _cache.get(key)
|
||||
|
||||
|
||||
# Use Self for return type annotations (Python 3.11+)
|
||||
from typing import Self
|
||||
|
||||
class Client:
|
||||
def configure(self, **kwargs: str) -> Self:
|
||||
# Update configuration
|
||||
return self
|
||||
```
|
||||
|
||||
## Testing (pytest)
|
||||
|
||||
```python
|
||||
# tests/conftest.py
|
||||
import pytest
|
||||
from package_name import Config, configure
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config() -> Config:
|
||||
"""Fresh config for each test."""
|
||||
return configure(timeout=5, debug=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_data() -> bytes:
|
||||
"""Sample input data."""
|
||||
return b"test data content"
|
||||
|
||||
|
||||
# tests/test_core.py
|
||||
import pytest
|
||||
from package_name import process_data, PackageError
|
||||
|
||||
|
||||
class TestProcessData:
|
||||
"""Tests for process_data function."""
|
||||
|
||||
def test_basic_functionality(self, sample_data: bytes) -> None:
|
||||
result = process_data(sample_data)
|
||||
assert result == "test data content"
|
||||
|
||||
def test_empty_input_raises_error(self) -> None:
|
||||
with pytest.raises(ValueError, match="cannot be empty"):
|
||||
process_data(b"")
|
||||
|
||||
def test_with_transform(self, sample_data: bytes) -> None:
|
||||
result = process_data(sample_data, transform=str.upper)
|
||||
assert result == "TEST DATA CONTENT"
|
||||
|
||||
|
||||
class TestConfig:
|
||||
"""Tests for configuration."""
|
||||
|
||||
def test_defaults(self) -> None:
|
||||
config = Config()
|
||||
assert config.timeout == 30
|
||||
assert config.retries == 3
|
||||
|
||||
def test_env_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("PACKAGE_API_KEY", "test-key")
|
||||
config = Config()
|
||||
assert config.api_key == "test-key"
|
||||
```
|
||||
|
||||
## FastAPI Integration
|
||||
|
||||
Optional FastAPI integration pattern:
|
||||
|
||||
```python
|
||||
# src/package_name/fastapi.py
|
||||
"""FastAPI integration - only import if FastAPI is installed."""
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import FastAPI
|
||||
|
||||
from package_name.config import get_config
|
||||
|
||||
|
||||
def init_app(app: "FastAPI") -> None:
|
||||
"""Initialize package with FastAPI app."""
|
||||
config = get_config()
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup() -> None:
|
||||
# Initialize connections, caches, etc.
|
||||
pass
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown() -> None:
|
||||
# Cleanup resources
|
||||
pass
|
||||
|
||||
|
||||
# Usage in FastAPI app:
|
||||
# from package_name.fastapi import init_app
|
||||
# init_app(app)
|
||||
```
|
||||
|
||||
## Anti-Patterns to Avoid
|
||||
|
||||
- `__getattr__` magic (use explicit imports)
|
||||
- Global mutable state (use configuration objects)
|
||||
- `*` imports in `__init__.py` (explicit `__all__`)
|
||||
- Many runtime dependencies
|
||||
- Committing `.venv/` or `__pycache__/`
|
||||
- Not including `py.typed` marker
|
||||
- Using `setup.py` (use `pyproject.toml`)
|
||||
- Mixing src layout and flat layout
|
||||
- `print()` for debugging (use logging)
|
||||
- Bare `except:` clauses
|
||||
|
||||
## Reference Files
|
||||
|
||||
For deeper patterns, see:
|
||||
- **[references/package-structure.md](./references/package-structure.md)** - Directory layouts, module organization
|
||||
- **[references/pyproject-config.md](./references/pyproject-config.md)** - Complete pyproject.toml examples
|
||||
- **[references/testing-patterns.md](./references/testing-patterns.md)** - pytest patterns, fixtures, CI setup
|
||||
- **[references/type-hints.md](./references/type-hints.md)** - Modern typing patterns
|
||||
- **[references/fastapi-integration.md](./references/fastapi-integration.md)** - FastAPI/Pydantic integration
|
||||
- **[references/publishing.md](./references/publishing.md)** - PyPI publishing, CI/CD
|
||||
- **[references/resources.md](./references/resources.md)** - Links to exemplary Python packages
|
||||
120
plugins/compound-engineering/skills/ship-it/SKILL.md
Normal file
120
plugins/compound-engineering/skills/ship-it/SKILL.md
Normal file
@@ -0,0 +1,120 @@
|
||||
---
|
||||
name: ship-it
|
||||
description: This skill should be used when the user wants to ticket, branch, commit, and open a PR in one shot. It creates a Jira ticket from conversation context, assigns it, moves it to In Progress, creates a branch, commits changes, pushes, and opens a PR. Triggers on "ship it", "ticket and PR this", "put up a PR", "let's ship this", or any request to package completed work into a ticket + PR.
|
||||
---
|
||||
|
||||
# Ship It
|
||||
|
||||
End-to-end workflow: Jira ticket + branch + commit + push + PR from conversation context. Run after a fix or feature is done and needs to be formally shipped.
|
||||
|
||||
## Constants
|
||||
|
||||
- **Jira cloudId**: `9cbcbbfd-6b43-42ab-a91c-aaaafa8b7f32`
|
||||
- **Jira project**: `ZAS`
|
||||
- **Issue type**: `Story`
|
||||
- **Assignee accountId**: `712020:62c4d18e-a579-49c1-b228-72fbc63186de`
|
||||
- **PR target branch**: `stg` (unless specified otherwise)
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Gather Context
|
||||
|
||||
Analyze the conversation above to determine:
|
||||
- **What was done** — the fix, feature, or change
|
||||
- **Why** — the problem or motivation
|
||||
- **Which files changed** — run `git diff` and `git status` to see the actual changes
|
||||
|
||||
Synthesize a ticket summary (under 80 chars, imperative mood) and a brief description. Do not ask the user to describe the work — extract it from conversation context.
|
||||
|
||||
### Step 2: Create Jira Ticket
|
||||
|
||||
Use `/john-voice` to draft the ticket content, then create via MCP:
|
||||
|
||||
```
|
||||
mcp__atlassian__createJiraIssue
|
||||
cloudId: 9cbcbbfd-6b43-42ab-a91c-aaaafa8b7f32
|
||||
projectKey: ZAS
|
||||
issueTypeName: Story
|
||||
summary: <ticket title>
|
||||
description: <ticket body>
|
||||
assignee_account_id: 712020:62c4d18e-a579-49c1-b228-72fbc63186de
|
||||
contentFormat: markdown
|
||||
```
|
||||
|
||||
Extract the ticket key (e.g. `ZAS-123`) from the response.
|
||||
|
||||
### Step 3: Move to In Progress
|
||||
|
||||
Get transitions and find the "In Progress" transition ID:
|
||||
|
||||
```
|
||||
mcp__atlassian__getTransitionsForJiraIssue
|
||||
cloudId: 9cbcbbfd-6b43-42ab-a91c-aaaafa8b7f32
|
||||
issueIdOrKey: <ticket key>
|
||||
```
|
||||
|
||||
Then apply the transition:
|
||||
|
||||
```
|
||||
mcp__atlassian__transitionJiraIssue
|
||||
cloudId: 9cbcbbfd-6b43-42ab-a91c-aaaafa8b7f32
|
||||
issueIdOrKey: <ticket key>
|
||||
transition: { "id": "<transition_id>" }
|
||||
```
|
||||
|
||||
### Step 4: Create Branch
|
||||
|
||||
Create and switch to a new branch named after the ticket:
|
||||
|
||||
```bash
|
||||
git checkout -b <ticket-key>
|
||||
```
|
||||
|
||||
Example: `git checkout -b ZAS-123`
|
||||
|
||||
### Step 5: Commit Changes
|
||||
|
||||
Stage and commit all relevant changes. Use the ticket key as a prefix in the commit message. Follow project git conventions (lowercase, no periods, casual).
|
||||
|
||||
```bash
|
||||
git add <specific files>
|
||||
git commit -m "<ticket-key> <short description>"
|
||||
```
|
||||
|
||||
Example: `ZAS-123 fix candidate email field mapping`
|
||||
|
||||
Include the co-author trailer:
|
||||
```
|
||||
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
||||
```
|
||||
|
||||
### Step 6: Push and Open PR
|
||||
|
||||
Push the branch:
|
||||
|
||||
```bash
|
||||
git push -u origin <ticket-key>
|
||||
```
|
||||
|
||||
Use `/john-voice` to write the PR title and body. Create the PR:
|
||||
|
||||
```bash
|
||||
gh pr create --title "<PR title>" --base stg --body "<PR body>"
|
||||
```
|
||||
|
||||
PR body format:
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
<2-3 bullets describing the change>
|
||||
|
||||
## Jira
|
||||
[<ticket-key>](https://discoverorg.atlassian.net/browse/<ticket-key>)
|
||||
|
||||
## Test plan
|
||||
<bulleted checklist>
|
||||
```
|
||||
|
||||
### Step 7: Report
|
||||
|
||||
Output the ticket URL and PR URL to the user.
|
||||
48
plugins/compound-engineering/skills/story-lens/SKILL.md
Normal file
48
plugins/compound-engineering/skills/story-lens/SKILL.md
Normal file
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: story-lens
|
||||
description: This skill should be used when evaluating whether a piece of prose constitutes a high-quality story. It applies George Saunders's craft framework — causality, escalation, efficiency, expectation, and character accumulation — as a structured diagnostic lens. Triggers on requests like "is this a good story?", "review this prose", "does this feel like a story or just an anecdote?", "critique this narrative", or any request to assess the craft quality of fiction or narrative nonfiction.
|
||||
---
|
||||
|
||||
# Story Lens
|
||||
|
||||
A diagnostic skill for evaluating prose quality using George Saunders's storytelling framework. The framework operates on a single core insight: the difference between a story and an anecdote is causality plus irreversible change.
|
||||
|
||||
Load [saunders-framework.md](./references/saunders-framework.md) for the full framework, including all diagnostic questions and definitions.
|
||||
|
||||
## How to Apply the Skill
|
||||
|
||||
### 1. Read the Prose
|
||||
|
||||
Read the full piece before forming any judgments. Resist diagnosing on first pass.
|
||||
|
||||
### 2. Apply the Six Diagnostic Questions in Order
|
||||
|
||||
Each question builds on the previous.
|
||||
|
||||
**Beat Causality**
|
||||
Map the beats. Does each beat cause the next? Or are they sequential — "and then... and then..."? Sequential beats = anecdote. Causal beats = story.
|
||||
|
||||
**Escalation**
|
||||
Is the story moving up a staircase or running on a treadmill? Each step must be irrevocable. Once a character's condition has fundamentally changed, the story cannot re-enact that change or linger in elaboration. Look for sections that feel like they're holding still.
|
||||
|
||||
**The Story-Yet Test**
|
||||
Stop at the end of each major section and ask: *if it ended here, would it be complete?* Something must have changed irreversibly. If nothing has changed, everything so far is setup — not story.
|
||||
|
||||
**Character Accumulation**
|
||||
Track what the reader learns about the character, beat by beat. Is that knowledge growing? Does each beat confirm, complicate, or overturn prior understanding? Flat accumulation = underdeveloped character. Specificity accrues into care.
|
||||
|
||||
**The Three E's**
|
||||
Check against the triad: Escalation (moving forward), Efficiency (nothing extraneous), Expectation (next beat is surprising but not absurd). Failure in any one of these is diagnosable.
|
||||
|
||||
**Moral/Technical Unity**
|
||||
If something feels off emotionally or ethically — a character's choice that doesn't ring true, a resolution that feels unearned — look for the technical failure underneath. Saunders's claim: it is always there. Find the craft problem, and the moral problem dissolves.
|
||||
|
||||
### 3. Render a Verdict
|
||||
|
||||
After applying all six diagnostics, deliver a clear assessment:
|
||||
|
||||
- Is this a story, or still an anecdote?
|
||||
- Which diagnostic reveals the primary weakness?
|
||||
- What is the single most important structural fix?
|
||||
|
||||
Be direct. The framework produces precise, actionable diagnoses — not impressionistic feedback. Imprecise praise or vague encouragement is not useful here. The goal is to help the writer see exactly where the story is working and where it isn't.
|
||||
@@ -0,0 +1,75 @@
|
||||
# The Saunders Storytelling Framework
|
||||
|
||||
A distillation of George Saunders's craft principles for evaluating whether prose constitutes a high-quality story.
|
||||
|
||||
---
|
||||
|
||||
## The Fundamental Unit: The Beat
|
||||
|
||||
Every moment in a story is a beat. Each beat must *cause* the next beat. Saunders calls causality "what melody is to a songwriter" — it's the invisible connective tissue the audience feels as the story's logic.
|
||||
|
||||
The test: are beats **causal** or merely **sequential**?
|
||||
|
||||
- Sequential (anecdote): "this happened, then this happened"
|
||||
- Causal (story): "this happened, *therefore* this happened"
|
||||
|
||||
If beats are merely sequential, the work reads as anecdote, not story.
|
||||
|
||||
---
|
||||
|
||||
## What Transforms Anecdote into Story: Escalation
|
||||
|
||||
> "Always be escalating. That's all a story is, really: a continual system of escalation. A swath of prose earns its place in the story to the extent that it contributes to our sense that the story is still escalating."
|
||||
|
||||
Escalation isn't just raising stakes — it's **irrevocable change**. Once a story has moved forward through some fundamental change in a character's condition, you don't get to enact that change again, and you don't get to stay there elaborating on that state.
|
||||
|
||||
**The story is a staircase, not a treadmill.**
|
||||
|
||||
---
|
||||
|
||||
## The "Is This a Story Yet?" Diagnostic
|
||||
|
||||
Stop at any point and ask: *if it ended here, would it be complete?*
|
||||
|
||||
Early on, the answer is almost always no — because nothing has changed yet. The story only becomes a story at the moment something changes irreversibly.
|
||||
|
||||
**Precise test: change = story. No change = still just setup.**
|
||||
|
||||
---
|
||||
|
||||
## The "What Do We Know About This Character So Far?" Tool
|
||||
|
||||
Take inventory constantly. A reader's understanding of a character is always a running accumulation — and every beat should either **confirm**, **complicate**, or **overturn** that understanding.
|
||||
|
||||
The more we know about a person — their hopes, dreams, fears, and failures — the more compassionate we become toward them. This is how the empathy machine operates mechanically: **specificity accrues, and accrued specificity generates care.**
|
||||
|
||||
---
|
||||
|
||||
## The Three E's
|
||||
|
||||
Three words that capture the full framework:
|
||||
|
||||
1. **Escalation** — the story must continuously move forward through irrevocable change
|
||||
2. **Efficiency** — ruthlessly exclude anything extraneous to the story's purposes
|
||||
3. **Expectation** — what comes next must hit a Goldilocks level: not too obvious, not too absurd
|
||||
|
||||
---
|
||||
|
||||
## The Moral/Technical Unity
|
||||
|
||||
Any story that suffers from what seems like a **moral failing** will, with sufficient analytical attention, be found to be suffering from a **technical failing** — and if that failing is addressed, it will always become a better story.
|
||||
|
||||
This means: when a story feels wrong emotionally or ethically, look for the craft problem first. The fix is almost always structural.
|
||||
|
||||
---
|
||||
|
||||
## Summary: The Diagnostic Questions
|
||||
|
||||
Apply these in order to any piece of prose:
|
||||
|
||||
1. **Beat causality** — Does each beat cause the next, or are they merely sequential?
|
||||
2. **Escalation** — Is the story continuously moving up the staircase, or running on a treadmill?
|
||||
3. **Story-yet test** — If it ended here, would something have irreversibly changed?
|
||||
4. **Character accumulation** — Is our understanding of the character growing richer with each beat?
|
||||
5. **Three E's check** — Is it escalating, efficient, and pitched at the right level of expectation?
|
||||
6. **Moral/technical unity** — If something feels off morally or emotionally, where is the technical failure?
|
||||
153
plugins/compound-engineering/skills/sync-confluence/SKILL.md
Normal file
153
plugins/compound-engineering/skills/sync-confluence/SKILL.md
Normal file
@@ -0,0 +1,153 @@
|
||||
---
|
||||
name: sync-confluence
|
||||
description: This skill should be used when syncing local markdown documentation to Confluence Cloud pages. It handles first-time setup (creating mapping files and docs directories), pushing updates to existing pages, and creating new pages with interactive destination prompts. Triggers on "sync to confluence", "push docs to confluence", "update confluence pages", "create a confluence page", or any request to publish markdown content to Confluence.
|
||||
allowed-tools: Read, Bash(find *), Bash(source *), Bash(uv run *)
|
||||
---
|
||||
|
||||
# Sync Confluence
|
||||
|
||||
Sync local markdown files to Confluence Cloud pages via REST API. Handles the full lifecycle: first-time project setup, page creation, and bulk updates.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Two environment variables must be set (typically in `~/.zshrc`):
|
||||
|
||||
- `CONFLUENCE_EMAIL` — Atlassian account email
|
||||
- `CONFLUENCE_API_TOKEN_WRITE` — Atlassian API token with write scope (falls back to `CONFLUENCE_API_TOKEN`)
|
||||
|
||||
Generate tokens at: https://id.atlassian.com/manage-profile/security/api-tokens
|
||||
|
||||
The script requires `uv` to be installed. Dependencies (`markdown`, `requests`, `truststore`) are declared inline via PEP 723 and resolved automatically by `uv run`.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Check for Mapping File
|
||||
|
||||
Before running the sync script, check whether a `.confluence-mapping.json` exists in the project:
|
||||
|
||||
```bash
|
||||
find "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" -name ".confluence-mapping.json" -maxdepth 3 2>/dev/null
|
||||
```
|
||||
|
||||
- **If found** — skip to step 3 (Sync).
|
||||
- **If not found** — proceed to step 2 (First-Time Setup).
|
||||
|
||||
### 2. First-Time Setup
|
||||
|
||||
When no mapping file exists, gather configuration interactively via `AskUserQuestion`:
|
||||
|
||||
1. **Confluence base URL** — e.g., `https://myorg.atlassian.net/wiki`
|
||||
2. **Space key** — short identifier in Confluence URLs (e.g., `ZR`, `ENG`)
|
||||
3. **Parent page ID** — the page under which synced pages nest. Tell the user: "Open the parent page in Confluence — the page ID is the number in the URL."
|
||||
4. **Parent page title** — prefix for generated page titles (e.g., `ATS Platform`)
|
||||
5. **Docs directory** — where markdown files live relative to repo root (default: `docs/`)
|
||||
|
||||
Then create the docs directory and mapping file:
|
||||
|
||||
```python
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
config = {
|
||||
"confluence": {
|
||||
"cloudId": "<domain>.atlassian.net",
|
||||
"spaceId": "",
|
||||
"spaceKey": "<SPACE_KEY>",
|
||||
"baseUrl": "<BASE_URL>"
|
||||
},
|
||||
"parentPage": {
|
||||
"id": "<PARENT_PAGE_ID>",
|
||||
"title": "<PARENT_TITLE>",
|
||||
"url": "<BASE_URL>/spaces/<SPACE_KEY>/pages/<PARENT_PAGE_ID>"
|
||||
},
|
||||
"pages": {},
|
||||
"unmapped": [],
|
||||
"lastSynced": ""
|
||||
}
|
||||
|
||||
docs_dir = Path("<REPO_ROOT>") / "<DOCS_DIR>"
|
||||
docs_dir.mkdir(parents=True, exist_ok=True)
|
||||
mapping_path = docs_dir / ".confluence-mapping.json"
|
||||
mapping_path.write_text(json.dumps(config, indent=2) + "\n")
|
||||
```
|
||||
|
||||
To discover `spaceId` (required for page creation), run:
|
||||
|
||||
```bash
|
||||
source ~/.zshrc && curl -s -u "${CONFLUENCE_EMAIL}:${CONFLUENCE_API_TOKEN_WRITE}" \
|
||||
-H "X-Atlassian-Token: no-check" \
|
||||
"<BASE_URL>/rest/api/space/<SPACE_KEY>" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])"
|
||||
```
|
||||
|
||||
Update the mapping file with the discovered spaceId before proceeding.
|
||||
|
||||
### 3. Sync — Running the Script
|
||||
|
||||
The sync script is at `${CLAUDE_PLUGIN_ROOT}/skills/sync-confluence/scripts/sync_confluence.py`.
|
||||
|
||||
**Always source shell profile before running** to load env vars:
|
||||
|
||||
```bash
|
||||
source ~/.zshrc && uv run ${CLAUDE_PLUGIN_ROOT}/skills/sync-confluence/scripts/sync_confluence.py [options]
|
||||
```
|
||||
|
||||
#### Common Operations
|
||||
|
||||
| Command | What it does |
|
||||
|---------|-------------|
|
||||
| _(no flags)_ | Sync all markdown files in docs dir |
|
||||
| `--dry-run` | Preview changes without API calls |
|
||||
| `--file docs/my-doc.md` | Sync a single file |
|
||||
| `--update-only` | Only update existing pages, skip unmapped files |
|
||||
| `--create-only` | Only create new pages, skip existing |
|
||||
| `--mapping-file path/to/file` | Use a specific mapping file |
|
||||
| `--docs-dir path/to/dir` | Override docs directory |
|
||||
|
||||
### 4. Creating a New Confluence Page
|
||||
|
||||
When the user wants to create a new page:
|
||||
|
||||
1. Ask for the page topic/title
|
||||
2. Create the markdown file in the docs directory with a `# Title` heading and content
|
||||
3. Run the sync script with `--file` pointing to the new file
|
||||
4. The script detects the unmapped file, creates the page, and updates the mapping
|
||||
|
||||
**Title resolution order:** First `# H1` from the markdown → filename-derived title → raw filename. Titles are prefixed with the parent page title (e.g., `My Project: New Page`).
|
||||
|
||||
### 5. Mapping File Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"confluence": {
|
||||
"cloudId": "myorg.atlassian.net",
|
||||
"spaceId": "1234567890",
|
||||
"spaceKey": "ZR",
|
||||
"baseUrl": "https://myorg.atlassian.net/wiki"
|
||||
},
|
||||
"parentPage": {
|
||||
"id": "123456789",
|
||||
"title": "My Project",
|
||||
"url": "https://..."
|
||||
},
|
||||
"pages": {
|
||||
"my-doc.md": {
|
||||
"pageId": "987654321",
|
||||
"title": "My Project: My Doc",
|
||||
"url": "https://..."
|
||||
}
|
||||
},
|
||||
"unmapped": [],
|
||||
"lastSynced": "2026-03-03"
|
||||
}
|
||||
```
|
||||
|
||||
The script updates this file after each successful sync. Do not manually edit page entries unless correcting a known error.
|
||||
|
||||
## Technical Notes
|
||||
|
||||
- **Auth:** Confluence REST API v1 with Basic Auth + `X-Atlassian-Token: no-check`. Some Cloud instances block v2 or require this XSRF bypass.
|
||||
- **Content format:** Markdown converted to Confluence storage format (XHTML) via Python `markdown` library with tables, fenced code, and TOC extensions.
|
||||
- **SSL:** `truststore` delegates cert verification to the OS trust store, handling corporate SSL proxies (Zscaler, etc.).
|
||||
- **Rate limiting:** Automatic retry with backoff on 429 and 5xx responses.
|
||||
- **Sync timestamp:** `> **Last synced to Confluence**: YYYY-MM-DD` injected into the Confluence copy only. Local files are untouched.
|
||||
- **Versioning:** Page versions auto-increment. The script GETs the current version before PUTting.
|
||||
@@ -0,0 +1,529 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.11"
|
||||
# dependencies = ["markdown", "requests", "truststore"]
|
||||
# ///
|
||||
"""Sync markdown docs to Confluence Cloud.
|
||||
|
||||
Reads a .confluence-mapping.json file, syncs local markdown files
|
||||
to Confluence pages via REST API v2, and updates the mapping file.
|
||||
|
||||
Run with: uv run scripts/sync_confluence.py [options]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timezone, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
import truststore
|
||||
truststore.inject_into_ssl()
|
||||
|
||||
import markdown
|
||||
import requests
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Path discovery
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def find_repo_root() -> Path | None:
|
||||
"""Walk up from CWD to find a git repo root."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "--show-toplevel"],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
return Path(result.stdout.strip())
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
return None
|
||||
|
||||
|
||||
def find_mapping_file(start: Path) -> Path | None:
|
||||
"""Search for .confluence-mapping.json walking up from *start*.
|
||||
|
||||
Checks <dir>/docs/.confluence-mapping.json and
|
||||
<dir>/.confluence-mapping.json at each level.
|
||||
"""
|
||||
current = start.resolve()
|
||||
while True:
|
||||
for candidate in (
|
||||
current / "docs" / ".confluence-mapping.json",
|
||||
current / ".confluence-mapping.json",
|
||||
):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
parent = current.parent
|
||||
if parent == current:
|
||||
break
|
||||
current = parent
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mapping file helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def load_mapping(path: Path) -> dict:
|
||||
"""Load and lightly validate the mapping file."""
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
for key in ("confluence", "parentPage"):
|
||||
if key not in data:
|
||||
raise ValueError(f"Mapping file missing required key: '{key}'")
|
||||
data.setdefault("pages", {})
|
||||
data.setdefault("unmapped", [])
|
||||
return data
|
||||
|
||||
|
||||
def save_mapping(path: Path, data: dict) -> None:
|
||||
"""Write the mapping file with stable formatting."""
|
||||
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Markdown → Confluence storage format
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MD_EXTENSIONS = [
|
||||
"markdown.extensions.tables",
|
||||
"markdown.extensions.fenced_code",
|
||||
"markdown.extensions.toc",
|
||||
"markdown.extensions.md_in_html",
|
||||
"markdown.extensions.sane_lists",
|
||||
]
|
||||
|
||||
MD_EXTENSION_CONFIGS: dict = {
|
||||
"markdown.extensions.toc": {"permalink": False},
|
||||
}
|
||||
|
||||
|
||||
def md_to_storage(md_content: str) -> str:
|
||||
"""Convert markdown to Confluence storage-format XHTML."""
|
||||
return markdown.markdown(
|
||||
md_content,
|
||||
extensions=MD_EXTENSIONS,
|
||||
extension_configs=MD_EXTENSION_CONFIGS,
|
||||
output_format="xhtml",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Title helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def extract_h1(md_content: str) -> str | None:
|
||||
"""Return the first ``# Heading`` from *md_content*, or None."""
|
||||
for line in md_content.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("# ") and not stripped.startswith("## "):
|
||||
return stripped[2:].strip()
|
||||
return None
|
||||
|
||||
|
||||
def title_from_filename(filename: str) -> str:
|
||||
"""Derive a human-readable title from a kebab-case filename."""
|
||||
stem = filename.removesuffix(".md")
|
||||
words = stem.split("-")
|
||||
# Capitalise each word, then fix known acronyms/terms
|
||||
title = " ".join(w.capitalize() for w in words)
|
||||
acronyms = {
|
||||
"Ats": "ATS", "Api": "API", "Ms": "MS", "Unie": "UNIE",
|
||||
"Id": "ID", "Opa": "OPA", "Zi": "ZI", "Cql": "CQL",
|
||||
"Jql": "JQL", "Sdk": "SDK", "Oauth": "OAuth", "Cdn": "CDN",
|
||||
"Aws": "AWS", "Gcp": "GCP", "Grpc": "gRPC",
|
||||
}
|
||||
for wrong, right in acronyms.items():
|
||||
title = re.sub(rf"\b{wrong}\b", right, title)
|
||||
return title
|
||||
|
||||
|
||||
def resolve_title(filename: str, md_content: str, parent_title: str | None) -> str:
|
||||
"""Pick the best page title for a file.
|
||||
|
||||
Priority: H1 from markdown > filename-derived > raw filename.
|
||||
If *parent_title* is set, prefix with ``<parent>: <title>``.
|
||||
"""
|
||||
title = extract_h1(md_content) or title_from_filename(filename)
|
||||
if parent_title:
|
||||
# Avoid double-prefixing if the title already starts with parent
|
||||
if not title.startswith(parent_title):
|
||||
title = f"{parent_title}: {title}"
|
||||
return title
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync timestamp injection (Confluence copy only — local files untouched)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SYNC_RE = re.compile(r"> \*\*Last synced to Confluence\*\*:.*")
|
||||
|
||||
|
||||
def inject_sync_timestamp(md_content: str, sync_date: str) -> str:
|
||||
"""Add or update the sync-timestamp callout in *md_content*."""
|
||||
stamp = f"> **Last synced to Confluence**: {sync_date}"
|
||||
|
||||
if _SYNC_RE.search(md_content):
|
||||
return _SYNC_RE.sub(stamp, md_content)
|
||||
|
||||
lines = md_content.split("\n")
|
||||
insert_at = 0
|
||||
|
||||
# After YAML front-matter
|
||||
if lines and lines[0].strip() == "---":
|
||||
for i, line in enumerate(lines[1:], 1):
|
||||
if line.strip() == "---":
|
||||
insert_at = i + 1
|
||||
break
|
||||
# Or after first H1
|
||||
elif lines and lines[0].startswith("# "):
|
||||
insert_at = 1
|
||||
|
||||
lines.insert(insert_at, "")
|
||||
lines.insert(insert_at + 1, stamp)
|
||||
lines.insert(insert_at + 2, "")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Confluence REST API v1 client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ConfluenceClient:
|
||||
"""Thin wrapper around the Confluence Cloud REST API v1.
|
||||
|
||||
Uses Basic Auth (email + API token) with X-Atlassian-Token header,
|
||||
which is required by some Confluence Cloud instances that block v2
|
||||
or enforce XSRF protection.
|
||||
"""
|
||||
|
||||
def __init__(self, base_url: str, email: str, api_token: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.session = requests.Session()
|
||||
cred = base64.b64encode(f"{email}:{api_token}".encode()).decode()
|
||||
self.session.headers.update({
|
||||
"Authorization": f"Basic {cred}",
|
||||
"X-Atlassian-Token": "no-check",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
|
||||
# -- low-level helpers ---------------------------------------------------
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs) -> requests.Response:
|
||||
"""Make a request with basic retry on 429 / 5xx."""
|
||||
url = f"{self.base_url}{path}"
|
||||
for attempt in range(4):
|
||||
resp = self.session.request(method, url, **kwargs)
|
||||
if resp.status_code == 429:
|
||||
wait = int(resp.headers.get("Retry-After", 5))
|
||||
print(f" Rate-limited, waiting {wait}s …")
|
||||
time.sleep(wait)
|
||||
continue
|
||||
if resp.status_code >= 500 and attempt < 3:
|
||||
time.sleep(2 ** attempt)
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
return resp
|
||||
resp.raise_for_status() # final attempt — let it raise
|
||||
return resp # unreachable, keeps type-checkers happy
|
||||
|
||||
# -- page operations -----------------------------------------------------
|
||||
|
||||
def get_page(self, page_id: str) -> dict:
|
||||
"""Fetch page metadata including current version number."""
|
||||
return self._request(
|
||||
"GET", f"/rest/api/content/{page_id}",
|
||||
params={"expand": "version"},
|
||||
).json()
|
||||
|
||||
def create_page(
|
||||
self, *, space_key: str, parent_id: str, title: str, body: str,
|
||||
) -> dict:
|
||||
payload = {
|
||||
"type": "page",
|
||||
"title": title,
|
||||
"space": {"key": space_key},
|
||||
"ancestors": [{"id": parent_id}],
|
||||
"body": {
|
||||
"storage": {
|
||||
"value": body,
|
||||
"representation": "storage",
|
||||
},
|
||||
},
|
||||
}
|
||||
return self._request("POST", "/rest/api/content", json=payload).json()
|
||||
|
||||
def update_page(
|
||||
self, *, page_id: str, title: str, body: str, version_msg: str = "",
|
||||
) -> dict:
|
||||
current = self.get_page(page_id)
|
||||
next_ver = current["version"]["number"] + 1
|
||||
payload = {
|
||||
"type": "page",
|
||||
"title": title,
|
||||
"body": {
|
||||
"storage": {
|
||||
"value": body,
|
||||
"representation": "storage",
|
||||
},
|
||||
},
|
||||
"version": {"number": next_ver, "message": version_msg},
|
||||
}
|
||||
return self._request(
|
||||
"PUT", f"/rest/api/content/{page_id}", json=payload,
|
||||
).json()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# URL builder
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def page_url(base_url: str, space_key: str, page_id: str, title: str) -> str:
|
||||
"""Build a human-friendly Confluence page URL."""
|
||||
safe = quote(title.replace(" ", "+"), safe="+")
|
||||
return f"{base_url}/spaces/{space_key}/pages/{page_id}/{safe}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core sync logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def sync_file(
|
||||
client: ConfluenceClient,
|
||||
md_path: Path,
|
||||
mapping: dict,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
) -> dict | None:
|
||||
"""Sync one markdown file. Returns page-info dict or None on failure."""
|
||||
filename = md_path.name
|
||||
cfg = mapping["confluence"]
|
||||
parent = mapping["parentPage"]
|
||||
pages = mapping["pages"]
|
||||
existing = pages.get(filename)
|
||||
today = date.today().isoformat()
|
||||
|
||||
md_content = md_path.read_text(encoding="utf-8")
|
||||
md_for_confluence = inject_sync_timestamp(md_content, today)
|
||||
storage_body = md_to_storage(md_for_confluence)
|
||||
|
||||
# Resolve title — keep existing title for already-mapped pages
|
||||
if existing:
|
||||
title = existing["title"]
|
||||
else:
|
||||
title = resolve_title(filename, md_content, parent.get("title"))
|
||||
|
||||
base = cfg.get("baseUrl", "")
|
||||
space_key = cfg.get("spaceKey", "")
|
||||
|
||||
# -- update existing page ------------------------------------------------
|
||||
if existing:
|
||||
pid = existing["pageId"]
|
||||
if dry_run:
|
||||
print(f" [dry-run] update {filename} (page {pid})")
|
||||
return existing
|
||||
try:
|
||||
client.update_page(
|
||||
page_id=pid,
|
||||
title=title,
|
||||
body=storage_body,
|
||||
version_msg=f"Synced from local docs {today}",
|
||||
)
|
||||
url = page_url(base, space_key, pid, title)
|
||||
print(f" updated {filename}")
|
||||
return {"pageId": pid, "title": title, "url": url}
|
||||
except requests.HTTPError as exc:
|
||||
_report_error("update", filename, exc)
|
||||
return None
|
||||
|
||||
# -- create new page -----------------------------------------------------
|
||||
if dry_run:
|
||||
print(f" [dry-run] create {filename} → {title}")
|
||||
return {"pageId": "DRY_RUN", "title": title, "url": ""}
|
||||
try:
|
||||
result = client.create_page(
|
||||
space_key=cfg["spaceKey"],
|
||||
parent_id=parent["id"],
|
||||
title=title,
|
||||
body=storage_body,
|
||||
)
|
||||
pid = result["id"]
|
||||
url = page_url(base, space_key, pid, title)
|
||||
print(f" created {filename} (page {pid})")
|
||||
return {"pageId": pid, "title": title, "url": url}
|
||||
except requests.HTTPError as exc:
|
||||
_report_error("create", filename, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _report_error(verb: str, filename: str, exc: requests.HTTPError) -> None:
|
||||
print(f" FAILED {verb} {filename}: {exc}")
|
||||
if exc.response is not None:
|
||||
body = exc.response.text[:500]
|
||||
print(f" {body}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(
|
||||
description="Sync markdown docs to Confluence Cloud.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
environment variables
|
||||
CONFLUENCE_EMAIL Atlassian account email
|
||||
CONFLUENCE_API_TOKEN_WRITE Atlassian API token (write-scoped)
|
||||
CONFLUENCE_API_TOKEN Fallback if _WRITE is not set
|
||||
CONFLUENCE_BASE_URL Wiki base URL (overrides mapping file)
|
||||
|
||||
examples
|
||||
%(prog)s # sync all docs
|
||||
%(prog)s --dry-run # preview without changes
|
||||
%(prog)s --file docs/my-doc.md # sync one file
|
||||
%(prog)s --update-only # only update existing pages
|
||||
""",
|
||||
)
|
||||
p.add_argument("--docs-dir", type=Path,
|
||||
help="Docs directory (default: inferred from mapping file location)")
|
||||
p.add_argument("--mapping-file", type=Path,
|
||||
help="Path to .confluence-mapping.json (default: auto-detect)")
|
||||
p.add_argument("--file", type=Path, dest="single_file",
|
||||
help="Sync a single file instead of all docs")
|
||||
p.add_argument("--dry-run", action="store_true",
|
||||
help="Show what would happen without making API calls")
|
||||
p.add_argument("--create-only", action="store_true",
|
||||
help="Only create new pages (skip existing)")
|
||||
p.add_argument("--update-only", action="store_true",
|
||||
help="Only update existing pages (skip new)")
|
||||
return p
|
||||
|
||||
|
||||
def resolve_base_url(cfg: dict) -> str | None:
|
||||
"""Derive the Confluence base URL from env or mapping config."""
|
||||
from_env = os.environ.get("CONFLUENCE_BASE_URL")
|
||||
if from_env:
|
||||
return from_env.rstrip("/")
|
||||
from_cfg = cfg.get("baseUrl")
|
||||
if from_cfg:
|
||||
return from_cfg.rstrip("/")
|
||||
# cloudId might be a domain like "discoverorg.atlassian.net"
|
||||
cloud_id = cfg.get("cloudId", "")
|
||||
if "." in cloud_id:
|
||||
return f"https://{cloud_id}/wiki"
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
# -- discover paths ------------------------------------------------------
|
||||
repo_root = find_repo_root() or Path.cwd()
|
||||
|
||||
if args.mapping_file:
|
||||
mapping_path = args.mapping_file.resolve()
|
||||
else:
|
||||
mapping_path = find_mapping_file(repo_root)
|
||||
if not mapping_path or not mapping_path.is_file():
|
||||
print("ERROR: cannot find .confluence-mapping.json")
|
||||
print(" Pass --mapping-file or run from within the project.")
|
||||
sys.exit(1)
|
||||
|
||||
docs_dir = args.docs_dir.resolve() if args.docs_dir else mapping_path.parent
|
||||
print(f"mapping: {mapping_path}")
|
||||
print(f"docs dir: {docs_dir}")
|
||||
|
||||
# -- load config ---------------------------------------------------------
|
||||
mapping = load_mapping(mapping_path)
|
||||
cfg = mapping["confluence"]
|
||||
|
||||
email = os.environ.get("CONFLUENCE_EMAIL", "")
|
||||
# Prefer write-scoped token, fall back to general token
|
||||
token = (os.environ.get("CONFLUENCE_API_TOKEN_WRITE")
|
||||
or os.environ.get("CONFLUENCE_API_TOKEN", ""))
|
||||
base_url = resolve_base_url(cfg)
|
||||
|
||||
if not email or not token:
|
||||
print("ERROR: CONFLUENCE_EMAIL and CONFLUENCE_API_TOKEN_WRITE must be set.")
|
||||
print(" https://id.atlassian.com/manage-profile/security/api-tokens")
|
||||
sys.exit(1)
|
||||
if not base_url:
|
||||
print("ERROR: cannot determine Confluence base URL.")
|
||||
print(" Set CONFLUENCE_BASE_URL or add baseUrl to the mapping file.")
|
||||
sys.exit(1)
|
||||
|
||||
# Ensure baseUrl is persisted so page_url() works
|
||||
cfg.setdefault("baseUrl", base_url)
|
||||
|
||||
client = ConfluenceClient(base_url, email, token)
|
||||
|
||||
# -- collect files -------------------------------------------------------
|
||||
if args.single_file:
|
||||
target = args.single_file.resolve()
|
||||
if not target.is_file():
|
||||
print(f"ERROR: file not found: {target}")
|
||||
sys.exit(1)
|
||||
md_files = [target]
|
||||
else:
|
||||
md_files = sorted(
|
||||
p for p in docs_dir.glob("*.md")
|
||||
if not p.name.startswith(".")
|
||||
)
|
||||
if not md_files:
|
||||
print("No markdown files found.")
|
||||
sys.exit(0)
|
||||
|
||||
pages = mapping["pages"]
|
||||
if args.create_only:
|
||||
md_files = [f for f in md_files if f.name not in pages]
|
||||
elif args.update_only:
|
||||
md_files = [f for f in md_files if f.name in pages]
|
||||
|
||||
total = len(md_files)
|
||||
mode = "dry-run" if args.dry_run else "live"
|
||||
print(f"\n{total} file(s) to sync ({mode})\n")
|
||||
|
||||
# -- sync ----------------------------------------------------------------
|
||||
created = updated = failed = 0
|
||||
for i, md_path in enumerate(md_files, 1):
|
||||
filename = md_path.name
|
||||
is_new = filename not in pages
|
||||
prefix = f"[{i}/{total}]"
|
||||
|
||||
result = sync_file(client, md_path, mapping, dry_run=args.dry_run)
|
||||
if result:
|
||||
if not args.dry_run:
|
||||
pages[filename] = result
|
||||
if is_new:
|
||||
created += 1
|
||||
else:
|
||||
updated += 1
|
||||
else:
|
||||
failed += 1
|
||||
|
||||
# -- persist mapping -----------------------------------------------------
|
||||
if not args.dry_run and (created or updated):
|
||||
mapping["lastSynced"] = date.today().isoformat()
|
||||
# Clean synced files out of the unmapped list
|
||||
synced = {f.name for f in md_files}
|
||||
mapping["unmapped"] = [u for u in mapping.get("unmapped", []) if u not in synced]
|
||||
save_mapping(mapping_path, mapping)
|
||||
print(f"\nmapping file updated")
|
||||
|
||||
# -- summary -------------------------------------------------------------
|
||||
print(f"\ndone: {created} created · {updated} updated · {failed} failed")
|
||||
if failed:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
199
plugins/compound-engineering/skills/upstream-merge/SKILL.md
Normal file
199
plugins/compound-engineering/skills/upstream-merge/SKILL.md
Normal file
@@ -0,0 +1,199 @@
|
||||
---
|
||||
name: upstream-merge
|
||||
description: This skill should be used when incorporating upstream git changes into a local fork while preserving local intent. It provides a structured workflow for analyzing divergence, categorizing conflicts, creating triage todos for each conflict, reviewing decisions one-by-one with the user, and executing all resolutions. Triggers on "merge upstream", "incorporate upstream changes", "sync fork", or when local and remote branches have diverged significantly.
|
||||
---
|
||||
|
||||
# Upstream Merge
|
||||
|
||||
Incorporate upstream changes into a local fork without losing local intent. Analyze divergence, categorize every changed file, triage conflicts interactively, then execute all decisions in a single structured pass.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before starting, establish context:
|
||||
|
||||
1. **Identify the guiding principle** — ask the user what local intent must be preserved (e.g., "FastAPI pivot is non-negotiable", "custom branding must remain"). This principle governs every triage decision.
|
||||
2. **Confirm remote** — verify `git remote -v` shows the correct upstream origin.
|
||||
3. **Fetch latest** — `git fetch origin` to get current upstream state.
|
||||
|
||||
## Phase 1: Analyze Divergence
|
||||
|
||||
Gather the full picture before making any decisions.
|
||||
|
||||
**Run these commands:**
|
||||
|
||||
```bash
|
||||
# Find common ancestor
|
||||
git merge-base HEAD origin/main
|
||||
|
||||
# Count divergence
|
||||
git rev-list --count HEAD ^origin/main # local-only commits
|
||||
git rev-list --count origin/main ^HEAD # remote-only commits
|
||||
|
||||
# List all changed files on each side
|
||||
git diff --name-only $(git merge-base HEAD origin/main) HEAD > /tmp/local-changes.txt
|
||||
git diff --name-only $(git merge-base HEAD origin/main) origin/main > /tmp/remote-changes.txt
|
||||
```
|
||||
|
||||
**Categorize every file into three buckets:**
|
||||
|
||||
| Bucket | Definition | Action |
|
||||
|--------|-----------|--------|
|
||||
| **Remote-only** | Changed upstream, untouched locally | Accept automatically |
|
||||
| **Local-only** | Changed locally, untouched upstream | Keep as-is |
|
||||
| **Both-changed** | Modified on both sides | Create triage todo |
|
||||
|
||||
```bash
|
||||
# Generate buckets
|
||||
comm -23 <(sort /tmp/remote-changes.txt) <(sort /tmp/local-changes.txt) > /tmp/remote-only.txt
|
||||
comm -13 <(sort /tmp/remote-changes.txt) <(sort /tmp/local-changes.txt) > /tmp/local-only.txt
|
||||
comm -12 <(sort /tmp/remote-changes.txt) <(sort /tmp/local-changes.txt) > /tmp/both-changed.txt
|
||||
```
|
||||
|
||||
**Present summary to user:**
|
||||
|
||||
```
|
||||
Divergence Analysis:
|
||||
- Common ancestor: [commit hash]
|
||||
- Local: X commits ahead | Remote: Y commits ahead
|
||||
- Remote-only: N files (auto-accept)
|
||||
- Local-only: N files (auto-keep)
|
||||
- Both-changed: N files (need triage)
|
||||
```
|
||||
|
||||
## Phase 2: Create Triage Todos
|
||||
|
||||
For each file in the "both-changed" bucket, create a triage todo using the template at [merge-triage-template.md](./assets/merge-triage-template.md).
|
||||
|
||||
**Process:**
|
||||
|
||||
1. Determine next issue ID: `ls todos/ | grep -o '^[0-9]\+' | sort -n | tail -1`
|
||||
2. For each both-changed file:
|
||||
- Read both versions (local and remote)
|
||||
- Generate the diff: `git diff $(git merge-base HEAD origin/main)..origin/main -- <file>`
|
||||
- Analyze what each side intended
|
||||
- Write a recommendation based on the guiding principle
|
||||
- Create todo: `todos/{id}-pending-p2-merge-{brief-name}.md`
|
||||
|
||||
**Naming convention for merge triage todos:**
|
||||
|
||||
```
|
||||
{id}-pending-p2-merge-{component-name}.md
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `001-pending-p2-merge-marketplace-json.md`
|
||||
- `002-pending-p2-merge-kieran-python-reviewer.md`
|
||||
- `003-pending-p2-merge-workflows-review.md`
|
||||
|
||||
**Use parallel agents** to create triage docs when there are many conflicts (batch 4-6 at a time).
|
||||
|
||||
**Announce when complete:**
|
||||
|
||||
```
|
||||
Created N triage todos in todos/. Ready to review one-by-one.
|
||||
```
|
||||
|
||||
## Phase 3: Triage (Review One-by-One)
|
||||
|
||||
Present each triage todo to the user for a decision. Follow the `/triage` command pattern.
|
||||
|
||||
**For each conflict, present:**
|
||||
|
||||
```
|
||||
---
|
||||
Conflict X/N: [filename]
|
||||
|
||||
Category: [agent/command/skill/config]
|
||||
Conflict Type: [content/modify-delete/add-add]
|
||||
|
||||
Remote intent: [what upstream changed and why]
|
||||
Local intent: [what local changed and why]
|
||||
|
||||
Recommendation: [Accept remote / Keep local / Merge both / Keep deleted]
|
||||
Reasoning: [why, referencing the guiding principle]
|
||||
|
||||
---
|
||||
How should we handle this?
|
||||
1. Accept remote — take upstream version as-is
|
||||
2. Keep local — preserve local version
|
||||
3. Merge both — combine changes (specify how)
|
||||
4. Keep deleted — file was deleted locally, keep it deleted
|
||||
```
|
||||
|
||||
**Use AskUserQuestion tool** for each decision with appropriate options.
|
||||
|
||||
**Record decisions** by updating the triage todo:
|
||||
- Fill the "Decision" section with the chosen resolution
|
||||
- Add merge instructions if "merge both" was selected
|
||||
- Update status: `pending` → `ready`
|
||||
|
||||
**Group related files** when presenting (e.g., present all 7 dspy-ruby files together, not separately).
|
||||
|
||||
**Track progress:** Show "X/N completed" with each presentation.
|
||||
|
||||
## Phase 4: Execute Decisions
|
||||
|
||||
After all triage decisions are made, execute them in a structured order.
|
||||
|
||||
### Step 1: Create Working Branch
|
||||
|
||||
```bash
|
||||
git branch backup-local-changes # safety net
|
||||
git checkout -b merge-upstream origin/main
|
||||
```
|
||||
|
||||
### Step 2: Execute in Order
|
||||
|
||||
Process decisions in this sequence to avoid conflicts:
|
||||
|
||||
1. **Deletions first** — Remove files that should stay deleted
|
||||
2. **Copy local-only files** — `git checkout backup-local-changes -- <file>` for local additions
|
||||
3. **Merge files** — Apply "merge both" decisions (the most complex step)
|
||||
4. **Update metadata** — Counts, versions, descriptions, changelogs
|
||||
|
||||
### Step 3: Verify
|
||||
|
||||
```bash
|
||||
# Validate JSON/YAML files
|
||||
cat <config-files> | python3 -m json.tool > /dev/null
|
||||
|
||||
# Verify component counts match descriptions
|
||||
# (skill-specific: count agents, commands, skills, etc.)
|
||||
|
||||
# Check diff summary
|
||||
git diff --stat HEAD
|
||||
```
|
||||
|
||||
### Step 4: Commit and Merge to Main
|
||||
|
||||
```bash
|
||||
git add <specific-files> # stage explicitly, not -A
|
||||
git commit -m "Merge upstream vX.Y.Z with [guiding principle] (vX.Y.Z+1)"
|
||||
git checkout main
|
||||
git merge merge-upstream
|
||||
```
|
||||
|
||||
**Ask before merging to main** — confirm the user wants to proceed.
|
||||
|
||||
## Decision Framework
|
||||
|
||||
When making recommendations, apply these heuristics:
|
||||
|
||||
| Signal | Recommendation |
|
||||
|--------|---------------|
|
||||
| Remote adds new content, no local equivalent | Accept remote |
|
||||
| Remote updates content local deleted intentionally | Keep deleted |
|
||||
| Remote has structural improvements (formatting, frontmatter) + local has content changes | Merge both: remote structure + local content |
|
||||
| Both changed same content differently | Merge both: evaluate which serves the guiding principle |
|
||||
| Remote renames what local deleted | Keep deleted |
|
||||
| File is metadata (counts, versions, descriptions) | Defer to Phase 4 — recalculate from actual files |
|
||||
|
||||
## Important Rules
|
||||
|
||||
- **Never auto-resolve "both-changed" files** — always triage with user
|
||||
- **Never code during triage** — triage is for decisions only, execution is Phase 4
|
||||
- **Always create a backup branch** before making changes
|
||||
- **Always stage files explicitly** — never `git add -A` or `git add .`
|
||||
- **Group related files** — don't present 7 files from the same skill directory separately
|
||||
- **Metadata is derived, not merged** — counts, versions, and descriptions should be recalculated from actual files after all other changes are applied
|
||||
- **Preserve the guiding principle** — every recommendation should reference it
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
status: pending
|
||||
priority: p2
|
||||
issue_id: "XXX"
|
||||
tags: [upstream-merge]
|
||||
dependencies: []
|
||||
---
|
||||
|
||||
# Merge Conflict: [filename]
|
||||
|
||||
## File Info
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| **File** | `path/to/file` |
|
||||
| **Category** | agent / command / skill / config / other |
|
||||
| **Conflict Type** | content / modify-delete / add-add |
|
||||
|
||||
## What Changed
|
||||
|
||||
### Remote Version
|
||||
|
||||
[What the upstream version added, changed, or intended]
|
||||
|
||||
### Local Version
|
||||
|
||||
[What the local version added, changed, or intended]
|
||||
|
||||
## Diff
|
||||
|
||||
<details>
|
||||
<summary>Show diff</summary>
|
||||
|
||||
```diff
|
||||
[Relevant diff content]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Recommendation
|
||||
|
||||
**Suggested resolution:** Accept remote / Keep local / Merge both / Keep deleted
|
||||
|
||||
[Reasoning for the recommendation, considering the local fork's guiding principles]
|
||||
|
||||
## Decision
|
||||
|
||||
**Resolution:** *(filled during triage)*
|
||||
|
||||
**Details:** *(specific merge instructions if "merge both")*
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Resolution applied correctly
|
||||
- [ ] No content lost unintentionally
|
||||
- [ ] Local intent preserved
|
||||
- [ ] File validates (JSON/YAML if applicable)
|
||||
Reference in New Issue
Block a user