@blackbelt-technology/pi-dashboard-authoring-toolkit 0.6.1 → 0.7.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.
@@ -35,13 +35,22 @@ Two layers:
35
35
  `~/.pi/agent/sessions/--<cwd-with-slashes-as-dashes>--/<timestamp>_<uuid>.jsonl`
36
36
  (JSONL tree; see the pi `session-format` docs). The scripts locate files for you.
37
37
 
38
+ **Worktrees are included by default.** A project's OpenSpec work runs in `.worktrees/<name>`
39
+ sub-checkouts, which get their own encoded session dir (`--<project>-.worktrees-<name>--`).
40
+ Both scripts resolve a `--cwd` to the project root + every `.worktrees/*` worktree, so
41
+ project-scoped listing/`latest` covers worktree sessions too (rows tagged `[wt:<name>]`).
42
+ Pass `--no-worktrees` for the old root-only behavior. Running from *inside* a worktree still
43
+ lists the whole project (the root is recovered by stripping `/.worktrees/<name>`).
44
+
38
45
  ## Procedure
39
46
 
40
47
  1. **Pick the session.** If the user didn't name one, list candidates:
41
48
  ```bash
42
- npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --limit 20 # this project
49
+ npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --limit 20 # this project + its worktrees
50
+ npx tsx scripts/list_sessions.ts --cwd "$(pwd)" --no-worktrees # project root only
43
51
  npx tsx scripts/list_sessions.ts --all --limit 30 # every project
44
52
  ```
53
+ Worktree rows are tagged `[wt:<name>]` so you can tell root work from worktree work.
45
54
  (`tsx` runs the `.ts` directly, no build step.)
46
55
  Show the table and confirm which one (by 8-char id or # index). The *current* live
47
56
  session is usually #0/`latest`; documenting a finished prior session gives a complete
@@ -75,14 +84,66 @@ Two layers:
75
84
  - Rewrite weak prompts into the stronger version the reader should use.
76
85
  - Quote sparingly; summarize tool activity into phases.
77
86
 
78
- 5. **Write the deliverable.** Default location, unless the user says otherwise:
87
+ 5. **Write the deliverable** into the **weekly** folder. The bucket is the
88
+ `ISO week bucket` line from the facts sheet Metadata (`YYYY/Www`, ISO-8601 week of the
89
+ session start). Default location, unless the user says otherwise:
90
+ ```
91
+ <cwd>/Prompt stories/<YYYY>/W<WW>/<Topic>.md # e.g. Prompt stories/2026/W30/Hermes memory pressure.md
92
+ ```
93
+ `mkdir -p` the week folder first. (Do NOT write it inside a skill folder.) Name the file
94
+ after the session name/topic. **Begin the file with the YAML frontmatter block** (see
95
+ `references/guideline-template.md`), filled from the facts sheet:
96
+ ```yaml
97
+ ---
98
+ session: <8-char id>
99
+ week: <YYYY/Www>
100
+ type: <development|planning|research|documentation|other> # copy "Session type" verbatim
101
+ model: "@fast" # ALWAYS quote — an @-prefixed role is INVALID YAML unquoted
102
+ premium: <true|false> # copy the "Premium candidate" flag verbatim
103
+ premium_reason: "<reasons from the flag, or empty>"
104
+ upgrade_status: <pending|done|n/a>
105
+ # --- the next two ONLY when the facts sheet has an "OpenSpec changes" line ---
106
+ openspec_changes: [<change-name>, ...]
107
+ proposal_excerpt: "<the facts sheet 'Proposal excerpt' line, or omit if none>"
108
+ ---
79
109
  ```
80
- <cwd>/Prompt stories/<Topic>.md
110
+ - **`model`** MUST be quoted (`"@fast"`, `"@research"`): a YAML plain scalar cannot start
111
+ with `@` (reserved indicator) — unquoted `model: @fast` makes the whole frontmatter
112
+ invalid. It is the model that generated THIS story. A subagent **cannot observe its own
113
+ runtime model**, so when spawning `SessionGuideline` the parent MUST state it in the
114
+ prompt (e.g. `generated-by: @fast`) and the subagent writes that verbatim. Getting this
115
+ wrong mis-routes the upgrade queue (a budget story stamped `@research` never gets
116
+ re-run). Inline (non-subagent) runs: use the model you are actually running as.
117
+ - **`type`** is classified deterministically by the extractor (`Session type` line:
118
+ code files → development, proposal/design/spec files → planning, research docs / many
119
+ searches + no code → research, docs → documentation, else other). Copy it; only override
120
+ if the narrative *clearly* contradicts the signal.
121
+ - **`openspec_changes` / `proposal_excerpt`** appear **only when a proposal is attached**
122
+ to the session (the extractor found `openspec/changes/<name>/` in the session's
123
+ files/commands and prints an `OpenSpec changes` line). Omit both fields entirely when
124
+ that line is absent — do not invent a proposal link.
125
+ When the write-up references images (storyboards, screenshots), link them relative to the
126
+ story file — from a week folder that is `../../Projektek/<Project>/.../shot_01.png` — and
127
+ verify each resolves. Tell the user the path.
128
+
129
+ 6. **Mark premium stories for later Opus upgrade.** Premium is decided **deterministically**
130
+ by the extractor — the facts sheet's `Premium candidate` flag is `yes` when the session
131
+ created a skill/memory, OR had ≥5 user prompts, OR produced a facts sheet ≥ ~10K tokens.
132
+ You do NOT judge it; you transcribe it. Set `upgrade_status`:
133
+ - `pending` — `premium: true` AND a **budget** model wrote this story (`@fast`/`@compact`);
134
+ it is a candidate for an Opus re-run.
135
+ - `done` — `@research`/Opus wrote it (already premium quality).
136
+ - `n/a` — `premium: false`.
137
+
138
+ When `upgrade_status: pending`, append one row to the queue index
139
+ `<cwd>/Prompt stories/_premium-queue.md` (create with the header if missing):
81
140
  ```
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.
141
+ | week | story | model | reason | status |
142
+ |------|-------|-------|--------|--------|
143
+ | 2026/W30 | 2026/W30/<Topic>.md | @fast | heavy steering (7 prompts) | pending |
144
+ ```
145
+ A later upgrade pass re-runs each `pending` story on `@research`/Opus, overwrites the
146
+ file, and flips both its `upgrade_status` and the queue row to `done`.
86
147
 
87
148
  ## Batch / past-session application (via the `SessionGuideline` subagent)
88
149
 
@@ -101,9 +162,19 @@ context and sessions don't accumulate there:
101
162
  a parent file on forked sessions) + an explicit output path. Each spawn runs BOTH layers
