@blackbelt-technology/pi-dashboard-authoring-toolkit 0.6.1 → 0.8.0

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.
@@ -1,13 +1,6 @@
1
1
  ---
2
2
  name: faq-mine
3
- description: >-
4
- Mine docs/faq.md from README.md, docs/*.md, AND the pi-hermes memory stores
5
- (project MEMORY.md + global failures.md). Dispatches @fast subagents per source
6
- to extract recurring how-to / what-is questions and runtime-problem fixes,
7
- dedupes against existing FAQ, and merges entries in caveman style. Use when the
8
- user asks to "build / regenerate / extend the FAQ", "mine docs into FAQ", "mine
9
- hermes memory into FAQ", "surface runtime problems in the FAQ", "create FAQ from
10
- README + docs", or "process knowledge into faq.md".
3
+ description: 'Mine docs/faq.md from README.md, docs/*.md, and the pi-hermes memory stores. Dispatches @fast subagents per source, dedupes against the existing FAQ, and merges entries in caveman style. Use when asked to "build / regenerate / extend the FAQ", "mine docs into FAQ", "mine hermes memory into FAQ", "surface runtime problems in the FAQ", or "create FAQ from README + docs".'
11
4
  license: MIT
12
5
  compatibility: Requires @fast subagents (general-purpose) + write access to docs/ + read access to ~/.pi/agent hermes stores.
13
6
  metadata:
@@ -1,15 +1,6 @@
1
1
  ---
2
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".
3
+ description: 'Turn a pi session into a Markdown "how-we-did-it" collaboration guideline: reads the session''s JSONL transcript and synthesizes a reusable playbook of which prompts worked, what had to be steered, and how to reproduce the result faster. Use when: "document this session", "write up how we did X with the AI", "make a guideline from this session", "turn this session into a playbook/tutorial".'
13
4
  ---
14
5
 
15
6
  # Session → Collaboration Guideline
@@ -35,13 +26,22 @@ Two layers:
35
26
  `~/.pi/agent/sessions/--<cwd-with-slashes-as-dashes>--/<timestamp>_<uuid>.jsonl`
36
27
  (JSONL tree; see the pi `session-format` docs). The scripts locate files for you.
37
28
 
29
+ **Worktrees are included by default.** A project's OpenSpec work runs in `.worktrees/<name>`
30
+ sub-checkouts, which get their own encoded session dir (`--<project>-.worktrees-<name>--`).
31
+ Both scripts resolve a `--cwd` to the project root + every `.worktrees/*` worktree, so
32
+ project-scoped listing/`latest` covers worktree sessions too (rows tagged `[wt:<name>]`).
33
+ Pass `--no-worktrees` for the old root-only behavior. Running from *inside* a worktree still
34
+ lists the whole project (the root is recovered by stripping `/.worktrees/<name>`).
35
+
38
36
  ## Procedure
39
37
 
40
38
  1. **Pick the session.** If the user didn't name one, list candidates:
41
39
  ```bash
42
- npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --limit 20 # this project
40
+ npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --limit 20 # this project + its worktrees
41
+ npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --no-worktrees # project root only
43
42
  npx tsx scripts/list_sessions.ts --all --limit 30 # every project
44
43
  ```
44
+ Worktree rows are tagged `[wt:<name>]` so you can tell root work from worktree work.
45
45
  (`tsx` runs the `.ts` directly, no build step.)
46
46
  Show the table and confirm which one (by 8-char id or # index). The *current* live
47
47
  session is usually #0/`latest`; documenting a finished prior session gives a complete
@@ -75,14 +75,66 @@ Two layers:
75
75
  - Rewrite weak prompts into the stronger version the reader should use.
76
76
  - Quote sparingly; summarize tool activity into phases.
77
77
 
78
- 5. **Write the deliverable.** Default location, unless the user says otherwise:
78
+ 5. **Write the deliverable** into the **weekly** folder. The bucket is the
79
+ `ISO week bucket` line from the facts sheet Metadata (`YYYY/Www`, ISO-8601 week of the
80
+ session start). Default location, unless the user says otherwise:
81
+ ```
82
+ <cwd>/Prompt stories/<YYYY>/W<WW>/<Topic>.md # e.g. Prompt stories/2026/W30/Hermes memory pressure.md
83
+ ```
84
+ `mkdir -p` the week folder first. (Do NOT write it inside a skill folder.) Name the file
85
+ after the session name/topic. **Begin the file with the YAML frontmatter block** (see
86
+ `references/guideline-template.md`), filled from the facts sheet:
87
+ ```yaml
88
+ ---
89
+ session: <8-char id>
90
+ week: <YYYY/Www>
91
+ type: <development|planning|research|documentation|other> # copy "Session type" verbatim
92
+ model: "@fast" # ALWAYS quote — an @-prefixed role is INVALID YAML unquoted
93
+ premium: <true|false> # copy the "Premium candidate" flag verbatim
94
+ premium_reason: "<reasons from the flag, or empty>"
95
+ upgrade_status: <pending|done|n/a>
96
+ # --- the next two ONLY when the facts sheet has an "OpenSpec changes" line ---
97
+ openspec_changes: [<change-name>, ...]
98
+ proposal_excerpt: "<the facts sheet 'Proposal excerpt' line, or omit if none>"
99
+ ---
79
100
  ```
80
- <cwd>/Prompt stories/<Topic>.md
101
+ - **`model`** MUST be quoted (`"@fast"`, `"@research"`): a YAML plain scalar cannot start
102
+ with `@` (reserved indicator) — unquoted `model: @fast` makes the whole frontmatter
103
+ invalid. It is the model that generated THIS story. A subagent **cannot observe its own
104
+ runtime model**, so when spawning `SessionGuideline` the parent MUST state it in the
105
+ prompt (e.g. `generated-by: @fast`) and the subagent writes that verbatim. Getting this
106
+ wrong mis-routes the upgrade queue (a budget story stamped `@research` never gets
107
+ re-run). Inline (non-subagent) runs: use the model you are actually running as.
108
+ - **`type`** is classified deterministically by the extractor (`Session type` line:
109
+ code files → development, proposal/design/spec files → planning, research docs / many
110
+ searches + no code → research, docs → documentation, else other). Copy it; only override
111
+ if the narrative *clearly* contradicts the signal.
112
+ - **`openspec_changes` / `proposal_excerpt`** appear **only when a proposal is attached**
113
+ to the session (the extractor found `openspec/changes/<name>/` in the session's
114
+ files/commands and prints an `OpenSpec changes` line). Omit both fields entirely when
115
+ that line is absent — do not invent a proposal link.
116
+ When the write-up references images (storyboards, screenshots), link them relative to the
117
+ story file — from a week folder that is `../../Projektek/<Project>/.../shot_01.png` — and
118
+ verify each resolves. Tell the user the path.
119
+
120
+ 6. **Mark premium stories for later Opus upgrade.** Premium is decided **deterministically**
121
+ by the extractor — the facts sheet's `Premium candidate` flag is `yes` when the session
122
+ created a skill/memory, OR had ≥5 user prompts, OR produced a facts sheet ≥ ~10K tokens.
123
+ You do NOT judge it; you transcribe it. Set `upgrade_status`:
124
+ - `pending` — `premium: true` AND a **budget** model wrote this story (`@fast`/`@compact`);
125
+ it is a candidate for an Opus re-run.
126
+ - `done` — `@research`/Opus wrote it (already premium quality).
127
+ - `n/a` — `premium: false`.
128
+
129
+ When `upgrade_status: pending`, append one row to the queue index
130
+ `<cwd>/Prompt stories/_premium-queue.md` (create with the header if missing):
81
131
  ```
82
- (Do NOT write it inside a skill folder.) Name the file after the session name/topic.
83
- When the write-up references images (storyboards, screenshots), link them with paths
84
- relative to `Prompt stories/` (e.g. `../Projektek/<Project>/.../shot_01.png`) and verify
85
- each resolves. Tell the user the path.
132
+ | week | story | model | reason | status |
133
+ |------|-------|-------|--------|--------|
134
+ | 2026/W30 | 2026/W30/<Topic>.md | @fast | heavy steering (7 prompts) | pending |
135
+ ```
136
+ A later upgrade pass re-runs each `pending` story on `@research`/Opus, overwrites the
137
+ file, and flips both its `upgrade_status` and the queue row to `done`.
86
138
 
87
139
  ## Batch / past-session application (via the `SessionGuideline` subagent)
88
140
 
@@ -101,9 +153,19 @@ context and sessions don't accumulate there:
101
153
  a parent file on forked sessions) + an explicit output path. Each spawn runs BOTH layers
102
154
  in isolation (extract → synthesise) and returns only the written path + a short abstract:
103
155
  ```
104
- Agent(subagent_type="SessionGuideline",
105
- prompt="session JSONL <abs-path>; cwd <dir>; write to Prompt stories/<Topic>.md")
156
+ Agent(subagent_type="SessionGuideline", model="@fast",
157
+ prompt="session JSONL <abs-path>; cwd <dir>; generated-by: @fast; write to the weekly
158
+ folder Prompt stories/<YYYY>/W<WW>/<Topic>.md (bucket from the facts sheet's
159
+ ISO week line); add frontmatter; if premium+budget-model, queue it")
160
+ ```
161
+ **Pass the model twice:** the `Agent(model=…)` param sets the runtime model, and
162
+ `generated-by: <same model>` in the prompt tells the subagent what to write into
163
+ `model:` (it cannot introspect its own model). Keep them identical.
164
+ ```
106
165
  ```
166
+ For **bulk backfill on `@fast`**, each spawn writes into its week folder and self-marks
167
+ premium candidates (`upgrade_status: pending`) into `_premium-queue.md` — a later Opus
168
+ pass drains that queue. See steps 5–6.
107
169
  3. Collect the returned paths. Parallel batches are safe ONLY because step 2 uses a
108
170
  `mktemp` facts sheet per run — the old fixed `/tmp/session_facts.md` raced (concurrent
109
171
  spawns overwrote it, so every playbook got the same sheet). Verify no two outputs share
@@ -121,7 +183,8 @@ override per run.
121
183
 
122
184
  | Goal | Command |
123
185
  |------|---------|
124
- | Latest session in this project | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)"` |
186
+ | Latest session in this project (+ worktrees) | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)"` |
187
+ | Latest, project root only (no worktrees) | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)" --no-worktrees` |
125
188
  | 2nd-most-recent | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)" --index 1` |
126
189
  | A specific session by id | `npx tsx scripts/extract_session.ts 019ea8a9` |
127
190
  | A session in another project | `npx tsx scripts/extract_session.ts latest --cwd /path/to/other` |
@@ -1,3 +1,16 @@
1
+ ---
2
+ session: <8-char id>
3
+ week: <YYYY/Www>
4
+ type: <development|planning|research|documentation|other> # copy facts sheet "Session type"
5
+ model: "@fast" # ALWAYS quote: an @-prefixed role is INVALID YAML unquoted (e.g. "@fast", "@research")
6
+ premium: <true|false> # copy the facts sheet "Premium candidate" flag verbatim
7
+ premium_reason: "<reasons, or empty>"
8
+ upgrade_status: <pending|done|n/a> # pending = budget model + premium -> re-run on Opus
9
+ # openspec_changes / proposal_excerpt: ONLY when the facts sheet has an "OpenSpec changes" line
10
+ openspec_changes: [<change-name>, ...]
11
+ proposal_excerpt: "<facts sheet 'Proposal excerpt', or omit both fields if none>"
12
+ ---
13
+
1
14
  # How we did it: <Task title> — an AI collaboration guideline
2
15
 
3
16
  > A reusable playbook reconstructed from a real pi session. It explains **what was
@@ -27,7 +27,7 @@
27
27
  * --include-thinking reserved (assistant reasoning omitted by default)
28
28
  */
