@blackbelt-technology/pi-dashboard-authoring-toolkit 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ ---
2
+ name: session-to-guideline
3
+ description: >
4
+ Turn a pi session into a Markdown "how-we-did-it" collaboration guideline. Reads a
5
+ session's JSONL transcript, extracts the user's goal, every steering/correction turn,
6
+ the tools/files/searches used, and any skills or memories created — then synthesizes a
7
+ reusable playbook explaining how the task was performed WITH the AI: which prompts
8
+ worked, what had to be steered, which skills were created and why they're effective,
9
+ and how to reproduce the result faster.
10
+ Use when: "document this session", "write up how we did X with the AI", "make a
11
+ guideline from this session", "turn this session into a playbook/tutorial",
12
+ "summarize what we built and how I steered it".
13
+ ---
14
+
15
+ # Session → Collaboration Guideline
16
+
17
+ Produces a Markdown document that reads like a **playbook for collaborating with the AI**
18
+ on a task — not a raw transcript. It separates the *goal* from the *steering*, surfaces
19
+ the skills/memories created and why they work, and ends with a reproduce-it checklist.
20
+
21
+ Two layers:
22
+
23
+ 1. **Deterministic extract** (`scripts/extract_session.ts`) — parses the session JSONL on
24
+ the active branch and emits a structured **facts sheet** (prompts in order, tool usage,
25
+ files written/edited, searches, skills/memories created, failed commands, cost). This is
26
+ raw material, not the deliverable. TypeScript, run with `npx tsx` (repo convention).
27
+ 2. **Synthesis (you, the agent)** — read the facts sheet and write the guideline using
28
+ `references/guideline-template.md`. The *why it's effective* and *what to steer* parts
29
+ require judgment; that's your job.
30
+
31
+ ## Where sessions live
32
+
33
+ `~/.pi/agent/sessions/--<cwd-with-slashes-as-dashes>--/<timestamp>_<uuid>.jsonl`
34
+ (JSONL tree; see the pi `session-format` docs). The scripts locate files for you.
35
+
36
+ ## Procedure
37
+
38
+ 1. **Pick the session.** If the user didn't name one, list candidates:
39
+ ```bash
40
+ npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --limit 20 # this project
41
+ npx tsx scripts/list_sessions.ts --all --limit 30 # every project
42
+ ```
43
+ (`tsx` runs the `.ts` directly, no build step.)
44
+ Show the table and confirm which one (by 8-char id or # index). The *current* live
45
+ session is usually #0/`latest`; documenting a finished prior session gives a complete
46
+ picture (the live one won't include the not-yet-written tail).
47
+
48
+ 2. **Extract the facts sheet** (cheap, deterministic):
49
+ ```bash
50
+ npx tsx scripts/extract_session.ts <id-or-'latest'> --cwd "$(pwd)" \
51
+ --out-md /tmp/session_facts.md --out-json /tmp/session_facts.json
52
+ ```
53
+ - `<selector>` may be an 8-char id, a full path, or `latest` (use `--index N` for the
54
+ Nth most recent).
55
+ - Use `--max-text` / `--max-cmd` to widen truncation if you need more prompt/command text.
56
+
57
+ 3. **Read the facts sheet** (`/tmp/session_facts.md`). Pay attention to:
58
+ - **Prompt 1 = the goal**; **prompts 2..N = steering** (corrections, scope additions,
59
+ quality bars, yes/all-three style unlocks).
60
+ - **Skills created / Memories saved** — these are the reusable assets; explain *why*.
61
+ - **Tool errors / failed commands** — these become the *Pitfalls* section.
62
+ - **Artifacts** — the files the operator ends up with.
63
+
64
+ 4. **Synthesize the guideline** following `references/guideline-template.md`. Fill every
65
+ section. Rules:
66
+ - Write for a *future operator with the same goal* — instructive, not a log.
67
+ - Turn each steering turn into a **guardrail** ("the AI tended to X → state Y up front").
68
+ - For each skill/memory created, state the reusable problem it solves and when to invoke it.
69
+ - Rewrite weak prompts into the stronger version the reader should use.
70
+ - Quote sparingly; summarize tool activity into phases.
71
+
72
+ 5. **Write the deliverable.** Default location, unless the user says otherwise:
73
+ ```
74
+ <cwd>/Prompt stories/<Topic>.md
75
+ ```
76
+ (Do NOT write it inside a skill folder.) Name the file after the session name/topic.
77
+ When the write-up references images (storyboards, screenshots), link them with paths
78
+ relative to `Prompt stories/` (e.g. `../Projektek/<Project>/.../shot_01.png`) and verify
79
+ each resolves. Tell the user the path.
80
+
81
+ ## Selector cheatsheet
82
+
83
+ | Goal | Command |
84
+ |------|---------|
85
+ | Latest session in this project | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)"` |
86
+ | 2nd-most-recent | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)" --index 1` |
87
+ | A specific session by id | `npx tsx scripts/extract_session.ts 019ea8a9` |
88
+ | A session in another project | `npx tsx scripts/extract_session.ts latest --cwd /path/to/other` |
89
+ | An explicit file | `npx tsx scripts/extract_session.ts /abs/path/to/session.jsonl` |
90
+
91
+ ## Notes & pitfalls
92
+
93
+ - The extractor walks the **active branch only** (leaf → root via `parentId`), so abandoned
94
+ `/tree` branches are excluded — you document what actually happened.
95
+ - Tool names are normalized (`mcp__pi__web_search` → `web_search`); `skill` and `memory`
96
+ calls are captured with their action/scope/target so "skills created & why effective" is
97
+ easy to write.
98
+ - The `Tokens total` includes cache reads, so it can dwarf the in/out numbers — report cost,
99
+ not raw total, if it looks confusing.
100
+ - No third-party deps; TypeScript on Node built-ins (`fs`/`path`/`os`). Run with `npx tsx`
101
+ — no compile/build step. Scripts never write to the session store.
102
+ - If a session is huge, raise `--max-cmds` only when you actually need more commands; the
103
+ default keeps the facts sheet token-cheap.
@@ -0,0 +1,77 @@
1
+ # How we did it: <Task title> — an AI collaboration guideline
2
+
3
+ > A reusable playbook reconstructed from a real pi session. It explains **what was
4
+ > asked, how it was built with the AI, what had to be steered, and how to reproduce
5
+ > the result faster next time.** Write for a future operator who has the same goal.
6
+
7
+ ---
8
+
9
+ ## 1. Goal (the ask)
10
+
11
+ One paragraph: what the user originally wanted, in plain language. Quote the first
12
+ prompt, then restate the *real* objective once the steering turns clarified it.
13
+
14
+ ## 2. TL;DR playbook
15
+
16
+ A numbered, copy-pasteable sequence of the moves that actually worked — the shortest
17
+ path from zero to the finished artifact. 5–10 steps. Each step = one concrete action
18
+ (a prompt to give, a tool/skill to run, a file to produce). This is the part a reader
19
+ will skim first.
20
+
21
+ ## 3. How the collaboration unfolded
22
+
23
+ Narrative of the session as phases (group the tool activity into 3–6 phases, e.g.
24
+ *Discovery → Gather → Design → Generate → Verify*). For each phase:
25
+
26
+ - **What the AI did** (the tools/files, summarized — not a raw log).
27
+ - **Why that approach worked** (the effective bit worth repeating).
28
+ - **The decision points** where the human chose a direction.
29
+
30
+ ## 4. Prompts that worked
31
+
32
+ List the prompts that moved the work forward, with a short note on *why each was
33
+ effective*. Distinguish:
34
+
35
+ - **The goal prompt** — what made it (or would have made it) a good kickoff.
36
+ - **High-leverage follow-ups** — short prompts that unlocked a lot ("all three",
37
+ "yes", "do X everywhere").
38
+
39
+ Rewrite weak prompts into a stronger version a future user should use instead.
40
+
41
+ ## 5. Steering & corrections (what to watch for)
42
+
43
+ The heart of the guideline. From the steering turns, extract the moments where the
44
+ human had to redirect the AI, and turn each into a *guardrail*:
45
+
46
+ | The AI tended to… | The human had to steer by… | Bake this in next time by… |
47
+ |-------------------|----------------------------|----------------------------|
48
+ | e.g. drift the brand name | "always write BlackBelt" | stating naming rules up front / saving a memory |
49
+
50
+ Include corrections, scope expansions ("there are also emails from X"), and
51
+ quality bars the user imposed.
52
+
53
+ ## 6. Skills, tools & memory created — and why they're effective
54
+
55
+ For each skill/memory/subagent created in the session:
56
+
57
+ - **What it captures** and the reusable problem it solves.
58
+ - **Why it's effective** (what manual work it removes, what it makes reproducible).
59
+ - **When to invoke it** next time.
60
+
61
+ If no skill was created but the workflow is clearly repeatable, recommend the skill
62
+ that *should* be created.
63
+
64
+ ## 7. Pitfalls & dead ends
65
+
66
+ Failed commands, retried edits, things that didn't work, blind alleys. Each as a
67
+ "if you hit X, do Y" note so the reader avoids the same loss.
68
+
69
+ ## 8. Reproduce it faster — checklist
70
+
71
+ A tight checklist (the distilled, no-narrative version of §2) plus the key inputs
72
+ the operator must have ready (API keys, source files, config) and the final
73
+ artifacts produced (paths).
74
+
75
+ ---
76
+
77
+ _Generated from session `<session-id>` · `<cwd>` · <date>. Source extract: `<facts file>`._
@@ -0,0 +1,488 @@
1
+ #!/usr/bin/env -S npx tsx
2
+ /**
3
+ * Extract a structured "facts sheet" from a pi session JSONL file.
4
+ *
5
+ * The output is NOT the final guideline. It is the deterministic raw material
6
+ * (prompts, tool usage, files touched, skills/memories created, steering turns,
7
+ * errors) that the agent then synthesizes into a human-readable collaboration
8
+ * guideline (see SKILL.md).
9
+ *
10
+ * Run with npx tsx:
11
+ * npx tsx scripts/extract_session.ts <selector> [options]
12
+ *
13
+ * Selector:
14
+ * /abs/path/to/session.jsonl explicit file
15
+ * <partial-uuid> match any session file whose name contains it
16
+ * latest most recent session for --cwd (default)
17
+ * . alias for latest in current cwd
18
+ *
19
+ * Options:
20
+ * --cwd PATH working dir whose sessions to search (default: process.cwd())
21
+ * --index N with 'latest', pick the Nth most recent (0=newest)
22
+ * --out-md PATH write the markdown facts sheet here (default: stdout)
23
+ * --out-json PATH also write the structured JSON here
24
+ * --max-text N truncate each assistant/user text block to N chars (default 1200)
25
+ * --max-cmd N truncate each shown bash command to N chars (default 200)
26
+ * --max-cmds N max bash commands listed (default 60)
27
+ * --include-thinking reserved (assistant reasoning omitted by default)
28
+ */
29
+ import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from "node:fs";
30
+ import { join, basename } from "node:path";
31
+ import { homedir } from "node:os";
32
+
33
+ const HOME = homedir();
34
+ const SESS_ROOT = join(HOME, ".pi", "agent", "sessions");
35
+
36
+ // ---------- tiny arg parser ----------
37
+
38
+ interface Args {
39
+ selector: string;
40
+ cwd: string;
41
+ index: number;
42
+ outMd?: string;
43
+ outJson?: string;
44
+ maxText: number;
45
+ maxCmd: number;
46
+ maxCmds: number;
47
+ includeThinking: boolean;
48
+ }
49
+
50
+ function parseArgs(argv: string[]): Args {
51
+ const a: Args = {
52
+ selector: "latest",
53
+ cwd: process.cwd(),
54
+ index: 0,
55
+ maxText: 1200,
56
+ maxCmd: 200,
57
+ maxCmds: 60,
58
+ includeThinking: false,
59
+ };
60
+ const positionals: string[] = [];
61
+ for (let i = 0; i < argv.length; i++) {
62
+ const t = argv[i];
63
+ const next = () => argv[++i];
64
+ switch (t) {
65
+ case "--cwd": a.cwd = next(); break;
66
+ case "--index": a.index = parseInt(next(), 10) || 0; break;
67
+ case "--out-md": a.outMd = next(); break;
68
+ case "--out-json": a.outJson = next(); break;
69
+ case "--max-text": a.maxText = parseInt(next(), 10) || a.maxText; break;
70
+ case "--max-cmd": a.maxCmd = parseInt(next(), 10) || a.maxCmd; break;
71
+ case "--max-cmds": a.maxCmds = parseInt(next(), 10) || a.maxCmds; break;
72
+ case "--include-thinking": a.includeThinking = true; break;
73
+ default:
74
+ if (t.startsWith("--")) { /* ignore unknown flag */ }
75
+ else positionals.push(t);
76
+ }
77
+ }
78
+ if (positionals.length) a.selector = positionals[0];
79
+ return a;
80
+ }
81
+
82
+ function die(msg: string): never {
83
+ process.stderr.write(msg + "\n");
84
+ process.exit(1);
85
+ }
86
+
87
+ // ---------- locating the session file ----------
88
+
89
+ function encodeCwd(cwd: string): string {
90
+ // mirror pi's session dir naming: "-" + abspath-with-slashes-as-dashes + "--"
91
+ return "-" + cwd.replace(/\/+$/, "").replace(/\//g, "-") + "--";
92
+ }
93
+
94
+ function listJsonl(dir: string): string[] {
95
+ if (!existsSync(dir)) return [];
96
+ return readdirSync(dir)
97
+ .filter((f) => f.endsWith(".jsonl"))
98
+ .map((f) => join(dir, f));
99
+ }
100
+
101
+ function findSession(selector: string, cwd: string, index: number): string {
102
+ // 1) explicit existing path
103
+ if (selector && existsSync(selector) && statSync(selector).isFile()) return selector;
104
+
105
+ // 2) latest / . -> most recent for cwd
106
+ if (["latest", ".", ""].includes(selector)) {
107
+ const d = join(SESS_ROOT, encodeCwd(cwd));
108
+ const files = listJsonl(d)
109
+ .map((f) => ({ f, mt: statSync(f).mtimeMs }))
110
+ .sort((a, b) => b.mt - a.mt)
111
+ .map((x) => x.f);
112
+ if (!files.length) die(`No sessions found for cwd ${cwd}\n (looked in ${d})`);
113
+ if (index >= files.length) die(`--index ${index} out of range; only ${files.length} sessions for ${cwd}`);
114
+ return files[index];
115
+ }
116
+
117
+ // 3) partial id -> search every session dir
118
+ const hits: string[] = [];
119
+ if (existsSync(SESS_ROOT)) {
120
+ for (const sub of readdirSync(SESS_ROOT)) {
121
+ const d = join(SESS_ROOT, sub);
122
+ if (!statSync(d).isDirectory()) continue;
123
+ for (const f of listJsonl(d)) if (basename(f).includes(selector)) hits.push(f);
124
+ }
125
+ }
126
+ if (!hits.length) die(`No session file matches '${selector}'`);
127
+ return hits
128
+ .map((f) => ({ f, mt: statSync(f).mtimeMs }))
129
+ .sort((a, b) => b.mt - a.mt)[0].f;
130
+ }
131
+
132
+ // ---------- parsing ----------
133
+
134
+ type Entry = Record<string, any>;
135
+
136
+ function loadEntries(path: string): { header: Entry | null; entries: Entry[] } {
137
+ const entries: Entry[] = [];
138
+ let header: Entry | null = null;
139
+ const text = readFileSync(path, "utf8");
140
+ for (const raw of text.split("\n")) {
141
+ const line = raw.trim();
142
+ if (!line) continue;
143
+ let e: Entry;
144
+ try { e = JSON.parse(line); } catch { continue; }
145
+ if (e.type === "session") header = e;
146
+ else entries.push(e);
147
+ }
148
+ return { header, entries };
149
+ }
150
+
151
+ /** Active branch (root -> leaf) via id/parentId; falls back to file order (v1). */
152
+ function activePath(entries: Entry[]): Entry[] {
153
+ const byId = new Map<string, Entry>();
154
+ for (const e of entries) if (e.id) byId.set(e.id, e);
155
+ if (!byId.size) return entries;
156
+
157
+ let leaf: Entry | null = null;
158
+ for (let i = entries.length - 1; i >= 0; i--) {
159
+ if (entries[i].id) { leaf = entries[i]; break; }
160
+ }
161
+ if (!leaf) return entries;
162
+
163
+ const chain: Entry[] = [];
164
+ const seen = new Set<string>();
165
+ let cur: Entry | null = leaf;
166
+ while (cur && !seen.has(cur.id)) {
167
+ seen.add(cur.id);
168
+ chain.push(cur);
169
+ cur = cur.parentId ? byId.get(cur.parentId) ?? null : null;
170
+ }
171
+ chain.reverse();
172
+ return chain;
173
+ }
174
+
175
+ // ---------- helpers ----------
176
+
177
+ const shortTool = (name: string): string =>
178
+ name && name.startsWith("mcp__") ? name.split("__").pop()! : name || "?";
179
+
180
+ function textOf(content: any): string {
181
+ if (typeof content === "string") return content;
182
+ const out: string[] = [];
183
+ for (const c of content ?? []) {
184
+ if (c && c.type === "text") out.push(c.text ?? "");
185
+ else if (c && c.type === "image") out.push("[image]");
186
+ }
187
+ return out.join("\n").trim();
188
+ }
189
+
190
+ function tsToIso(ts?: number): string {
191
+ if (!ts) return "";
192
+ const d = new Date(ts);
193
+ if (isNaN(d.getTime())) return "";
194
+ const p = (n: number) => String(n).padStart(2, "0");
195
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
196
+ }
197
+
198
+ function trunc(s: string, n: number): string {
199
+ s = (s ?? "").trim();
200
+ return s.length <= n ? s : s.slice(0, n).trimEnd() + " …[truncated]";
201
+ }
202
+
203
+ // ---------- extraction ----------
204
+
205
+ interface FactData {
206
+ session_id: string | null;
207
+ cwd: string | null;
208
+ session_name: string | null;
209
+ started: string | null;
210
+ ended: string | null;
211
+ duration: string | null;
212
+ models: string[];
213
+ thinking_levels: string[];
214
+ counts: { user: number; assistant: number; toolResult: number };
215
+ tool_counts: Record<string, number>;
216
+ tool_errors: Record<string, number>;
217
+ turns: { n: number; time: string; text: string; is_first: boolean }[];
218
+ assistant_notes: { time: string; text: string }[];
219
+ files_written: string[];
220
+ files_edited: string[];
221
+ files_read: string[];
222
+ bash: { cmd: string; error: boolean }[];
223
+ searches: { tool: string; q: any }[];
224
+ skills: any[];
225
+ memories: any[];
226
+ subagents: any[];
227
+ usage: { input: number; output: number; total_tokens: number; cost: number };
228
+ _source_file?: string;
229
+ }
230
+
231
+ function classifyTool(name: string, a: Record<string, any>, isErr: boolean, d: FactData): void {
232
+ if (name === "write" && a.path) d.files_written.push(a.path);
233
+ else if (name === "edit" && a.path) d.files_edited.push(a.path);
234
+ else if (name === "read" && a.path) d.files_read.push(a.path);
235
+ else if (name === "bash" && a.command) d.bash.push({ cmd: a.command, error: isErr });
236
+ else if (["web_search", "code_search", "fetch_content"].includes(name) &&
237
+ (a.query || a.queries || a.url || a.urls)) {
238
+ d.searches.push({ tool: name, q: a.query ?? a.queries ?? a.url ?? a.urls });
239
+ } else if (name === "skill") {
240
+ d.skills.push({
241
+ action: a.action, name: a.name ?? a.skill_id, scope: a.scope,
242
+ description: a.description, section: a.section,
243
+ });
244
+ } else if (name === "memory") {
245
+ d.memories.push({
246
+ action: a.action, target: a.target, category: a.category,
247
+ content: trunc(a.content ?? a.old_text ?? "", 200),
248
+ });
249
+ } else if (["Agent", "agent", "task"].includes(name)) {
250
+ d.subagents.push({ type: a.subagent_type, desc: a.description, model: a.model });
251
+ }
252
+ }
253
+
254
+ function extract(header: Entry | null, path: Entry[]): FactData {
255
+ const byCallId = new Map<string, Entry>();
256
+ for (const e of path) {
257
+ if (e.type === "message" && e.message?.role === "toolResult") {
258
+ byCallId.set(e.message.toolCallId, e.message);
259
+ }
260
+ }
261
+
262
+ const d: FactData = {
263
+ session_id: header?.id ?? null,
264
+ cwd: header?.cwd ?? null,
265
+ session_name: null,
266
+ started: null, ended: null, duration: null,
267
+ models: [], thinking_levels: [],
268
+ counts: { user: 0, assistant: 0, toolResult: 0 },
269
+ tool_counts: {}, tool_errors: {},
270
+ turns: [], assistant_notes: [],
271
+ files_written: [], files_edited: [], files_read: [],
272
+ bash: [], searches: [], skills: [], memories: [], subagents: [],
273
+ usage: { input: 0, output: 0, total_tokens: 0, cost: 0 },
274
+ };
275
+
276
+ let firstTs: number | null = null;
277
+ let lastTs: number | null = null;
278
+ let userTurnNo = 0;
279
+ const modelsSeen: string[] = [];
280
+
281
+ for (const e of path) {
282
+ const et = e.type;
283
+ if (et === "session_info" && e.name) {
284
+ d.session_name = e.name;
285
+ } else if (et === "model_change") {
286
+ const m = `${e.provider ?? ""}/${e.modelId ?? ""}`.replace(/^\/|\/$/g, "");
287
+ if (m && !modelsSeen.includes(m)) modelsSeen.push(m);
288
+ } else if (et === "thinking_level_change") {
289
+ const lv = e.thinkingLevel;
290
+ if (lv && !d.thinking_levels.includes(lv)) d.thinking_levels.push(lv);
291
+ } else if (et === "message") {
292
+ const m = e.message;
293
+ const role = m.role;
294
+ const ts: number | undefined = m.timestamp;
295
+ if (ts) {
296
+ firstTs = firstTs === null ? ts : Math.min(firstTs, ts);
297
+ lastTs = lastTs === null ? ts : Math.max(lastTs, ts);
298
+ }
299
+
300
+ if (role === "user") {
301
+ d.counts.user++;
302
+ const txt = textOf(m.content);
303
+ if (txt) {
304
+ userTurnNo++;
305
+ d.turns.push({ n: userTurnNo, time: tsToIso(ts), text: txt, is_first: userTurnNo === 1 });
306
+ }
307
+ } else if (role === "assistant") {
308
+ d.counts.assistant++;
309
+ const mdl = `${m.provider ?? ""}/${m.model ?? ""}`.replace(/^\/|\/$/g, "");
310
+ if (mdl && !modelsSeen.includes(mdl)) modelsSeen.push(mdl);
311
+ const u = m.usage ?? {};
312
+ d.usage.input += u.input ?? 0;
313
+ d.usage.output += u.output ?? 0;
314
+ d.usage.total_tokens += u.totalTokens ?? 0;
315
+ d.usage.cost += u.cost?.total ?? 0;
316
+ const note = textOf(m.content);
317
+ if (note) d.assistant_notes.push({ time: tsToIso(ts), text: note });
318
+ for (const c of m.content ?? []) {
319
+ if (!(c && c.type === "toolCall")) continue;
320
+ const name = shortTool(c.name ?? "");
321
+ const args = c.arguments ?? {};
322
+ d.tool_counts[name] = (d.tool_counts[name] ?? 0) + 1;
323
+ const res = byCallId.get(c.id);
324
+ const isErr = Boolean(res && res.isError);
325
+ if (isErr) d.tool_errors[name] = (d.tool_errors[name] ?? 0) + 1;
326
+ classifyTool(name, args, isErr, d);
327
+ }
328
+ } else if (role === "toolResult") {
329
+ d.counts.toolResult++;
330
+ }
331
+ }
332
+ }
333
+
334
+ d.models = modelsSeen;
335
+ d.started = firstTs ? tsToIso(firstTs) : null;
336
+ d.ended = lastTs ? tsToIso(lastTs) : null;
337
+ if (firstTs && lastTs) {
338
+ const secs = Math.floor((lastTs - firstTs) / 1000);
339
+ d.duration = secs >= 3600
340
+ ? `${Math.floor(secs / 3600)}h ${Math.floor((secs % 3600) / 60)}m`
341
+ : `${Math.floor(secs / 60)}m ${secs % 60}s`;
342
+ }
343
+
344
+ // dedup file lists, keep order
345
+ for (const k of ["files_written", "files_edited", "files_read"] as const) {
346
+ d[k] = [...new Set(d[k])];
347
+ }
348
+ return d;
349
+ }
350
+
351
+ // ---------- markdown facts sheet ----------
352
+
353
+ function renderMd(d: FactData, args: Args): string {
354
+ const L: string[] = [];
355
+ const title = d.session_name ?? d.session_id ?? "session";
356
+ L.push(`# Session facts: ${title}\n`);
357
+ L.push("> Deterministic extract — raw material for the collaboration guideline. " +
358
+ "Synthesize, don't paste verbatim.\n");
359
+
360
+ L.push("## Metadata\n");
361
+ L.push(`- **Session id:** \`${d.session_id}\``);
362
+ if (d.session_name) L.push(`- **Name:** ${d.session_name}`);
363
+ L.push(`- **Working dir:** \`${d.cwd}\``);
364
+ L.push(`- **Started / ended:** ${d.started} → ${d.ended} (${d.duration})`);
365
+ if (d.models.length) L.push(`- **Model(s):** ${d.models.join(", ")}`);
366
+ if (d.thinking_levels.length) L.push(`- **Thinking level(s):** ${d.thinking_levels.join(", ")}`);
367
+ const c = d.counts;
368
+ L.push(`- **Messages:** ${c.user} user · ${c.assistant} assistant · ${c.toolResult} tool results`);
369
+ const u = d.usage;
370
+ L.push(`- **Tokens:** ${u.total_tokens.toLocaleString("en-US")} total ` +
371
+ `(${u.input.toLocaleString("en-US")} in / ${u.output.toLocaleString("en-US")} out) · ` +
372
+ `**cost:** $${u.cost.toFixed(4)}\n`);
373
+
374
+ if (Object.keys(d.tool_counts).length) {
375
+ L.push("## Tool usage\n");
376
+ L.push("| Tool | Calls | Errors |");
377
+ L.push("|------|-------|--------|");
378
+ for (const [name, n] of Object.entries(d.tool_counts).sort((a, b) => b[1] - a[1])) {
379
+ L.push(`| ${name} | ${n} | ${d.tool_errors[name] ?? 0} |`);
380
+ }
381
+ L.push("");
382
+ }
383
+
384
+ L.push("## User prompts (in order)\n");
385
+ L.push("The **first** prompt is the goal. Later prompts are *steering* — the corrections, " +
386
+ "clarifications, and redirections that shaped the result.\n");
387
+ for (const t of d.turns) {
388
+ const tag = t.is_first ? "🎯 GOAL" : `↪ steering #${t.n - 1}`;
389
+ L.push(`### Prompt ${t.n} · ${tag} _( ${t.time} )_`);
390
+ L.push("```");
391
+ L.push(trunc(t.text, args.maxText));
392
+ L.push("```");
393
+ }
394
+ L.push("");
395
+
396
+ if (d.skills.length) {
397
+ L.push("## Skills created / modified\n");
398
+ for (const s of d.skills) {
399
+ const extra = s.description ? ` — _${trunc(s.description, 160)}_` : "";
400
+ const sec = s.section ? ` (section: ${s.section})` : "";
401
+ L.push(`- **${s.action}** \`${s.name}\` [${s.scope ?? "?"}]${sec}${extra}`);
402
+ }
403
+ L.push("");
404
+ }
405
+
406
+ if (d.memories.length) {
407
+ L.push("## Memories saved\n");
408
+ for (const m of d.memories) {
409
+ const cat = m.category ? ` · ${m.category}` : "";
410
+ L.push(`- **${m.action}** → ${m.target}${cat}: ${m.content}`);
411
+ }
412
+ L.push("");
413
+ }
414
+
415
+ if (d.subagents.length) {
416
+ L.push("## Subagents spawned\n");
417
+ for (const s of d.subagents) {
418
+ L.push(`- \`${s.type}\`${s.model ? ` (${s.model})` : ""}: ${s.desc}`);
419
+ }
420
+ L.push("");
421
+ }
422
+
423
+ if (d.files_written.length || d.files_edited.length) {
424
+ L.push("## Artifacts (files created / edited)\n");
425
+ for (const p of d.files_written) L.push(`- ✏️ created \`${p}\``);
426
+ for (const p of d.files_edited) L.push(`- 🔧 edited \`${p}\``);
427
+ L.push("");
428
+ }
429
+
430
+ if (d.searches.length) {
431
+ L.push("## Research (searches / fetches)\n");
432
+ for (const s of d.searches.slice(0, 30)) {
433
+ const q = Array.isArray(s.q) ? s.q.join(", ") : String(s.q);
434
+ L.push(`- [${s.tool}] ${trunc(q, 160)}`);
435
+ }
436
+ L.push("");
437
+ }
438
+
439
+ if (d.bash.length) {
440
+ L.push("## Commands run\n");
441
+ const fails = d.bash.filter((b) => b.error);
442
+ L.push(`_${d.bash.length} commands, ${fails.length} failed._\n`);
443
+ for (const b of d.bash.slice(0, args.maxCmds)) {
444
+ const flag = b.error ? "❌ " : "";
445
+ L.push(`- ${flag}\`${trunc(b.cmd, args.maxCmd)}\``);
446
+ }
447
+ if (d.bash.length > args.maxCmds) L.push(`- … +${d.bash.length - args.maxCmds} more`);
448
+ L.push("");
449
+ }
450
+
451
+ if (d.assistant_notes.length) {
452
+ L.push("## Assistant explanations (condensed)\n");
453
+ L.push("_What the model said it was doing — useful for the narrative & rationale._\n");
454
+ for (const n of d.assistant_notes) {
455
+ const txt = trunc(n.text, args.maxText);
456
+ if (txt) L.push(`**[${n.time}]** ${txt}\n`);
457
+ }
458
+ }
459
+ return L.join("\n");
460
+ }
461
+
462
+ // ---------- main ----------
463
+
464
+ function main(): void {
465
+ const args = parseArgs(process.argv.slice(2));
466
+ const path = findSession(args.selector, args.cwd, args.index);
467
+ const { header, entries } = loadEntries(path);
468
+ const chain = activePath(entries);
469
+ const data = extract(header, chain);
470
+ data._source_file = path;
471
+
472
+ const md = renderMd(data, args);
473
+
474
+ if (args.outJson) {
475
+ writeFileSync(args.outJson, JSON.stringify(data, null, 2), "utf8");
476
+ process.stderr.write(`[wrote json] ${args.outJson}\n`);
477
+ }
478
+ if (args.outMd) {
479
+ writeFileSync(args.outMd, md, "utf8");
480
+ process.stderr.write(`[wrote md] ${args.outMd}\n`);
481
+ process.stderr.write(`[source] ${path}\n`);
482
+ } else {
483
+ process.stdout.write(md + "\n");
484
+ process.stderr.write(`\n[source] ${path}\n`);
485
+ }
486
+ }
487
+
488
+ main();
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env -S npx tsx
2
+ /**
3
+ * List recent pi sessions so a session can be chosen for documentation.
4
+ *
5
+ * Run with npx tsx:
6
+ * npx tsx scripts/list_sessions.ts [--cwd PATH] [--limit N] [--all]
7
+ *
8
+ * Without --all, lists sessions for --cwd (default: current working directory),
9
+ * newest first, with id, time, name, message count, and the first user prompt.
10
+ */
11
+ import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
12
+ import { join, basename } from "node:path";
13
+ import { homedir } from "node:os";
14
+
15
+ const HOME = homedir();
16
+ const SESS_ROOT = join(HOME, ".pi", "agent", "sessions");
17
+
18
+ interface Args { cwd: string; limit: number; all: boolean; }
19
+
20
+ function parseArgs(argv: string[]): Args {
21
+ const a: Args = { cwd: process.cwd(), limit: 20, all: false };
22
+ for (let i = 0; i < argv.length; i++) {
23
+ const t = argv[i];
24
+ if (t === "--cwd") a.cwd = argv[++i];
25
+ else if (t === "--limit") a.limit = parseInt(argv[++i], 10) || a.limit;
26
+ else if (t === "--all") a.all = true;
27
+ }
28
+ return a;
29
+ }
30
+
31
+ const encodeCwd = (cwd: string): string =>
32
+ "-" + cwd.replace(/\/+$/, "").replace(/\//g, "-") + "--";
33
+
34
+ function listJsonl(dir: string): string[] {
35
+ if (!existsSync(dir)) return [];
36
+ return readdirSync(dir).filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
37
+ }
38
+
39
+ function firstPromptAndName(path: string): { name: string | null; prompt: string; msgs: number } {
40
+ let name: string | null = null;
41
+ let prompt: string | null = null;
42
+ let msgs = 0;
43
+ try {
44
+ const text = readFileSync(path, "utf8");
45
+ for (const raw of text.split("\n")) {
46
+ const line = raw.trim();
47
+ if (!line) continue;
48
+ let e: Record<string, any>;
49
+ try { e = JSON.parse(line); } catch { continue; }
50
+ if (e.type === "session_info" && e.name) {
51
+ name = e.name;
52
+ } else if (e.type === "message") {
53
+ const m = e.message;
54
+ if (m.role === "user" || m.role === "assistant") msgs++;
55
+ if (m.role === "user" && prompt === null) {
56
+ if (typeof m.content === "string") prompt = m.content;
57
+ else if (Array.isArray(m.content)) {
58
+ for (const b of m.content) {
59
+ if (b && b.type === "text") { prompt = b.text; break; }
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+ } catch { /* ignore unreadable files */ }
66
+ return { name, prompt: (prompt ?? "").trim().replace(/\n/g, " "), msgs };
67
+ }
68
+
69
+ function fmtTime(ms: number): string {
70
+ const d = new Date(ms);
71
+ const p = (n: number) => String(n).padStart(2, "0");
72
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
73
+ }
74
+
75
+ function main(): void {
76
+ const args = parseArgs(process.argv.slice(2));
77
+
78
+ let files: string[] = [];
79
+ if (args.all) {
80
+ if (existsSync(SESS_ROOT)) {
81
+ for (const sub of readdirSync(SESS_ROOT)) {
82
+ const d = join(SESS_ROOT, sub);
83
+ if (statSync(d).isDirectory()) files.push(...listJsonl(d));
84
+ }
85
+ }
86
+ } else {
87
+ files = listJsonl(join(SESS_ROOT, encodeCwd(args.cwd)));
88
+ }
89
+
90
+ files = files
91
+ .map((f) => ({ f, mt: statSync(f).mtimeMs }))
92
+ .sort((a, b) => b.mt - a.mt)
93
+ .slice(0, args.limit)
94
+ .map((x) => x.f);
95
+
96
+ if (!files.length) {
97
+ console.log(`No sessions found (${args.all ? "all projects" : args.cwd}).`);
98
+ return;
99
+ }
100
+
101
+ console.log(`${"#".padStart(2)} ${"when".padEnd(19)} ${"msgs".padStart(4)} id / name / first prompt`);
102
+ console.log("-".repeat(100));
103
+ files.forEach((f, i) => {
104
+ const when = fmtTime(statSync(f).mtimeMs);
105
+ const sid = basename(f).split("_").slice(1).join("_").replace(".jsonl", "");
106
+ const { name, prompt, msgs } = firstPromptAndName(f);
107
+ const label = name ?? (prompt.slice(0, 70) + (prompt.length > 70 ? "…" : ""));
108
+ console.log(`${String(i).padStart(2)} ${when.padEnd(19)} ${String(msgs).padStart(4)} ${sid.slice(0, 8)} ${label}`);
109
+ });
110
+ console.log("\nPick with: npx tsx scripts/extract_session.ts <id-or-'latest'> --cwd <dir>");
111
+ console.log(" (use 'latest --index N' to pick the Nth-most-recent by the # column)");
112
+ }
113
+
114
+ main();
@@ -0,0 +1,356 @@
1
+ ---
2
+ name: skill-creator
3
+ description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
4
+ license: MIT
5
+ ---
6
+
7
+ # Skill Creator
8
+
9
+ This skill provides guidance for creating effective skills.
10
+
11
+ ## About Skills
12
+
13
+ Skills are modular, self-contained packages that extend Claude's capabilities by providing
14
+ specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
15
+ domains or tasks—they transform Claude from a general-purpose agent into a specialized agent
16
+ equipped with procedural knowledge that no model can fully possess.
17
+
18
+ ### What Skills Provide
19
+
20
+ 1. Specialized workflows - Multi-step procedures for specific domains
21
+ 2. Tool integrations - Instructions for working with specific file formats or APIs
22
+ 3. Domain expertise - Company-specific knowledge, schemas, business logic
23
+ 4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
24
+
25
+ ## Core Principles
26
+
27
+ ### Concise is Key
28
+
29
+ The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
30
+
31
+ **Default assumption: Claude is already very smart.** Only add context Claude doesn't already have. Challenge each piece of information: "Does Claude really need this explanation?" and "Does this paragraph justify its token cost?"
32
+
33
+ Prefer concise examples over verbose explanations.
34
+
35
+ ### Set Appropriate Degrees of Freedom
36
+
37
+ Match the level of specificity to the task's fragility and variability:
38
+
39
+ **High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
40
+
41
+ **Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
42
+
43
+ **Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
44
+
45
+ Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
46
+
47
+ ### Anatomy of a Skill
48
+
49
+ Every skill consists of a required SKILL.md file and optional bundled resources:
50
+
51
+ ```
52
+ skill-name/
53
+ ├── SKILL.md (required)
54
+ │ ├── YAML frontmatter metadata (required)
55
+ │ │ ├── name: (required)
56
+ │ │ └── description: (required)
57
+ │ └── Markdown instructions (required)
58
+ └── Bundled Resources (optional)
59
+ ├── scripts/ - Executable code (Python/Bash/etc.)
60
+ ├── references/ - Documentation intended to be loaded into context as needed
61
+ └── assets/ - Files used in output (templates, icons, fonts, etc.)
62
+ ```
63
+
64
+ #### SKILL.md (required)
65
+
66
+ Every SKILL.md consists of:
67
+
68
+ - **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
69
+ - **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
70
+
71
+ #### Bundled Resources (optional)
72
+
73
+ ##### Scripts (`scripts/`)
74
+
75
+ Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
76
+
77
+ - **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
78
+ - **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
79
+ - **Benefits**: Token efficient, deterministic, may be executed without loading into context
80
+ - **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
81
+
82
+ ##### References (`references/`)
83
+
84
+ Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
85
+
86
+ - **When to include**: For documentation that Claude should reference while working
87
+ - **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
88
+ - **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
89
+ - **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed
90
+ - **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
91
+ - **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
92
+
93
+ ##### Assets (`assets/`)
94
+
95
+ Files not intended to be loaded into context, but rather used within the output Claude produces.
96
+
97
+ - **When to include**: When the skill needs files that will be used in the final output
98
+ - **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
99
+ - **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
100
+ - **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
101
+
102
+ #### What to Not Include in a Skill
103
+
104
+ A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
105
+
106
+ - README.md
107
+ - INSTALLATION_GUIDE.md
108
+ - QUICK_REFERENCE.md
109
+ - CHANGELOG.md
110
+ - etc.
111
+
112
+ The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
113
+
114
+ ### Progressive Disclosure Design Principle
115
+
116
+ Skills use a three-level loading system to manage context efficiently:
117
+
118
+ 1. **Metadata (name + description)** - Always in context (~100 words)
119
+ 2. **SKILL.md body** - When skill triggers (<5k words)
120
+ 3. **Bundled resources** - As needed by Claude (Unlimited because scripts can be executed without reading into context window)
121
+
122
+ #### Progressive Disclosure Patterns
123
+
124
+ Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
125
+
126
+ **Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
127
+
128
+ **Pattern 1: High-level guide with references**
129
+
130
+ ```markdown
131
+ # PDF Processing
132
+
133
+ ## Quick start
134
+
135
+ Extract text with pdfplumber:
136
+ [code example]
137
+
138
+ ## Advanced features
139
+
140
+ - **Form filling**: See [FORMS.md](FORMS.md) for complete guide
141
+ - **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
142
+ - **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
143
+ ```
144
+
145
+ Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
146
+
147
+ **Pattern 2: Domain-specific organization**
148
+
149
+ For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
150
+
151
+ ```
152
+ bigquery-skill/
153
+ ├── SKILL.md (overview and navigation)
154
+ └── reference/
155
+ ├── finance.md (revenue, billing metrics)
156
+ ├── sales.md (opportunities, pipeline)
157
+ ├── product.md (API usage, features)
158
+ └── marketing.md (campaigns, attribution)
159
+ ```
160
+
161
+ When a user asks about sales metrics, Claude only reads sales.md.
162
+
163
+ Similarly, for skills supporting multiple frameworks or variants, organize by variant:
164
+
165
+ ```
166
+ cloud-deploy/
167
+ ├── SKILL.md (workflow + provider selection)
168
+ └── references/
169
+ ├── aws.md (AWS deployment patterns)
170
+ ├── gcp.md (GCP deployment patterns)
171
+ └── azure.md (Azure deployment patterns)
172
+ ```
173
+
174
+ When the user chooses AWS, Claude only reads aws.md.
175
+
176
+ **Pattern 3: Conditional details**
177
+
178
+ Show basic content, link to advanced content:
179
+
180
+ ```markdown
181
+ # DOCX Processing
182
+
183
+ ## Creating documents
184
+
185
+ Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
186
+
187
+ ## Editing documents
188
+
189
+ For simple edits, modify the XML directly.
190
+
191
+ **For tracked changes**: See [REDLINING.md](REDLINING.md)
192
+ **For OOXML details**: See [OOXML.md](OOXML.md)
193
+ ```
194
+
195
+ Claude reads REDLINING.md or OOXML.md only when the user needs those features.
196
+
197
+ **Important guidelines:**
198
+
199
+ - **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
200
+ - **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing.
201
+
202
+ ## Skill Creation Process
203
+
204
+ Skill creation involves these steps:
205
+
206
+ 1. Understand the skill with concrete examples
207
+ 2. Plan reusable skill contents (scripts, references, assets)
208
+ 3. Initialize the skill (run init_skill.py)
209
+ 4. Edit the skill (implement resources and write SKILL.md)
210
+ 5. Package the skill (run package_skill.py)
211
+ 6. Iterate based on real usage
212
+
213
+ Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
214
+
215
+ ### Step 1: Understanding the Skill with Concrete Examples
216
+
217
+ Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
218
+
219
+ To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
220
+
221
+ For example, when building an image-editor skill, relevant questions include:
222
+
223
+ - "What functionality should the image-editor skill support? Editing, rotating, anything else?"
224
+ - "Can you give some examples of how this skill would be used?"
225
+ - "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
226
+ - "What would a user say that should trigger this skill?"
227
+
228
+ To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
229
+
230
+ Conclude this step when there is a clear sense of the functionality the skill should support.
231
+
232
+ ### Step 2: Planning the Reusable Skill Contents
233
+
234
+ To turn concrete examples into an effective skill, analyze each example by:
235
+
236
+ 1. Considering how to execute on the example from scratch
237
+ 2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
238
+
239
+ Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
240
+
241
+ 1. Rotating a PDF requires re-writing the same code each time
242
+ 2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
243
+
244
+ Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
245
+
246
+ 1. Writing a frontend webapp requires the same boilerplate HTML/React each time
247
+ 2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
248
+
249
+ Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
250
+
251
+ 1. Querying BigQuery requires re-discovering the table schemas and relationships each time
252
+ 2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
253
+
254
+ To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
255
+
256
+ ### Step 3: Initializing the Skill
257
+
258
+ At this point, it is time to actually create the skill.
259
+
260
+ Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
261
+
262
+ When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
263
+
264
+ Usage:
265
+
266
+ ```bash
267
+ scripts/init_skill.py <skill-name> --path <output-directory>
268
+ ```
269
+
270
+ The script:
271
+
272
+ - Creates the skill directory at the specified path
273
+ - Generates a SKILL.md template with proper frontmatter and TODO placeholders
274
+ - Creates example resource directories: `scripts/`, `references/`, and `assets/`
275
+ - Adds example files in each directory that can be customized or deleted
276
+
277
+ After initialization, customize or remove the generated SKILL.md and example files as needed.
278
+
279
+ ### Step 4: Edit the Skill
280
+
281
+ When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Include information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
282
+
283
+ #### Learn Proven Design Patterns
284
+
285
+ Consult these helpful guides based on your skill's needs:
286
+
287
+ - **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
288
+ - **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
289
+
290
+ These files contain established best practices for effective skill design.
291
+
292
+ #### Start with Reusable Skill Contents
293
+
294
+ To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
295
+
296
+ Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
297
+
298
+ Any example files and directories not needed for the skill should be deleted. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them.
299
+
300
+ #### Update SKILL.md
301
+
302
+ **Writing Guidelines:** Always use imperative/infinitive form.
303
+
304
+ ##### Frontmatter
305
+
306
+ Write the YAML frontmatter with `name` and `description`:
307
+
308
+ - `name`: The skill name
309
+ - `description`: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill.
310
+ - Include both what the Skill does and specific triggers/contexts for when to use it.
311
+ - Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude.
312
+ - Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
313
+
314
+ Do not include any other fields in YAML frontmatter.
315
+
316
+ ##### Body
317
+
318
+ Write instructions for using the skill and its bundled resources.
319
+
320
+ ### Step 5: Packaging a Skill
321
+
322
+ Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
323
+
324
+ ```bash
325
+ scripts/package_skill.py <path/to/skill-folder>
326
+ ```
327
+
328
+ Optional output directory specification:
329
+
330
+ ```bash
331
+ scripts/package_skill.py <path/to/skill-folder> ./dist
332
+ ```
333
+
334
+ The packaging script will:
335
+
336
+ 1. **Validate** the skill automatically, checking:
337
+
338
+ - YAML frontmatter format and required fields
339
+ - Skill naming conventions and directory structure
340
+ - Description completeness and quality
341
+ - File organization and resource references
342
+
343
+ 2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
344
+
345
+ If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
346
+
347
+ ### Step 6: Iterate
348
+
349
+ After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
350
+
351
+ **Iteration workflow:**
352
+
353
+ 1. Use the skill on real tasks
354
+ 2. Notice struggles or inefficiencies
355
+ 3. Identify how SKILL.md or bundled resources should be updated
356
+ 4. Implement changes and test again
package/NOTICE ADDED
@@ -0,0 +1,42 @@
1
+ @blackbelt-technology/pi-dashboard-authoring-toolkit
2
+
3
+ This package includes skill content derived from:
4
+
5
+ skill-creator
6
+ Copyright (c) 2025 Anthropic, PBC
7
+ Licensed under the MIT License
8
+ https://github.com/anthropics/skills
9
+
10
+ The `skill-creator` skill is a derived work of Anthropic's upstream skill of the
11
+ same name. The skill body is reproduced under the MIT License; only the YAML
12
+ frontmatter `license:` field was tidied to reference this package's MIT license.
13
+
14
+ this package upstream source
15
+ -------------- --------------------------------
16
+ skill-creator skill-creator (Anthropic skills)
17
+
18
+ `session-to-guideline` is original work authored for this project.
19
+
20
+ The MIT License text applies to the adapted skill content and is reproduced here:
21
+
22
+ MIT License
23
+
24
+ Copyright (c) 2025 Anthropic, PBC
25
+
26
+ Permission is hereby granted, free of charge, to any person obtaining a copy
27
+ of this software and associated documentation files (the "Software"), to deal
28
+ in the Software without restriction, including without limitation the rights
29
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30
+ copies of the Software, and to permit persons to whom the Software is
31
+ furnished to do so, subject to the following conditions:
32
+
33
+ The above copyright notice and this permission notice shall be included in all
34
+ copies or substantial portions of the Software.
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # @blackbelt-technology/pi-dashboard-authoring-toolkit
2
+
3
+ General-purpose **authoring** skills for pi sessions. Pure-skill package — a
4
+ `package.json` manifest only, no `extension.ts`. Skills load by natural-language
5
+ trigger from their frontmatter `description`; no manual invocation.
6
+
7
+ ## Skills
8
+
9
+ | Skill | What it does | Fires on |
10
+ |-------|--------------|----------|
11
+ | `skill-creator` | Guide for authoring or updating a skill — structure, frontmatter, scripts/references layout, progressive disclosure. | "create a skill", "write a new skill", "update this skill", "how do I author a skill" |
12
+ | `session-to-guideline` | Turns a pi session JSONL transcript into a reusable "how-we-did-it" Markdown playbook: goal vs. steering, tools/files/searches used, skills/memories created, reproduce-it checklist. | "document this session", "write up how we did X with the AI", "make a guideline/playbook from this session", "turn this session into a tutorial" |
13
+
14
+ `session-to-guideline` ships `scripts/` (deterministic facts-sheet extractor +
15
+ session lister) and `references/guideline-template.md`. Scripts run via
16
+ `npx tsx scripts/…` (repo convention) on Node built-ins — no build step, no
17
+ third-party deps. They read the pi-standard session path
18
+ (`~/.pi/agent/sessions/…`) and never write to the session store.
19
+
20
+ ## How loading works
21
+
22
+ pi auto-discovers each `.pi/skills/<name>/SKILL.md` listed under `pi.skills` in
23
+ `package.json`. No registration code required.
24
+
25
+ ## Attribution
26
+
27
+ `skill-creator` is a derived work of Anthropic's `skill-creator` (MIT). Full
28
+ attribution and license in [`NOTICE`](./NOTICE).
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@blackbelt-technology/pi-dashboard-authoring-toolkit",
3
+ "version": "0.5.4",
4
+ "description": "General-purpose authoring skills for pi sessions — skill-creator (author/update skills) and session-to-guideline (turn a pi session JSONL transcript into a how-we-did-it Markdown playbook). Pure-skill package, no extension.ts. skill-creator adapted from Anthropic's skill-creator (MIT).",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
13
+ "directory": "packages/authoring-toolkit"
14
+ },
15
+ "pi": {
16
+ "skills": [
17
+ ".pi/skills/skill-creator",
18
+ ".pi/skills/session-to-guideline"
19
+ ]
20
+ },
21
+ "files": [
22
+ ".pi/skills/",
23
+ "README.md",
24
+ "NOTICE"
25
+ ],
26
+ "keywords": [
27
+ "pi-package",
28
+ "pi-skill",
29
+ "pi-dashboard",
30
+ "authoring",
31
+ "skills",
32
+ "session"
33
+ ]
34
+ }