102
163
  in isolation (extract → synthesise) and returns only the written path + a short abstract:
103
164
  ```
104
- Agent(subagent_type="SessionGuideline",
105
- prompt="session JSONL <abs-path>; cwd <dir>; write to Prompt stories/<Topic>.md")
165
+ Agent(subagent_type="SessionGuideline", model="@fast",
166
+ prompt="session JSONL <abs-path>; cwd <dir>; generated-by: @fast; write to the weekly
167
+ folder Prompt stories/<YYYY>/W<WW>/<Topic>.md (bucket from the facts sheet's
168
+ ISO week line); add frontmatter; if premium+budget-model, queue it")
169
+ ```
170
+ **Pass the model twice:** the `Agent(model=…)` param sets the runtime model, and
171
+ `generated-by: <same model>` in the prompt tells the subagent what to write into
172
+ `model:` (it cannot introspect its own model). Keep them identical.
173
+ ```
106
174
  ```
175
+ For **bulk backfill on `@fast`**, each spawn writes into its week folder and self-marks
176
+ premium candidates (`upgrade_status: pending`) into `_premium-queue.md` — a later Opus
177
+ pass drains that queue. See steps 5–6.
107
178
  3. Collect the returned paths. Parallel batches are safe ONLY because step 2 uses a
108
179
  `mktemp` facts sheet per run — the old fixed `/tmp/session_facts.md` raced (concurrent
109
180
  spawns overwrote it, so every playbook got the same sheet). Verify no two outputs share
@@ -121,7 +192,8 @@ override per run.
121
192
 
122
193
  | Goal | Command |
123
194
  |------|---------|
124
- | Latest session in this project | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)"` |
195
+ | Latest session in this project (+ worktrees) | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)"` |
196
+ | Latest, project root only (no worktrees) | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)" --no-worktrees` |
125
197
  | 2nd-most-recent | `npx tsx scripts/extract_session.ts latest --cwd "$(pwd)" --index 1` |
126
198
  | A specific session by id | `npx tsx scripts/extract_session.ts 019ea8a9` |
127
199
  | 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)");
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.7.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",