29
29
  import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from "node:fs";
30
- import { join, basename } from "node:path";
30
+ import { join, basename, dirname } from "node:path";
31
31
  import { homedir } from "node:os";
32
32
 
33
33
  const HOME = homedir();
@@ -45,6 +45,7 @@ interface Args {
45
45
  maxCmd: number;
46
46
  maxCmds: number;
47
47
  includeThinking: boolean;
48
+ worktrees: boolean;
48
49
  }
49
50
 
50
51
  function parseArgs(argv: string[]): Args {
@@ -56,6 +57,7 @@ function parseArgs(argv: string[]): Args {
56
57
  maxCmd: 200,
57
58
  maxCmds: 60,
58
59
  includeThinking: false,
60
+ worktrees: true,
59
61
  };
60
62
  const positionals: string[] = [];
61
63
  for (let i = 0; i < argv.length; i++) {
@@ -70,6 +72,8 @@ function parseArgs(argv: string[]): Args {
70
72
  case "--max-cmd": a.maxCmd = parseInt(next(), 10) || a.maxCmd; break;
71
73
  case "--max-cmds": a.maxCmds = parseInt(next(), 10) || a.maxCmds; break;
72
74
  case "--include-thinking": a.includeThinking = true; break;
75
+ case "--worktrees": a.worktrees = true; break;
76
+ case "--no-worktrees": a.worktrees = false; break;
73
77
  default:
74
78
  if (t.startsWith("--")) { /* ignore unknown flag */ }
75
79
  else positionals.push(t);
@@ -98,18 +102,37 @@ function listJsonl(dir: string): string[] {
98
102
  .map((f) => join(dir, f));
99
103
  }
100
104
 
101
- function findSession(selector: string, cwd: string, index: number): string {
105
+ // Session dirs for the project owning `cwd`: the project root + every `.worktrees/*` worktree.
106
+ // If `cwd` is itself a worktree, the root is recovered by stripping `/.worktrees/<name>`.
107
+ function projectSessionDirs(cwd: string, includeWorktrees = true): string[] {
108
+ const root = cwd.replace(/\/+$/, "").replace(/\/\.worktrees\/[^/]+.*$/, "");
109
+ const rootEnc = encodeCwd(root);
110
+ const rootDir = join(SESS_ROOT, rootEnc);
111
+ if (!includeWorktrees) return [rootDir];
112
+ const wtMark = rootEnc.slice(0, -2) + "-.worktrees-"; // strip trailing "--"
113
+ const dirs: string[] = [rootDir];
114
+ if (existsSync(SESS_ROOT)) {
115
+ for (const sub of readdirSync(SESS_ROOT)) {
116
+ if (sub === rootEnc || !sub.startsWith(wtMark)) continue;
117
+ const d = join(SESS_ROOT, sub);
118
+ try { if (statSync(d).isDirectory()) dirs.push(d); } catch { /* skip */ }
119
+ }
120
+ }
121
+ return dirs;
122
+ }
123
+
124
+ function findSession(selector: string, cwd: string, index: number, worktrees = true): string {
102
125
  // 1) explicit existing path
103
126
  if (selector && existsSync(selector) && statSync(selector).isFile()) return selector;
104
127
 
105
- // 2) latest / . -> most recent for cwd
128
+ // 2) latest / . -> most recent across the project (root + worktrees unless --no-worktrees)
106
129
  if (["latest", ".", ""].includes(selector)) {
107
- const d = join(SESS_ROOT, encodeCwd(cwd));
108
- const files = listJsonl(d)
130
+ const dirs = projectSessionDirs(cwd, worktrees);
131
+ const files = dirs.flatMap(listJsonl)
109
132
  .map((f) => ({ f, mt: statSync(f).mtimeMs }))
110
133
  .sort((a, b) => b.mt - a.mt)
111
134
  .map((x) => x.f);
112
- if (!files.length) die(`No sessions found for cwd ${cwd}\n (looked in ${d})`);
135
+ if (!files.length) die(`No sessions found for project of ${cwd}\n (looked in ${dirs.length} dir(s))`);
113
136
  if (index >= files.length) die(`--index ${index} out of range; only ${files.length} sessions for ${cwd}`);
114
137
  return files[index];
115
138
  }
@@ -200,6 +223,113 @@ function trunc(s: string, n: number): string {
200
223
  return s.length <= n ? s : s.slice(0, n).trimEnd() + " …[truncated]";
201
224
  }
202
225
 
226
+ // ISO-8601 week bucket "YYYY/Www" from the session start (facts sheet -> story folder).
227
+ function isoWeekBucket(started: string | null): string {
228
+ if (!started) return "unknown";
229
+ const m = started.match(/^(\d{4})-(\d{2})-(\d{2})/);
230
+ if (!m) return "unknown";
231
+ const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
232
+ const day = (d.getUTCDay() + 6) % 7; // Mon=0
233
+ d.setUTCDate(d.getUTCDate() - day + 3); // nearest Thursday
234
+ const firstThu = new Date(Date.UTC(d.getUTCFullYear(), 0, 4));
235
+ const week = 1 + Math.round(
236
+ ((d.getTime() - firstThu.getTime()) / 864e5 - 3 + ((firstThu.getUTCDay() + 6) % 7)) / 7,
237
+ );
238
+ return `${d.getUTCFullYear()}/W${String(week).padStart(2, "0")}`;
239
+ }
240
+
241
+ // ---------- session type + attached OpenSpec proposals (deterministic) ----------
242
+
243
+ const CODE_RE =
244
+ /\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|c|cc|cpp|h|hpp|rb|php|swift|kt|scala|sh|bash|css|scss|less|html|vue|svelte|sql)$/i;
245
+
246
+ // Change names the session actually touched. files written/edited rank first (worked on),
247
+ // then read/bash/searches/cwd (merely referenced). Empty => no proposal attached.
248
+ function detectOpenspecChanges(d: FactData): string[] {
249
+ const re = /openspec\/changes\/(?:archive\/)?([A-Za-z0-9][A-Za-z0-9._-]+?)\//g;
250
+ const primary = new Set<string>();
251
+ const related = new Set<string>();
252
+ // archived changes live under archive/<YYYY-MM-DD-name>/ — normalize to the bare change name
253
+ // so the active and archived paths of the same change dedupe to one entry.
254
+ const norm = (n: string): string => n.replace(/^\d{4}-\d{2}-\d{2}-/, "");
255
+ const scan = (s: string, set: Set<string>): void => {
256
+ if (!s) return;
257
+ re.lastIndex = 0;
258
+ let m: RegExpExecArray | null;
259
+ while ((m = re.exec(s))) if (m[1] !== "archive") set.add(norm(m[1]));
260
+ };
261
+ for (const p of [...d.files_written, ...d.files_edited]) scan(p, primary);
262
+ for (const p of d.files_read) scan(p, related);
263
+ for (const b of d.bash) scan(b.cmd, related);
264
+ for (const s of d.searches) scan(typeof s.q === "string" ? s.q : JSON.stringify(s.q), related);
265
+ scan(d.cwd ?? "", related);
266
+ const out: string[] = [...primary];
267
+ for (const n of related) if (!primary.has(n)) out.push(n);
268
+ return out.slice(0, 6);
269
+ }
270
+
271
+ function findProposal(cwd: string | null, name: string): string | null {
272
+ const bases: string[] = [];
273
+ let c = cwd || process.cwd();
274
+ for (let i = 0; i < 6 && c; i++) { bases.push(c); const p = dirname(c); if (p === c) break; c = p; }
275
+ bases.push(process.cwd());
276
+ for (const b of bases) {
277
+ const direct = join(b, "openspec", "changes", name, "proposal.md");
278
+ if (existsSync(direct)) return direct;
279
+ const arch = join(b, "openspec", "changes", "archive");
280
+ try {
281
+ if (existsSync(arch)) {
282
+ for (const dir of readdirSync(arch)) {
283
+ if (dir.includes(name)) {
284
+ const p = join(arch, dir, "proposal.md");
285
+ if (existsSync(p)) return p;
286
+ }
287
+ }
288
+ }
289
+ } catch { /* unreadable archive dir */ }
290
+ }
291
+ return null;
292
+ }
293
+
294
+ // First real paragraph of the proposal's `## Why` (fallback: whole doc), one line, <=220 chars.
295
+ function proposalExcerpt(file: string): string | null {
296
+ let t: string;
297
+ try { t = readFileSync(file, "utf8"); } catch { return null; }
298
+ const why = t.match(/\n##\s+Why\s*\n([\s\S]*?)(?=\n##\s|$)/i);
299
+ const body = why ? why[1] : t;
300
+ const para = body.split(/\n\s*\n/).map((s) => s.trim())
301
+ .find((s) => s && !s.startsWith(">") && !s.startsWith("#"));
302
+ if (!para) return null;
303
+ let ex = para.replace(/\s+/g, " ").trim();
304
+ if (ex.length > 220) ex = ex.slice(0, 217).trimEnd() + "…";
305
+ return ex;
306
+ }
307
+
308
+ function classifySessionType(d: FactData, osc: string[]): { type: string; reasons: string } {
309
+ const wr = [...d.files_written, ...d.files_edited];
310
+ const code = wr.filter((p) => CODE_RE.test(p)).length;
311
+ const planning = wr.filter((p) =>
312
+ /(proposal|design)\.md$/i.test(p) || /openspec\/changes\/[^/]+\/specs?\//i.test(p)).length;
313
+ const researchDocs = wr.filter((p) => /docs\/research\//i.test(p)).length;
314
+ const docs = wr.filter((p) => /\.mdx?$/i.test(p) && !/openspec\//i.test(p)).length;
315
+ const searches = d.searches.length;
316
+ const tests = d.bash.filter((b) =>
317
+ /\b(npm|pnpm|yarn)\s+(run\s+)?test|vitest|pytest|jest|go test|cargo test\b/i.test(b.cmd)).length;
318
+ const reasons: string[] = [];
319
+ let type: string;
320
+ if (planning > 0 && code <= 2) { type = "planning"; reasons.push(`${planning} spec/proposal file(s)`); }
321
+ else if (researchDocs > 0 || (searches >= 3 && code === 0)) {
322
+ type = "research";
323
+ reasons.push(researchDocs ? `${researchDocs} research doc(s)` : `${searches} searches, no code`);
324
+ } else if (code > 0) {
325
+ type = "development";
326
+ reasons.push(`${code} code file(s)${tests ? ", tests run" : ""}`);
327
+ } else if (docs > 0) { type = "documentation"; reasons.push(`${docs} doc file(s)`); }
328
+ else { type = "other"; reasons.push("no dominant signal"); }
329
+ if (osc.length && type !== "planning") reasons.push(`openspec: ${osc[0]}`);
330
+ return { type, reasons: reasons.join("; ") };
331
+ }
332
+
203
333
  // ---------- extraction ----------
204
334
 
205
335
  interface FactData {
@@ -362,6 +492,17 @@ function renderMd(d: FactData, args: Args): string {
362
492
  if (d.session_name) L.push(`- **Name:** ${d.session_name}`);
363
493
  L.push(`- **Working dir:** \`${d.cwd}\``);
364
494
  L.push(`- **Started / ended:** ${d.started} → ${d.ended} (${d.duration})`);
495
+ L.push(`- **ISO week bucket:** ${isoWeekBucket(d.started)}`);
496
+ const osc = detectOpenspecChanges(d);
497
+ const cls = classifySessionType(d, osc);
498
+ L.push(`- **Session type:** ${cls.type}${cls.reasons ? ` — ${cls.reasons}` : ""}`);
499
+ if (osc.length) {
500
+ L.push(`- **OpenSpec changes:** ${osc.join(", ")}`);
501
+ const pf = findProposal(d.cwd, osc[0]);
502
+ const ex = pf ? proposalExcerpt(pf) : null;
503
+ if (ex) L.push(`- **Proposal excerpt:** ${ex}`);
504
+ }
505
+ L.push("@@PREMIUM@@");
365
506
  if (d.models.length) L.push(`- **Model(s):** ${d.models.join(", ")}`);
366
507
  if (d.thinking_levels.length) L.push(`- **Thinking level(s):** ${d.thinking_levels.join(", ")}`);
367
508
  const c = d.counts;
@@ -456,14 +597,26 @@ function renderMd(d: FactData, args: Args): string {
456
597
  if (txt) L.push(`**[${n.time}]** ${txt}\n`);
457
598
  }
458
599
  }
459
- return L.join("\n");
600
+
601
+ // Deterministic premium-candidate flag — copied verbatim into the story frontmatter,
602
+ // so premium detection does NOT depend on a weak model's judgment.
603
+ const sheet = L.join("\n");
604
+ const reasons: string[] = [];
605
+ if (d.skills.length || d.memories.length)
606
+ reasons.push(`created ${d.skills.length} skill(s) / ${d.memories.length} memory(ies)`);
607
+ if (d.counts.user >= 5) reasons.push(`heavy steering (${d.counts.user} user prompts)`);
608
+ const sheetTok = Math.round(sheet.length / 4);
609
+ if (sheetTok >= 10000) reasons.push(`large facts sheet (~${sheetTok} tok)`);
610
+ const premiumLine = `- **Premium candidate:** ${reasons.length ? "yes" : "no"}` +
611
+ (reasons.length ? ` — ${reasons.join("; ")}` : "");
612
+ return sheet.replace("@@PREMIUM@@", premiumLine);
460
613
  }
461
614
 
462
615
  // ---------- main ----------
463
616
 
464
617
  function main(): void {
465
618
  const args = parseArgs(process.argv.slice(2));
466
- const path = findSession(args.selector, args.cwd, args.index);
619
+ const path = findSession(args.selector, args.cwd, args.index, args.worktrees);
467
620
  const { header, entries } = loadEntries(path);
468
621
  const chain = activePath(entries);
469
622
  const data = extract(header, chain);
@@ -9,21 +9,23 @@
9
9
  * newest first, with id, time, name, message count, and the first user prompt.
10
10
  */
11
11
  import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
12
- import { join, basename } from "node:path";
12
+ import { join, basename, dirname } from "node:path";
13
13
  import { homedir } from "node:os";
14
14
 
15
15
  const HOME = homedir();
16
16
  const SESS_ROOT = join(HOME, ".pi", "agent", "sessions");
17
17
 
18
- interface Args { cwd: string; limit: number; all: boolean; }
18
+ interface Args { cwd: string; limit: number; all: boolean; worktrees: boolean; }
19
19
 
20
20
  function parseArgs(argv: string[]): Args {
21
- const a: Args = { cwd: process.cwd(), limit: 20, all: false };
21
+ const a: Args = { cwd: process.cwd(), limit: 20, all: false, worktrees: true };
22
22
  for (let i = 0; i < argv.length; i++) {
23
23
  const t = argv[i];
24
24
  if (t === "--cwd") a.cwd = argv[++i];
25
25
  else if (t === "--limit") a.limit = parseInt(argv[++i], 10) || a.limit;
26
26
  else if (t === "--all") a.all = true;
27
+ else if (t === "--no-worktrees") a.worktrees = false;
28
+ else if (t === "--worktrees") a.worktrees = true;
27
29
  }
28
30
  return a;
29
31
  }
@@ -31,6 +33,24 @@ function parseArgs(argv: string[]): Args {
31
33
  const encodeCwd = (cwd: string): string =>
32
34
  "-" + cwd.replace(/\/+$/, "").replace(/\//g, "-") + "--";
33
35
 
36
+ // Project root + every `.worktrees/*` worktree session dir (root recovered if cwd is a worktree).
37
+ function projectSessionDirs(cwd: string, includeWorktrees: boolean): string[] {
38
+ const root = cwd.replace(/\/+$/, "").replace(/\/\.worktrees\/[^/]+.*$/, "");
39
+ const rootEnc = encodeCwd(root);
40
+ const rootDir = join(SESS_ROOT, rootEnc);
41
+ if (!includeWorktrees) return [rootDir];
42
+ const wtMark = rootEnc.slice(0, -2) + "-.worktrees-";
43
+ const dirs: string[] = [rootDir];
44
+ if (existsSync(SESS_ROOT)) {
45
+ for (const sub of readdirSync(SESS_ROOT)) {
46
+ if (sub === rootEnc || !sub.startsWith(wtMark)) continue;
47
+ const d = join(SESS_ROOT, sub);
48
+ try { if (statSync(d).isDirectory()) dirs.push(d); } catch { /* skip */ }
49
+ }
50
+ }
51
+ return dirs;
52
+ }
53
+
34
54
  function listJsonl(dir: string): string[] {
35
55
  if (!existsSync(dir)) return [];
36
56
  return readdirSync(dir).filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
@@ -84,7 +104,7 @@ function main(): void {
84
104
  }
85
105
  }
86
106
  } else {
87
- files = listJsonl(join(SESS_ROOT, encodeCwd(args.cwd)));
107
+ files = projectSessionDirs(args.cwd, args.worktrees).flatMap(listJsonl);
88
108
  }
89
109
 
90
110
  files = files
@@ -105,7 +125,9 @@ function main(): void {
105
125
  const sid = basename(f).split("_").slice(1).join("_").replace(".jsonl", "");
106
126
  const { name, prompt, msgs } = firstPromptAndName(f);
107
127
  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}`);
128
+ const wt = basename(dirname(f)).match(/-\.worktrees-(.+?)--$/);
129
+ const tag = wt ? `[wt:${wt[1]}] ` : "";
130
+ console.log(`${String(i).padStart(2)} ${when.padEnd(19)} ${String(msgs).padStart(4)} ${sid.slice(0, 8)} ${tag}${label}`);
109
131
  });
110
132
  console.log("\nPick with: npx tsx scripts/extract_session.ts <id-or-'latest'> --cwd <dir>");
111
133
  console.log(" (use 'latest --index N' to pick the Nth-most-recent by the # column)");
@@ -0,0 +1,35 @@
1
+ # SKILL.md — index
2
+
3
+ Pull-only condensed map. Source: packages/authoring-toolkit/.pi/skills/skill-creator/SKILL.md. Trigger → principle → anatomy → creation step.
4
+
5
+ ## Meta
6
+ - Skill name — `skill-creator`. Guide for creating effective skills (new or update existing) that extend Claude's capabilities.
7
+ - Trigger — user wants to create a skill / extend capabilities with specialized knowledge, workflows, tool integrations.
8
+
9
+ ## About Skills
10
+ - Skills — modular self-contained packages; "onboarding guides" for domains. Provide: specialized workflows, tool integrations, domain expertise, bundled resources.
11
+
12
+ ## Core Principles
13
+ - Concise is key — context window is public good; Claude already smart; add only missing context; concise examples > verbose explanations.
14
+ - Degrees of freedom — high (text instructions, heuristics) for non-fragile tasks; medium (pseudocode/scripts w/ params); low (specific scripts) for fragile/error-prone ops needing exact sequence.
15
+
16
+ ## Anatomy of a Skill
17
+ - Layout — `skill-name/SKILL.md` (required: frontmatter `name`+`description` + markdown body) + optional `scripts/`, `references/`, `assets/`.
18
+ - scripts/ — executable code, deterministic, repeatedly rewritten. Token-efficient, run without loading into context. Example `scripts/rotate_pdf.py`.
19
+ - references/ — docs loaded into context as needed; schemas/API docs/policies. >10k words → include grep patterns in SKILL.md. Avoid duplication: info lives in SKILL.md OR references, prefer references for detail.
20
+ - assets/ — output files (templates, icons, fonts, boilerplate); not loaded into context.
21
+ - Do NOT include — README.md, INSTALLATION_GUIDE.md, QUICK_REFERENCE.md, CHANGELOG.md, etc. Clutter.
22
+
23
+ ## Progressive Disclosure
24
+ - 3 levels — metadata (always, ~100 words) → SKILL.md body (on trigger, <5k words) → bundled resources (as needed, unlimited). Keep body <500 lines.
25
+ - Patterns — 1 high-level guide w/ reference links (load refs only when needed); 2 domain organization (per-domain files, e.g. bigquery-skill/reference/finance.md); 3 conditional details (link advanced content).
26
+ - Guidelines — references one level deep from SKILL.md; refs >100 lines → table of contents.
27
+
28
+ ## Skill Creation Process
29
+ - Steps in order, skip only with clear reason — understand → plan → init → edit → package → iterate.
30
+ - Step 1 understand — concrete examples; ask functionality/use-cases/trigger phrases; avoid many questions at once.
31
+ - Step 2 plan — analyze each example → list reusable scripts/references/assets.
32
+ - Step 3 init — `scripts/init_skill.py <skill-name> --path <output-directory>`; creates template SKILL.md + scripts/references/assets w/ examples.
33
+ - Step 4 edit — write for another Claude instance; include beneficial non-obvious info. Consult references/workflows.md (multi-step) + references/output-patterns.md (output formats). Test scripts by running; delete unneeded examples. Imperative form. Frontmatter: only `name` + `description`; description = primary trigger, include what + all when-to-use (NOT in body). Quote description if contains `colon-space` (`Triggers: "..."`) — unquoted parses nested YAML, loader silently drops skill. Enforced: scripts/__tests__/skill-frontmatter.test.mjs.
34
+ - Step 5 package — `scripts/package_skill.py <path/to/skill-folder>` (optional output dir, e.g. ./dist). Validates: frontmatter, naming, directory structure, description quality, file organization. Creates `<name>.skill` (zip). Validation fails → errors, no package.
35
+ - Step 6 iterate — use on real tasks → notice struggles → update SKILL.md/resources → test again.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: skill-to-subagent
3
- description: "Turn an existing pi skill into an isolated subagent and wire it into a project's implementation pipeline. Use on triggers like \"wrap this skill as a subagent\", \"turn X into a subagent\", \"create a subagent from a skill\", \"should this be a subagent or a skill\", \"subagentize this\", \"isolate this into its own context\", \"add a subagent to the pipeline\". Tech-stack independent (works for any target project) but pi-platform-specific: relies on pi's .pi/agents/*.md, the Agent tool, role aliases, and inherit_context. Decides fitness first (coherence-critical work stays an inline skill), then writes the bridge agent, routes the model by function, tunes context inheritance, and wires a spawn checkpoint. Not a skill-authoring workflow (that's skill-creator) and not a feature-build workflow."
3
+ description: 'Turn an existing pi skill into an isolated subagent and wire it into a project''s implementation pipeline. Decides fitness first, writes the bridge agent, routes the model, tunes context inheritance, and wires a spawn checkpoint. Use on "wrap this skill as a subagent", "turn X into a subagent", "should this be a subagent or a skill", "subagentize this", "add a subagent to the pipeline".'
4
4
  related_skills: skill-creator
5
5
  ---
6
6
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-authoring-toolkit",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "General-purpose authoring skills for pi sessions — skill-creator (author/update skills), skill-to-subagent (wrap a skill as a subagent), session-to-guideline (turn a pi session JSONL transcript into a how-we-did-it Markdown playbook), and faq-mine (mine docs + memory stores into a FAQ). Pure-skill package, no extension.ts. skill-creator adapted from Anthropic's skill-creator (MIT).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,7 +23,9 @@
23
23
  "files": [
24
24
  ".pi/skills/",
25
25
  "README.md",
26
- "NOTICE"
26
+ "NOTICE",
27
+ "!**/AGENTS.md",
28
+ "!**/*.AGENTS.md"
27
29
  ],
28
30
  "keywords": [
29
31
  "pi-package",
@@ -1,3 +0,0 @@
1
- # faq-mine/SKILL.md — index
2
-
3
- Skill (v2.0): mine `docs/faq.md` from TWO source classes — docs (README.md + evergreen `docs/*.md`) AND pi-hermes memory stores (project `~/.pi/agent/projects-memory/<proj>/MEMORY.md` + global `~/.pi/agent/pi-hermes-memory/failures.md`, `MEMORY.md`). Memory source surfaces runtime problems (tool-quirks/failures/insights) that never reach docs. Inputs `--memory <off|project|failures|all>` (default `failures`), `--docs <list|skip>` (`skip` = memory-only). Passing both `--docs` + `--memory` skips Phase 1 prompt (headless `--docs skip --memory failures` = the ship-change step-10.5 harvest). Phase 0 dedupe existing `## ` headings + enumerate stores; Phase 1 `ask_user` multiselect (docs + stores); Phase 2A doc-mining subagents, Phase 2B memory-mining subagents (symptom-first Q&A, global stores get repo-relevance filter), each writes own `docs/.faq-draft-*.md`; Phase 3 cross-draft + cross-store + doc-vs-memory dedupe; Phase 4 `cat >> faq.md` + rm drafts + refresh condensed `docs/faq.agent.md` via subagent. Caveman style, `Cross-refs:` blocks (memory entries cross-ref store path). READ-ONLY on `~/.pi/agent/**`. Never rename existing faq.md headings (install-hints.test.ts asserts `docsAnchor`→heading). Excludes `AGENTS.md`, `docs/faq.agent.md`, `session-knowledge-*.md`, `spec-gap-analysis.md`.