Skill Tracer
Skills › BMAD Method › bmad-brainstorming › brain.py

brain.py

806 lines · skills/bmad-brainstorming/scripts/brain.py at bd70c64

1#!/usr/bin/env python3
2# /// script
3# requires-python = ">=3.11"
4# ///
5"""Serve the brainstorming technique library without loading it all into context.
6
7The library is a CSV (category, technique_name, description, detail). `description`
8is a short gist — enough to propose and run most techniques. `detail` is optional:
9a path (relative to the CSV's directory, and inside it) to a fuller instruction file for a technique
10complex enough to warrant one. Only `show` resolves detail files, and only for the
11technique asked for — so the heavy material never enters context until it is run.
13Commands:
14 categories list category names + counts (the cheap entry point)
15 list --category C [...] the index (name + gist) for those categories
16 list --all the whole index at once — deliberate; large, avoid interactively
17 show NAME [NAME ...] full gist for each, inlining its detail file if it has one
18 random [--category C] [-n N] pick N at random (optionally within categories)
19 html --out PATH write the offline 'browse all' selection page to a file
21`list` refuses to run with neither --category nor --all, and `html` writes to a file
22rather than stdout: dumping the full catalog into context is a footgun, so reaching the
23whole library at once must always be an explicit, deliberate choice.
25`--extra PATH` merges a JSON overlay of additional techniques (customize.toml's
26`additional_techniques`) into every command. An extra whose technique_name matches
27a shipped row (case-insensitive) REPLACES it — retune a shipped technique; others
28append, so custom techniques and whole new categories are first-class everywhere —
29including the browse page and category draws. (Same overlay semantics as
30bmad-advanced-elicitation's pick_methods.py.)
32Default output is lean text for an LLM to read; pass --json for structured output.
33"""
35import argparse
36import csv
37import hashlib
38import html
39import json
40import random
41import sys
42from pathlib import Path
44DEFAULT_FILE = Path(__file__).resolve().parent.parent / "assets" / "brain-methods.csv"
45FIELDS = ("category", "technique_name", "description", "detail", "provenance", "good_for", "audience")
46# Optional columns beyond the original four — absent in older CSVs and in --extra
47# overlays, so always read through .get/setdefault. `provenance` (classic|signature|
48# playful) drives the "Proven & Professional" lead group; `good_for` (a |-separated
49# list of goal tags) drives the browse page's goal filter; `audience` (solo|group|either)
50# is advisory.
51OPTIONAL_FIELDS = ("detail", "provenance", "good_for", "audience")
52REQUIRED_FIELDS = ("category", "technique_name", "description")
55def load(file: Path) -> list[dict]:
56 # utf-8-sig: tolerate BOM-prefixed catalogs (Excel "CSV UTF-8", Notepad)
57 with open(file, newline="", encoding="utf-8-sig") as f:
58 rows = list(csv.DictReader(f))
59 for r in rows:
60 for k in FIELDS:
61 r.setdefault(k, "")
62 r[k] = (r.get(k) or "").strip()
63 return rows
66def load_extra(file: Path) -> list[dict]:
67 """Merge-in techniques from a JSON overlay — a list of
68 {category, technique_name, description[, detail]} objects. This is how
69 customize.toml's `additional_techniques` become first-class across *every*
70 subcommand (categories/list/random/show/html), so the browse page and
71 category draws include them too, not just the in-chat flows."""
72 data = json.loads(file.read_text(encoding="utf-8-sig"))
73 if not isinstance(data, list):
74 raise ValueError("--extra must be a JSON array of objects")
75 rows = []
76 for n, item in enumerate(data, 1):
77 if not isinstance(item, dict):
78 raise ValueError(f"each --extra entry must be a JSON object, got: {item!r}")
79 row = {k: str(item.get(k) or "").strip() for k in FIELDS}
80 for field in REQUIRED_FIELDS:
81 if not row[field]:
82 raise ValueError(f"--extra entry {n} ({row['technique_name'] or 'unnamed'}) is missing {field}")
83 rows.append(row)
84 return rows
87def merge_extra(rows: list[dict], extras: list[dict]) -> list[dict]:
88 """Extras replace a catalog row with the same technique_name (case-insensitive),
89 otherwise append — the same overlay semantics as pick_methods.py, so
90 customize.toml additional_* entries behave identically across sibling skills."""
91 merged = list(rows)
92 index = {r["technique_name"].lower(): i for i, r in enumerate(merged)}
93 for e in extras:
94 key = e["technique_name"].lower()
95 if key in index:
96 merged[index[key]] = e
97 else:
98 index[key] = len(merged)
99 merged.append(e)
100 return merged
103def categories(rows: list[dict]) -> list[tuple[str, int]]:
104 counts: dict[str, int] = {}
105 for r in rows:
106 counts[r["category"]] = counts.get(r["category"], 0) + 1
107 return sorted(counts.items())
110def filter_cats(rows: list[dict], cats: list[str] | None) -> list[dict]:
111 if not cats:
112 return rows
113 wanted = {c.lower() for c in cats}
114 return [r for r in rows if r["category"].lower() in wanted]
117def find(rows: list[dict], names: list[str]) -> tuple[list[dict], list[str]]:
118 by_name = {r["technique_name"].lower(): r for r in rows}
119 found, missing = [], []
120 for n in names:
121 r = by_name.get(n.strip().lower())
122 (found if r else missing).append(r if r else n)
123 return found, missing
126def resolve_detail(row: dict, csv_dir: Path) -> str | None:
127 """Return the contents of a row's detail file, or None if there is no detail
128 (or the file is missing or outside csv_dir — reported to stderr, not fatal)."""
129 if not row.get("detail"):
130 return None
131 base = csv_dir.resolve()
132 path = (base / row["detail"]).resolve()
133 if not path.is_relative_to(base):
134 print(
135 f"# detail path outside the catalog folder, refused for {row['technique_name']}: {row['detail']}",
136 file=sys.stderr,
137 )
138 return None
139 if not path.is_file():
140 print(f"# detail file not found for {row['technique_name']}: {row['detail']}", file=sys.stderr)
141 return None
142 return path.read_text(encoding="utf-8").strip()
145def fmt_categories(cats: list[tuple[str, int]], as_json: bool) -> str:
146 if as_json:
147 return json.dumps([{"category": c, "count": n} for c, n in cats])
148 return "\n".join(f"{c}\t{n}" for c, n in cats)
151def fmt_list(rows: list[dict], as_json: bool) -> str:
152 if as_json:
153 return json.dumps([{k: r[k] for k in ("category", "technique_name", "description")} for r in rows])
154 return "\n".join(f"{r['category']}\t{r['technique_name']}\t{r['description']}" for r in rows)
157def fmt_show(rows: list[dict], csv_dir: Path, as_json: bool) -> str:
158 if as_json:
159 out = []
160 for r in rows:
161 d = resolve_detail(r, csv_dir)
162 entry = {k: r[k] for k in ("category", "technique_name", "description")}
163 if d:
164 entry["detail"] = d
165 out.append(entry)
166 return json.dumps(out)
167 blocks = []
168 for r in rows:
169 block = f"## {r['technique_name']} [{r['category']}]\n{r['description']}"
170 d = resolve_detail(r, csv_dir)
171 if d:
172 block += f"\n\n{d}"
173 blocks.append(block)
174 return "\n\n".join(blocks)
177def pretty(cat: str) -> str:
178 """Turn a category slug (e.g. 'speculative_future') into a display name."""
179 return cat.replace("_", " ").replace("-", " ").title()
182# --- card visuals: a crafted duotone icon + hue per category, plus a per-technique icon ---
183# The hues and SVG glyphs are *data*, not logic: they live in the icon sidecar
184# (assets/brain-icons.json) so the catalog's visuals can be edited without touching code.
185# It maps category slug -> {hue, glyph} and technique name -> svg (inner markup, drawn in
186# `currentColor` which the CSS sets to the category hue; the shared CHIP frame is added by
187# the renderer). Anything missing falls back here — an unknown category gets a hash-derived
188# hue + generic glyph, an unknown/not-yet-iconed technique a neutral mark — so custom
189# catalogs always render.
191ICON_FILE = DEFAULT_FILE.parent / "brain-icons.json"
193CHIP = '<rect x="1.5" y="1.5" width="41" height="41" rx="12" fill="currentColor" fill-opacity="0.12"/>'
195_FALLBACK_GLYPH = (
196 '<circle cx="22" cy="22" r="11" fill="currentColor" fill-opacity="0.16"/>'
197 '<circle cx="22" cy="22" r="11" stroke="currentColor" stroke-width="1.6" fill="none"/>'
198 '<circle cx="22" cy="22" r="3.4" fill="currentColor"/>'
200_FALLBACK_TECH = (
201 '<rect x="15" y="15" width="14" height="14" rx="2.5" transform="rotate(45 22 22)" '
202 'fill="none" stroke="currentColor" stroke-width="2"/><circle cx="22" cy="22" r="2.4" fill="currentColor"/>'
206def _load_icons(file: Path = ICON_FILE) -> tuple[dict, dict]:
207 """Read the icon sidecar: (category slug -> {hue, glyph}, technique name -> svg).
208 A missing or malformed file is non-fatal — everything then uses the fallbacks below."""
209 try:
210 data = json.loads(file.read_text(encoding="utf-8"))
211 except (OSError, ValueError):
212 return {}, {}
213 return (data.get("categories") or {}), (data.get("techniques") or {})
216_CATEGORY_STYLES, _TECH_ICONS = _load_icons()
219def _hsl_hex(deg: int, s: float, lt: float) -> str:
220 import colorsys
222 r, g, b = colorsys.hls_to_rgb((deg % 360) / 360, lt, s)
223 return f"#{round(r * 255):02x}{round(g * 255):02x}{round(b * 255):02x}"
226def category_style(cat: str) -> tuple[str, str]:
227 """(hue, glyph markup) for a category — from the sidecar for the shipped set, derived for extras."""
228 style = _CATEGORY_STYLES.get(cat)
229 if style and style.get("hue"):
230 return style["hue"], style.get("glyph") or _FALLBACK_GLYPH
231 deg = int(hashlib.md5(cat.encode("utf-8")).hexdigest(), 16) % 360
232 return _hsl_hex(deg, 0.58, 0.52), _FALLBACK_GLYPH
235def tech_icon(name: str) -> str:
236 """The hand-picked line-icon for a specific technique (neutral mark if unknown)."""
237 return _TECH_ICONS.get(name, _FALLBACK_TECH)
240SELECTOR_TEMPLATE = r"""<!DOCTYPE html>
241<html lang="en">
242<head>
243<meta charset="utf-8">
244<meta name="viewport" content="width=device-width, initial-scale=1">
245<title>BMad Method Brainstorming Selection</title>
246<script>
247/* set the theme before first paint so there's no light-mode flash */
248(function(){ try {
249 var t = localStorage.getItem('bmad-theme');
250 if (!t) { t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; }
251 document.documentElement.setAttribute('data-theme', t);
252} catch(e){} })();
253</script>
254<style>
255 :root {
256 --bg:#f6f7fb; --surface:#fff; --ink:#1c1e2b; --muted:#6b7080;
257 --accent:#5b4bdc; --accent-ink:#5b4bdc; --warn:#c0561f;
258 --line:#e6e8f0; --control:#eef0f7; --control2:#f1f2f8; --raised:#fff;
259 --cnt:#b9bdce; --foot:#aeb2c4; --shadow:rgba(20,20,50,.06);
260 }
261 :root[data-theme="dark"] {
262 --bg:#0f1117; --surface:#171a23; --ink:#e7e9f2; --muted:#9aa0b4;
263 --accent:#6d5cf0; --accent-ink:#a99bff; --warn:#e08a4a;
264 --line:#2a2f3e; --control:#222634; --control2:#1d212d; --raised:#2c3242;
265 --cnt:#5a6076; --foot:#5a6076; --shadow:rgba(0,0,0,.45);
266 }
267 /* lift the category hue toward white on dark surfaces so deep hues stay legible */
268 :root[data-theme="dark"] section > h2 { color:color-mix(in srgb, var(--c) 62%, #fff); }
269 :root[data-theme="dark"] .tech .ico { color:color-mix(in srgb, var(--c) 68%, #fff); }
270 :root[data-theme="dark"] label.tech:has(input:checked) { border-color:color-mix(in srgb, var(--c) 60%, #fff); }
271 .titlerow { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
272 .themebtn { flex:none; width:36px; height:36px; border-radius:9px; background:var(--control); color:var(--ink); font-size:17px; line-height:1; display:inline-flex; align-items:center; justify-content:center; }
273 .themebtn:hover { background:var(--raised); }
274 * { box-sizing:border-box; }
275 body { margin:0; font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; background:var(--bg); color:var(--ink); }
276 header { position:sticky; top:0; z-index:5; background:var(--surface); padding:20px 0 12px; border-bottom:1px solid var(--line); box-shadow:0 2px 12px var(--shadow); }
277 .hwrap { max-width:1120px; margin:0 auto; padding:0 24px; } /* align header content with the card column on wide screens */
278 h1 { margin:0 0 4px; font-size:24px; letter-spacing:-.02em; }
279 .sub { margin:0 0 12px; color:var(--muted); font-size:14px; max-width:74ch; }
280 button { font:inherit; border:0; border-radius:8px; cursor:pointer; }
281 .composer { display:flex; flex-direction:column; gap:9px; margin:6px 0 12px; }
282 .grp { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
283 .glabel { font-size:11px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); min-width:74px; }
284 .modes { display:inline-flex; background:var(--control); border-radius:9px; padding:3px; gap:2px; }
285 .mode { padding:7px 13px; font-size:14px; font-weight:600; color:var(--muted); background:transparent; }
286 .mode.on { background:var(--raised); color:var(--accent-ink); box-shadow:0 1px 3px var(--shadow); }
287 .modehint { flex:1 1 240px; min-width:0; font-size:13px; color:var(--muted); font-style:italic; }
288 .pill { font-size:13px; color:var(--muted); background:var(--control); padding:6px 12px; border-radius:20px; }
289 .pill b { color:var(--accent-ink); }
290 .step { display:inline-flex; align-items:center; gap:7px; font-size:13px; color:var(--ink); background:var(--control2); padding:4px 6px 4px 12px; border-radius:20px; }
291 .step b { min-width:12px; text-align:center; font-size:14px; color:var(--ink); }
292 .step button { width:24px; height:24px; border-radius:50%; background:var(--raised); color:var(--muted); font-size:17px; line-height:22px; text-align:center; box-shadow:0 1px 2px var(--shadow); }
293 .step button:hover { color:var(--accent-ink); }
294 .total { font-size:12px; color:var(--muted); }
295 .total.warn { color:var(--warn); font-weight:600; }
296 .bar { display:flex; gap:10px 14px; align-items:center; flex-wrap:wrap; }
297 #copy { margin-left:auto; padding:9px 22px; background:var(--accent); color:#fff; font-size:14px; font-weight:700; }
298 #copy:hover { filter:brightness(1.07); }
299 .chips { flex:1 1 320px; min-width:0; display:flex; gap:7px; flex-wrap:wrap; align-items:center; }
300 .chip { font-size:12px; padding:4px 11px; border-radius:16px; border:0; color:#fff; background:var(--cc); font-weight:600; cursor:pointer; }
301 .chip:hover { filter:brightness(1.08); }
302 .banner { max-height:0; overflow:hidden; transition:max-height .25s ease, padding .22s ease, margin .22s ease; background:linear-gradient(90deg,var(--accent),#8275f2); color:#fff; border-radius:10px; font-weight:700; text-align:center; padding:0 14px; }
303 .banner.show { max-height:64px; padding:13px 14px; margin-top:10px; }
304 .banner.fail { background:linear-gradient(90deg,var(--warn),#e0894a); }
305 main { padding:18px 24px 60px; max-width:1120px; margin:0 auto; }
306 section { margin:0 0 26px; }
307 section > h2 { font-size:13px; text-transform:uppercase; letter-spacing:.08em; color:var(--c); margin:0 0 10px; border-bottom:1px solid color-mix(in srgb, var(--c) 24%, var(--line)); padding-bottom:6px; }
308 section > h2 .cnt { color:color-mix(in srgb, var(--c) 45%, var(--cnt)); margin-left:6px; }
309 .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(360px,1fr)); gap:10px; }
310 label.tech { display:flex; gap:12px; align-items:flex-start; background:color-mix(in srgb, var(--c) 5%, var(--surface)); border:1px solid color-mix(in srgb, var(--c) 18%, var(--line)); border-radius:10px; padding:11px 13px; cursor:pointer; transition:border-color .12s, box-shadow .12s, background .12s; }
311 label.tech:hover { border-color:color-mix(in srgb, var(--c) 45%, var(--surface)); }
312 label.tech input { margin-top:2px; width:17px; height:17px; accent-color:var(--c); flex:none; }
313 label.tech:has(input:checked) { border-color:var(--c); background:color-mix(in srgb, var(--c) 12%, var(--surface)); box-shadow:0 0 0 2px color-mix(in srgb, var(--c) 30%, transparent); }
314 .tech .ic2 { display:flex; gap:5px; flex:none; }
315 .tech .ico { width:40px; height:40px; flex:none; color:var(--c); }
316 .tech .n { font-weight:600; display:block; }
317 .tech .d { color:var(--muted); font-size:13.5px; display:block; margin-top:2px; }
318 .tech .gf { color:var(--accent-ink); font-size:11px; display:block; margin-top:5px; opacity:.85; }
319 .grouphdr { margin:30px 0 12px; font-size:12px; text-transform:uppercase; letter-spacing:.14em; font-weight:700; color:var(--c); opacity:.92; border-bottom:1px solid color-mix(in srgb, var(--c) 22%, var(--line)); padding-bottom:7px; }
320 main > .grouphdr:first-child { margin-top:2px; }
321 :root[data-theme="dark"] .grouphdr { color:color-mix(in srgb, var(--c) 62%, #fff); }
322 .goals { display:flex; gap:7px; flex-wrap:wrap; }
323 .goal { font-size:12px; padding:5px 12px; border-radius:16px; background:var(--control); color:var(--muted); font-weight:600; }
324 .goal:hover { color:var(--ink); }
325 .goal.on { background:var(--accent); color:#fff; }
326 label.tech.invent { border-style:dashed; background:transparent; }
327 label.tech.invent:hover { border-color:var(--c); }
328 label.tech.invent .n { color:var(--c); }
329 label.tech.hidden { display:none; }
330 footer { text-align:center; color:var(--foot); font-size:12px; padding:24px; }
331</style>
332</head>
333<body>
334<header>
335 <div class="hwrap">
336 <div class="titlerow">
337 <h1>BMad Method Brainstorming Selection</h1>
338 <button id="theme" class="themebtn" type="button" aria-label="Toggle dark mode" title="Toggle dark mode"></button>
339 </div>
340 <p class="sub">Compose your session, hit <strong>Copy prompt</strong>, and paste it back into the chat to begin. {{TOTAL}}</p>
342 <div class="composer">
343 <div class="grp">
344 <span class="glabel">Facilitation</span>
345 <div class="modes" id="modes">
346 <button type="button" class="mode on" data-mode="Facilitator">Facilitator</button>
347 <button type="button" class="mode" data-mode="Creative Partner">Creative Partner</button>
348 <button type="button" class="mode" data-mode="Ideate for me">Ideate for me</button>
349 </div>
350 <span class="modehint" id="modehint"></span>
351 </div>
352 <div class="grp">
353 <span class="glabel">Techniques</span>
354 <span class="pill">Picked <b id="pickN">0</b></span>
355 <span class="step">Random <button type="button" data-step="rand" data-d="-1">&minus;</button><b id="randN">0</b><button type="button" data-step="rand" data-d="1">+</button></span>
356 <span class="step">Invent <button type="button" data-step="inv" data-d="-1">&minus;</button><b id="invN">0</b><button type="button" data-step="inv" data-d="1">+</button></span>
357 <span class="step">AI picks <button type="button" data-step="ai" data-d="-1">&minus;</button><b id="aiN">0</b><button type="button" data-step="ai" data-d="1">+</button></span>
358 <span class="total" id="total">Total 0 &middot; 3&ndash;4 is the sweet spot</span>
359 <button id="copy" type="button">Copy prompt</button>
360 </div>
361 </div>
363 {{GOALBAR}}
364 <div class="bar">
365 <span class="glabel">Jump to</span>
366 <div class="chips" id="chips">{{CHIPS}}</div>
367 </div>
369 <div class="banner" id="banner">&#10003; Copied! Now paste it into the chat to start your session.</div>
370 </div>
371</header>
372<main>
373{{BODY}}
374</main>
375<footer>BMad Method &middot; Brainstorming</footer>
376<script>
377(function(){
378 var $ = function(id){ return document.getElementById(id); };
379 var all = Array.prototype.slice;
380 var boxes = all.call(document.querySelectorAll('input[type=checkbox]'));
381 var techBoxes = boxes.filter(function(b){ return b.dataset.name; }); // real technique cards
382 var inventBoxes = boxes.filter(function(b){ return b.dataset.invent; }); // per-category "invent in the spirit of" cards
383 var header = document.querySelector('header');
384 var sections = all.call(document.querySelectorAll('section'));
385 var state = { mode: 'Facilitator', rand: 0, inv: 0, ai: 0 };
386 var MODE_HINTS = {
387 'Facilitator': 'A forcing function for your ideas — I prompt and push, but never supply them.',
388 'Creative Partner': 'We riff together — I facilitate and add ideas too, each logged as yours or mine.',
389 'Ideate for me': 'I run the whole session myself, then show you the result and offer to keep going.'
390 };
391 function setHint(){ $('modehint').textContent = MODE_HINTS[state.mode] || ''; }
393 var themeBtn = $('theme');
394 function setThemeIcon(){ themeBtn.textContent = document.documentElement.getAttribute('data-theme') === 'dark' ? '☀' : '☾'; }
395 themeBtn.addEventListener('click', function(){
396 var next = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
397 document.documentElement.setAttribute('data-theme', next);
398 try { localStorage.setItem('bmad-theme', next); } catch(e){}
399 setThemeIcon();
400 });
402 all.call(document.querySelectorAll('.mode')).forEach(function(b){
403 b.addEventListener('click', function(){
404 all.call(document.querySelectorAll('.mode')).forEach(function(m){ m.classList.remove('on'); });
405 b.classList.add('on');
406 state.mode = b.dataset.mode;
407 setHint();
408 });
409 });
411 all.call(document.querySelectorAll('[data-step]')).forEach(function(btn){
412 btn.addEventListener('click', function(){
413 var k = btn.dataset.step, d = parseInt(btn.dataset.d, 10);
414 state[k] = Math.max(0, state[k] + d);
415 update();
416 });
417 });
419 // Category chips are jump-nav: click one to smooth-scroll its section into view,
420 // offsetting by the sticky header's height so the heading isn't hidden beneath it.
421 all.call(document.querySelectorAll('.chip')).forEach(function(chip){
422 chip.addEventListener('click', function(){
423 var sec = null;
424 for (var i = 0; i < sections.length; i++){ if (sections[i].dataset.cat === chip.dataset.cat){ sec = sections[i]; break; } }
425 if (!sec){ return; }
426 var top = sec.getBoundingClientRect().top + window.pageYOffset - header.offsetHeight - 8;
427 window.scrollTo({ top: top, behavior: 'smooth' });
428 });
429 });
431 boxes.forEach(function(b){ b.addEventListener('change', update); });
433 // A `classic` technique appears twice (lead "Proven & Professional" group + its home
434 // category), so de-dupe checked picks by name; the lead copy carries data-lead.
435 function checkedTech(){
436 var seen = {}, out = [];
437 techBoxes.forEach(function(b){
438 if (!b.checked || seen[b.dataset.name]) { return; }
439 seen[b.dataset.name] = 1;
440 out.push(b);
441 });
442 return out;
443 }
444 function checkedInvent(){ return inventBoxes.filter(function(b){ return b.checked; }); }
446 function update(){
447 // rand can't exceed what the pool can supply — keep the counter honest with the draw
448 if (state.rand > randomPool().length){ state.rand = randomPool().length; }
449 $('pickN').textContent = checkedTech().length;
450 $('randN').textContent = state.rand;
451 $('invN').textContent = state.inv;
452 $('aiN').textContent = state.ai;
453 var total = checkedTech().length + state.rand + state.inv + checkedInvent().length + state.ai;
454 var t = $('total');
455 t.textContent = 'Total ' + total + ' · 3–4 is the sweet spot';
456 t.classList.toggle('warn', total > 5);
457 }
459 // "Great for" goal filter: clicking a goal narrows visible cards to those tagged with it.
460 var goalBtns = all.call(document.querySelectorAll('.goal'));
461 function activeGoals(){ return goalBtns.filter(function(b){ return b.classList.contains('on'); }).map(function(b){ return b.dataset.goal; }); }
462 function applyFilter(){
463 var act = activeGoals();
464 all.call(document.querySelectorAll('label.tech')).forEach(function(lab){
465 var inp = lab.querySelector('input');
466 if (inp.dataset.invent){ return; } // invent cards aren't goal-tagged — always visible
467 var good = (inp.dataset.good || '').split('|');
468 var show = !act.length || act.some(function(g){ return good.indexOf(g) >= 0; });
469 lab.classList.toggle('hidden', !show);
470 });
471 }
472 goalBtns.forEach(function(b){ b.addEventListener('click', function(){ b.classList.toggle('on'); applyFilter(); }); });
474 function randomPool(){
475 var picked = {};
476 checkedTech().forEach(function(b){ picked[b.dataset.name] = 1; });
477 // draw from unchecked, non-lead copies, skipping anything already picked
478 return techBoxes.filter(function(b){ return !b.checked && !b.dataset.lead && !picked[b.dataset.name]; });
479 }
481 function sample(arr, n){
482 var a = arr.slice(), out = [];
483 while (out.length < n && a.length){ out.push(a.splice(Math.floor(Math.random() * a.length), 1)[0]); }
484 return out;
485 }
487 function compose(){
488 var picks = checkedTech().map(function(b){ return { n: b.dataset.name, c: b.dataset.cat, d: b.dataset.desc, r: false }; });
489 var rnd = sample(randomPool(), state.rand).map(function(b){ return { n: b.dataset.name, c: b.dataset.cat, d: b.dataset.desc, r: true }; });
490 var techs = picks.concat(rnd);
491 var L = ["Let's run my brainstorming session.", "", 'Facilitation mode: ' + state.mode + '.'];
492 if (techs.length){
493 L.push("", 'Techniques to use:');
494 techs.forEach(function(t, i){
495 L.push((i + 1) + '.' + (t.r ? ' (random pick)' : '') + ' ' + t.n + ' · ' + t.c);
496 L.push(' ' + t.d);
497 });
498 }
499 var extra = [];
500 if (state.inv > 0){ extra.push('invent ' + state.inv + ' brand-new technique' + (state.inv > 1 ? 's' : '') + ' on the fly'); }
501 checkedInvent().forEach(function(b){ extra.push('invent 1 new technique in the spirit of ' + b.dataset.invent); });
502 if (state.ai > 0){ extra.push('you choose ' + state.ai + ' more technique' + (state.ai > 1 ? 's' : '') + ' that fit my goal'); }
503 if (extra.length){ L.push("", 'Then: ' + extra.join('; and ') + '.'); }
504 if (!techs.length && !extra.length){
505 L.push("", state.mode === 'Ideate for me'
506 ? 'Run the whole session yourself — pick the techniques, generate the ideas, then show me the result.'
507 : 'Help me choose 3–4 techniques to start.');
508 }
509 return L.join('\n');
510 }
512 function fallbackCopy(t){
513 var ta = document.createElement('textarea');
514 ta.value = t; ta.style.position = 'fixed'; ta.style.opacity = '0';
515 document.body.appendChild(ta); ta.focus(); ta.select();
516 var ok = false;
517 try { ok = document.execCommand('copy'); } catch(e){ ok = false; }
518 document.body.removeChild(ta);
519 return ok;
520 }
522 function flash(ok, text){
523 var b = $('banner');
524 b.classList.toggle('fail', !ok);
525 b.innerHTML = ok
526 ? '✓ Copied! Now paste it into the chat to start your session.'
527 : '⚠ Couldn’t reach the clipboard — copy the text in the box, then paste it into the chat.';
528 b.classList.add('show');
529 setTimeout(function(){ b.classList.remove('show'); }, 4500);
530 // Last resort on a hard failure: a prefilled, selectable prompt so the text is never lost.
531 if (!ok){ window.prompt('Copy this, then paste it into the chat:', text); }
532 }
534 $('copy').addEventListener('click', function(){
535 var text = compose();
536 if (navigator.clipboard && navigator.clipboard.writeText){
537 navigator.clipboard.writeText(text).then(
538 function(){ flash(true, text); },
539 function(){ flash(fallbackCopy(text), text); }
540 );
541 } else { flash(fallbackCopy(text), text); }
542 });
544 setHint();
545 setThemeIcon();
546 update();
547})();
548</script>
549</body>
550</html>
551"""
554# --- browse-page layout: a "Proven & Professional" lead group, then super-groups ----------
555CLASSIC_GROUP = "Proven & Professional"
556LEAD_HUE = "#3d4f73" # a dignified slate for the professional lead group
558# Super-group order for the shipped categories. Categories not listed (e.g. user-added
559# via --extra) render last under "More", alphabetically — so custom catalogs always show.
560CATEGORY_GROUPS = (
561 ("Structured & Analytical", ("structured", "deep")),
562 ("Creative & Generative", ("creative", "biomimetic", "cultural", "speculative_future", "quantum")),
563 ("Wild & Playful", ("wild", "absurdist", "theatrical", "constraint")),
564 ("Introspective & Personal", ("introspective_delight", "collaborative")),
567# Human labels for the `good_for` goal tags; this dict's order is the filter-bar order.
568GOAL_LABELS = {
569 "feature": "Build a feature",
570 "novel": "Novel concept",
571 "strategy": "Strategy",
572 "planning": "Planning",
573 "diagnosis": "Diagnose",
574 "personal": "Personal / life",
575 "unstuck": "Get unstuck",
579def _good_for_label(good: str) -> str:
580 parts = [GOAL_LABELS.get(g, g) for g in good.split("|") if g]
581 return ("Great for: " + " · ".join(parts)) if parts else ""
584def _svg(inner: str) -> str:
585 return f'<svg class="ico" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">{CHIP}{inner}</svg>'
588def _card(r: dict, lead: bool = False) -> str:
589 """One technique card. `lead=True` cards live in the cross-cutting professional group;
590 they carry their own category hue (inline --c) and data-lead so selection can de-dupe."""
591 name = html.escape(r["technique_name"])
592 desc = html.escape(r["description"])
593 hue, glyph = category_style(r["category"])
594 disp_cat = html.escape(pretty(r["category"]))
595 good = html.escape(r.get("good_for", ""))
596 prov = html.escape(r.get("provenance", ""))
597 style = f' style="--c:{hue}"' if lead else ""
598 lead_attr = ' data-lead="1"' if lead else ""
599 gf = _good_for_label(r.get("good_for", ""))
600 gf_html = f'<span class="gf">{html.escape(gf)}</span>' if gf else ""
601 return (
602 f'<label class="tech"{style}><input type="checkbox" '
603 f'data-name="{name}" data-cat="{disp_cat}" data-desc="{desc}" data-good="{good}" data-prov="{prov}"{lead_attr}>'
604 f'<span class="ic2">{_svg(glyph)}{_svg(tech_icon(r["technique_name"]))}</span>'
605 f'<span><span class="n">{name}</span><span class="d">{desc}</span>{gf_html}</span></label>'
606 )
609def _invent_card(disp_cat: str, glyph: str) -> str:
610 """A dashed 'invent on the fly, in this category's spirit' card appended to each section."""
611 return (
612 f'<label class="tech invent"><input type="checkbox" data-invent="{disp_cat}">'
613 f'<span class="ic2">{_svg(glyph)}</span>'
614 f'<span><span class="n">✨ Invent a {disp_cat} technique</span>'
615 f'<span class="d">Make up a brand-new technique on the fly, in the spirit of {disp_cat}</span></span></label>'
616 )
619def html_doc(rows: list[dict]) -> str:
620 """Render the self-contained 'browse all techniques' selection page from the catalog.
622 Deterministic ordering so the shipped asset can be snapshot-tested against the CSV:
623 a cross-cutting "Proven & Professional" lead group (every `classic`-tagged row), then
624 the categories in fixed super-group order, then any unlisted/custom categories under
625 "More" alphabetically. Techniques render in file order within a category. A `classic`
626 row appears both in the lead group and its home category; the page de-dupes on select.
627 """
628 groups: dict[str, list[dict]] = {}
629 for r in rows:
630 groups.setdefault(r["category"], []).append(r)
632 body: list[str] = []
633 chips: list[str] = []
635 def add_section(cat: str) -> None:
636 hue, glyph = category_style(cat)
637 disp = html.escape(pretty(cat))
638 cards = [_card(r) for r in groups[cat]]
639 cards.append(_invent_card(disp, glyph))
640 chips.append(f'<button type="button" class="chip" data-cat="{disp}" style="--cc:{hue}">{disp}</button>')
641 body.append(
642 f'<section data-cat="{disp}" style="--c:{hue}"><h2>{disp}<span class="cnt">{len(groups[cat])}</span></h2>'
643 f'<div class="grid">{"".join(cards)}</div></section>'
644 )
646 # 1) lead group — every classic-tagged technique, cross-category (no invent card here)
647 classics = [r for r in rows if r.get("provenance", "").lower() == "classic"]
648 if classics:
649 disp = html.escape(CLASSIC_GROUP)
650 lead_cards = "".join(_card(r, lead=True) for r in classics)
651 chips.append(f'<button type="button" class="chip" data-cat="{disp}" style="--cc:{LEAD_HUE}">{disp}</button>')
652 body.append(
653 f'<section data-cat="{disp}" style="--c:{LEAD_HUE}"><h2>{disp}<span class="cnt">{len(classics)}</span></h2>'
654 f'<div class="grid">{lead_cards}</div></section>'
655 )
657 # 2) shipped categories, in super-group order
658 placed = set()
659 for group_title, cats in CATEGORY_GROUPS:
660 present = [c for c in cats if c in groups]
661 if not present:
662 continue
663 hue, _ = category_style(present[0])
664 body.append(f'<h2 class="grouphdr" style="--c:{hue}">{html.escape(group_title)}</h2>')
665 for c in present:
666 add_section(c)
667 placed.add(c)
669 # 3) leftover (custom / --extra) categories, alphabetically
670 leftover = sorted(c for c in groups if c not in placed)
671 if leftover:
672 body.append('<h2 class="grouphdr" style="--c:#8a8f9e">More</h2>')
673 for c in leftover:
674 add_section(c)
676 # goal-affinity filter bar — only if the catalog actually carries good_for tags
677 present_goals: set[str] = set()
678 for r in rows:
679 for g in (r.get("good_for", "") or "").split("|"):
680 if g:
681 present_goals.add(g)
682 goalbar = ""
683 if present_goals:
684 ordered = [g for g in GOAL_LABELS if g in present_goals] + sorted(present_goals - set(GOAL_LABELS))
685 gchips = "".join(
686 f'<button type="button" class="goal" data-goal="{html.escape(g)}">{html.escape(GOAL_LABELS.get(g, g))}</button>'
687 for g in ordered
688 )
689 goalbar = (
690 f'<div class="bar"><span class="glabel">Great for</span><div class="goals" id="goals">{gchips}</div></div>'
691 )
693 total = html.escape(f"{len(rows)} techniques across {len(groups)} categories.")
694 return (
695 SELECTOR_TEMPLATE.replace("{{BODY}}", "\n".join(body))
696 .replace("{{CHIPS}}", "".join(chips))
697 .replace("{{GOALBAR}}", goalbar)
698 .replace("{{TOTAL}}", total)
699 )
702def pin_utf8(stream):
703 """Pin a console stream to UTF-8, keeping its own error handler.
705 `--extra` technique text and the technique names echoed to stderr are
706 arbitrary user input, so either stream can carry a character the platform
707 default cannot encode (cp1252 on Windows) and print() then raises.
709 errors= is passed through deliberately: reconfigure(encoding=...) alone
710 resets the handler to "strict", which would silently downgrade stderr's
711 POSIX default of "backslashreplace" and turn a diagnostic about an
712 undecodable path into a traceback.
713 """
714 reconfigure = getattr(stream, "reconfigure", None)
715 if reconfigure is not None:
716 reconfigure(encoding="utf-8", errors=getattr(stream, "errors", None) or "strict")
719def main(argv: list[str] | None = None) -> int:
720 pin_utf8(sys.stdout)
721 pin_utf8(sys.stderr)
722 p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
723 p.add_argument(
724 "--file", type=Path, default=DEFAULT_FILE, help="technique CSV (default: sibling assets/brain-methods.csv)"
725 )
726 p.add_argument(
727 "--extra",
728 type=Path,
729 help="JSON overlay of additional techniques (customize.toml additional_techniques), merged into every command",
730 )
731 p.add_argument("--json", action="store_true", help="emit structured JSON instead of lean text")
732 sub = p.add_subparsers(dest="cmd", required=True)
733 sub.add_parser("categories", help="list category names + counts")
734 pl = sub.add_parser("list", help="the index: category/name/gist (needs --category or --all)")
735 pl.add_argument("--category", action="append", help="filter to a category (repeatable)")
736 pl.add_argument("--all", action="store_true", help="dump the entire catalog (deliberate; large)")
737 ps = sub.add_parser("show", help="full gist + detail file for named techniques")
738 ps.add_argument("names", nargs="+")
739 pr = sub.add_parser("random", help="pick techniques at random")
740 pr.add_argument("--category", action="append", help="restrict to a category (repeatable)")
741 pr.add_argument("-n", type=int, default=1, help="how many (default 1)")
742 ph = sub.add_parser("html", help="write the offline 'browse all' selection page")
743 ph.add_argument("--out", help="file to write the page to (required; never prints the catalog)")
744 args = p.parse_args(argv)
746 if not args.file.is_file():
747 print(f"error: technique file not found: {args.file}", file=sys.stderr)
748 return 2
749 rows = load(args.file)
750 if args.extra:
751 if not args.extra.is_file():
752 print(f"error: --extra file not found: {args.extra}", file=sys.stderr)
753 return 2
754 try:
755 rows = merge_extra(rows, load_extra(args.extra))
756 except (OSError, ValueError) as e:
757 print(f"error: could not read --extra: {e}", file=sys.stderr)
758 return 2
759 csv_dir = args.file.resolve().parent
761 if args.cmd == "categories":
762 print(fmt_categories(categories(rows), args.json))
763 elif args.cmd == "list":
764 if not args.category and not args.all:
765 print(
766 "error: `list` needs --category (one or more) — or --all to dump the whole "
767 "catalog on purpose. Use `categories` for the cheap map, or `random` to draw blind.",
768 file=sys.stderr,
769 )
770 return 2
771 print(fmt_list(filter_cats(rows, args.category), args.json))
772 elif args.cmd == "show":
773 found, missing = find(rows, args.names)
774 for m in missing:
775 print(f"# not found: {m}", file=sys.stderr)
776 if not found:
777 return 1
778 print(fmt_show(found, csv_dir, args.json))
779 elif args.cmd == "random":
780 pool = filter_cats(rows, args.category)
781 if not pool:
782 print("# no techniques match", file=sys.stderr)
783 return 1
784 n = max(0, min(args.n, len(pool))) # clamp: never crash on a negative or oversized -n
785 print(fmt_list(random.sample(pool, n), args.json))
786 elif args.cmd == "html":
787 if not args.out:
788 print(
789 "error: `html` needs --out PATH — it writes the selection page to a file and "
790 "never prints the catalog to stdout (which would defeat the point).",
791 file=sys.stderr,
792 )
793 return 2
794 out = Path(args.out)
795 out.parent.mkdir(parents=True, exist_ok=True)
796 out.write_text(html_doc(rows), encoding="utf-8")
797 print(f"wrote {out} ({len(rows)} techniques, {len(categories(rows))} categories)")
798 return 0
801if __name__ == "__main__":
802 if sys.platform == "win32":
803 # Piped output on Windows defaults to a legacy code page, not UTF-8.
804 sys.stdout.reconfigure(encoding="utf-8")
805 sys.stderr.reconfigure(encoding="utf-8")
806 sys.exit(main())