SLOPSHOPPER

brainstorm-board

A pane with the brainstorms the brainstorm skill recorded, project's first, then global, shown as formatted text.

newpaneguardcommandtooltimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · brainstorm-board
│ ┃ Brainstorms ✕ › fix the failing auth test and add an audit log call │ ┃ Brainstorms [ Close ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ No brainstorms recorded yet. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /brainstorm-board │ ⎿ brainstorm-board: Brainstorm board opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Brainstorms
Brainstorms [ Close ] No brainstorms recorded yet.
README

AI Skills

A small collection of reusable SKILL.md instructions for coding agents. The skills are plain Markdown, version-controlled, and portable across compatible agent tools.

This README is the reference: what the skills are, which platforms they support, and how to install them. The [wiki][wiki] answers the other question — why the project is built this way: why a Markdown repository contains Rust crates, why the dev shell compiles bash 3.2 from source, which design choices were made and what they cost, how to verify any of it yourself, and what does not work yet.

[wiki]: https://github.com/tschallacka/ai-skills/wiki

Install

Pick whichever fits how you work. Any of these opens the same interactive installer, where you choose the skills and the agent destination(s).

npx — installs and runs in one step, nothing left on PATH afterward:

npx --yes --package @tschallacka/ai-skills ai-skills-install

Linux / macOS — the one-command installer, no npm required:

curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh | sh

Windows — the identical command, run inside Git Bash or WSL2 (both provide the POSIX sh it needs; there is no separate PowerShell/cmd installer):

curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh | sh

See "One-command installer" below for the full list of install destinations, and "npm installation" for a persistent ai-skills-install command on PATH instead of npx.

Skills

SkillPurposeDocumentation
PlanningDurable, resumable plans: goals, ordered steps, verification, progress trackers, handoff notes — plus a single-file HTML overview of any plan, and a live served version that updates in place. Steps complete with git-diff atomicity evidence, not decorative checkboxes.docs
Bug reportA defect register in one JSON file: every entry carries its reproduction, observed vs expected, the mechanism, and the verification that fails without the fix. bugs add/bugs update write through shared validation; a closure without proof is refused.docs
TodoA work queue that outlives the conversation, in one JSON file: nested tasks, every closed item carries its evidence. todo add/todo update keep the register sound; read recipes print user-ready output.docs
BrainstormShapes an under-specified idea into a recorded, agreed picture (brainstorm.md) before planning, with an adversarial completion pass and a plan-vs-implement gate.docs
Post-implementation reviewAfter-the-fact review of built code with concrete proposed fixes, in three passes: implementer self-analysis, an independent solutions agent, and a critical-feedback agent that ranks every fix.docs
Project-specific deviationsRecords confirmed project behavior and environment quirks in per-project notes that future agents load instead of re-debugging.docs
Resource-limited testingRuns heavyweight commands (suites, builds, analyzers, browsers) under platform-appropriate CPU/memory caps, with honest degradation when a platform has no cap mechanism.docs
ChatRFC-1459 IRC-over-TLS message bus for agents: a rust server a standard TLS IRC client can join, a rust client with UDP discovery and TOFU cert pinning, channels, and additive history/delta reads.docs
Interactive shellOperates a full-screen terminal program an agent has never seen - nano, mc, lynx, a pager, a menu: a rust PTY wrapper publishing each screen change as one JSONL event, compact row views and deltas to keep context small, element discovery, and a unix-socket client for keys, combos, pastes, mouse and resize. POSIX only.docs
Git worktreesParallel agents in one repository: isolated worktree verification, per-agent trees, and merging back in a conflict-aware order without trampling the main checkout.docs
Git merge resolvingConflicts resolved by what each side changed rather than by ours/theirs: reading intent from history, unions that look like choices, regenerated output, and attributing post-merge failures to the side that caused them.docs
Merge request etiquetteDescriptions a reviewer can act on, in the author's voice: a one-paragraph TLDR, the defect/cause/change body, derived from the branch's commits, and the one case where a collapsible section earns its place.docs
Text etiquetteShorthand and a clipped register for an agent's prose - chat, dev talk, and its own thinking: facts first, a shared shorthand with an ask-don't-guess rule, praise capped at gj, and the people-please prose banned. Plain english on request.docs
Question etiquetteNumbered questions, lettered options, never a bullet: a reply like Q7b is unambiguous, a partial answer names exactly which numbers are still open, and a lettered list always ends with "none of these, I'll say it myself."docs
AI text editorServer-owned agent editor tabs with explicit search, revision-aware edits, undo/redo, raw-byte and hex modes, SQLite metadata, and Unix/TCP transport.docs
wwwA brake the human can pull, and one the agent pulls on itself when it is thrashing: stop, answer what do we have / what are the values / what are we trying to achieve, in order, then continue with one reasoned step or a numbered question.docs
CI failuresWhat actually failed in a CI run or pipeline, from a run/pipeline id, a PR/MR number, or a branch: GitHub and GitLab detected from the git remote, named rather than chosen silently, with just the failing lines extracted per job.docs
DecisionsA register of non-blocking questions raised mid-work: Q# ids, lettered options, priority and the branch they came from as context, so a question can be stubbed and left open without blocking a turn.docs
rjqParses, filters and searches JSON with the shipped rjq binary, a jq-compatible tool, on machines without jq.docs
TailpipeA less/tail for agents: pipe a command's output into a named, server-held stream with chat-style message ids; a reader lists/reads/searches/tails it from anywhere, an MCP adapter offers the same as typed tools, and a board mod shows it to a human. Idle streams are gzip-snapshotted after 15 minutes.docs

Use a skill only when its frontmatter trigger matches the task or when the user explicitly requests it. Each skill documents when not to activate.

Supported platforms

"Portable" elsewhere in this repository means portable across agent tools (Claude Code, Codex, OpenCode, OpenClaw, Cline). Operating-system support is separate and stated here:

Those tools do not identify the calling agent the same way, which matters to every per-agent feature here. src/agent-session-key/HARNESS-IDENTITY.md records what each one provides, how it was measured, and the procedure for contributing a harness that is not yet listed.

Supported
Linuxany distribution, bash 4 or 5, GNU userland
macOS11+ with the stock /bin/bash 3.2, BSD userland; Homebrew bash not required
WindowsGit for Windows' bash with its bundled coreutils, checked by CI legs, or WSL2, which is a Linux install. The evidence and the conventions are in .agents/MAINTAINER.md 1.16, which is in a full git checkout and not part of the installed package

The one-command install needs a POSIX sh (bootstrap.sh has no bash-only constructs), plus curl, tar, awk, and standard coreutils; the installed skills' own helper scripts need bash, POSIX coreutils, awk, sed, grep, and git. The planning skill additionally needs rjq, and on macOS resource-limited-testing needs memlimit; the installer checks for both up front and prints a per-platform install hint rather than failing partway through. Those two are the only extra runtime dependencies any skill has — in particular python3 is not required by anything that gets installed, only by this repository's own benchmark harness. CODE-STYLE.md is the contract these scripts are held to; what CI proves on each platform is mapped in .agents/MAINTAINER.md section 3 (a full git checkout has both; the installed package has neither).

One skill is genuinely OS-scoped: resource-limited-testing enforces a hard RAM cap only on Linux, via a transient systemd --user cgroup v2 scope. On macOS it uses memlimit (MIT, by Jelle Besseling), which refuses allocations past the cap instead of killing the process — a best-effort cap on real resident memory over the process tree, not a cgroup-equivalent guarantee; SKILL.md lists what it does and does not promise. On Apple Silicon macOS the installer declares memlimit a soft requirement: without it the skill still installs and the run warns that the RAM cap is not enforced. The wrapper then degrades to nice plus cpulimit (CPU throttling only); on a Linux session without a user systemd instance it falls back to ulimit -v. memlimit is not asked for on Intel Macs at all — it does not support them. Every other skill behaves identically on both.

One-command installer

Run this command and choose the skills and agent destination interactively:

curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh | sh

The installer can install all the skills or one skill, and supports these global skill roots:

DestinationAgent or standard
~/.agents/skillsUniversal Agent Skills root; recommended shared destination
~/.codex/skillsCodex CLI
~/.claude/skillsClaude Code
~/.config/opencode/skillsOpenCode
~/.openclaw/skillsOpenClaw managed skills
~/.cline/skillsCline

The universal root is also discovered by OpenCode and OpenClaw. Installing the same skill into multiple roots can create duplicate definitions or precedence conflicts, so choose only the roots you need.

The interactive installer checks which supported agents are present and omits roots for agents it cannot detect. Custom roots are saved in ~/.config/tsch-ai-skills/custom-locations and are offered again when they still exist.

npm installation

Install the package globally to expose the installer command. The npm package keeps the skills in this repository and links ai-skills-install directly to installer/bootstrap.sh, which fetches the matching compiled installer release for your platform on first run:

npm install -g @tschallacka/ai-skills
ai-skills-install

For a one-off run without a global install:

npx --yes --package @tschallacka/ai-skills ai-skills-install

The npm package does not install skills automatically as an npm lifecycle side-effect; run the installer command when you are ready to choose a target.

Updating an existing install

Run the installer again against the same root. It compares every managed file with the repository copy and reports one of three outcomes per destination: Up to date (nothing differed), Installed (files were written), or Skipped (you declined, or the destination needs manual review).

Each installed skill contains a .version marker identifying its tag, branch, and commit. If an installed file differs from the repository version, the installer asks before replacing it. For a managed version transition that the user approves — the .version marker differs, so the change came from a new release rather than from you — old files are replaced without backups; the previous version can be restored by running the installer against its tag with AI_SKILLS_REF. Unmanaged changes still receive <file>.bak backups (.bak.1, .bak.2, … if one already exists). A symlinked skill is skipped for manual review rather than following the link and modifying an unexpected location.

Installing or updating one skill

Interactively, choose that one skill at the menu. Headless, name it:

curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh \
  | sh -s -- install --skill planning --target "$HOME/.codex/skills"

--skill may be given more than once, and each value may itself be a comma-separated list, so --skill planning --skill brainstorm and --skill planning,brainstorm install the same two. Repeats are collapsed, menu numbers work (--skill 1,4), and all selects everything wherever it appears.

Headless and CI usage

Use --all, --skill, --target and --yes when the choices are already known. --target takes a single root, so installing into two roots is two runs.

# Install all skills into the shared Agent Skills root
curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh \
  | sh -s -- install --all --target "$HOME/.agents/skills"

# Unattended replacement: managed version transitions replace without backups,
# unmanaged changed files are still backed up as <file>.bak
curl -fsSL https://raw.githubusercontent.com/tschallacka/ai-skills/master/installer/bootstrap.sh \
  | sh -s -- install --all --target "$HOME/.agents/skills" --yes

Every run ends with a summary block on stdout saying what was installed, what was not, and why; the progress and diagnostics go to stderr, so installer install … > summary.txt keeps the outcome and 2>/dev/null keeps it readable. A blocked skill is reported once — not once per root — with the commands that finish the job. This is what an --all run on a machine without rjq prints:

== Summary ==
Installed: /home/u/.agents/skills/project-specifics
Installed: /home/u/.agents/skills/resource-limited-testing
Installed: /home/u/.agents/skills/brainstorm
Installed: /home/u/.agents/skills/post-implementation-review
Skipped:   planning — a hard requirement is missing, nothing was written
To install planning once its requirements are met:
  1. install rjq:
    sudo apt-get install -y rjq
  2. replay this run:
  installer install --skill planning --target /home/u/.agents/skills --yes

The install step is chosen for the detected platform and package manager, and the replay line carries the same target and flags as the run that printed it, naming the installer binary bootstrap.sh downloaded to run it. The exit status is non-zero, because four of five skills is a partial install and CI must not read it as success.

Runtime dependencies

Dependencies are declared per skill, so one unsatisfiable dependency never stops the other skills from installing. Each skill ships a requires.tsv naming what it needs, on which platform and architecture, and how badly:

StrengthEffect
hardThe skill does not work without the tool. It is not installed, the run explains why and prints the replay commands, and the exit status is non-zero.
softThe skill works in a degraded form. It is installed, with a warning naming the tool and the capability that is lost. The exit status is unaffected.

Currently:

  • planning requires rjq (hard, every platform) — without it validate-plan.sh refuses to run and the plan gates stop firing.
  • resource-limited-testing names memlimit (soft, Apple Silicon macOS only) — see Supported platforms above for what the degraded path still does.

No other skill has a runtime dependency.

Exit codes

CodeMeaning
0Everything requested was installed. Soft warnings do not change this.
1A requested skill was blocked by a hard requirement, or any other error.
2install-skill only: approval declined, nothing was written.
3install-skill only: an unsafe collision (an existing file that is not a managed version upgrade, or a symlink).

Codes 2 and 3 belong to the machine-facing install-skill subcommand that the planning skill's own tooling uses; the interactive, install --all, and install --skill paths only ever return 0 or 1.

Full-screen installer UI

Running the bare one-liner with no arguments, or installer interactive directly, opens a full-screen skill picker instead of the numbered menu:

KeyAction
↑/k, ↓/j, PageUp, PageDown, Home, Endmove the cursor
Enter / Spacetoggle the skill under the cursor
Tab / Shift-Tabswitch focus between the skill list and the info pane
a / nselect all / select none
d, r, m (info pane focused)show dependency hints, re-verify requirements, cycle a skill's integration mode
iconfirm and install the current selection
q / Escapequit without installing

With neither --target nor --agent given, it also prompts to choose an auto-detected agent root, a saved custom directory, a new custom directory, or a for every listed root.

Review the installer before running it if you do not trust the source. Skills are instructions that may guide agents to run commands or access files.

install.sh retired in favor of a compiled Rust installer (src/installer/); installer/bootstrap.sh is the small, pure-POSIX-sh entry point (#!/usr/bin/env sh, no bash-only constructs) that detects the platform, downloads the matching release, and hands off to it — see CONTRIBUTING.md before editing either.

Supported agent documentation

Development checkout

installer/bootstrap.sh always downloads a release archive, so it is not how a checkout installs its own local files. Build the installer and point it at the checkout with --source instead:

cargo build --release -p installer
./target/release/installer interactive --source .

--package dev (also read from $PACKAGE_SELECTION) ships the MODE: DEV files too — tests, maintainer docs — instead of filtering them out, for installing a working development copy rather than the prod set.

installer/bootstrap.sh itself accepts AI_SKILLS_REPO_URL (a different owner/repo to resolve GitHub's "latest release" redirect against) and AI_SKILLS_RELEASE_URL (an exact archive URL, bypassing that redirect entirely — how RELEASE.md verifies one specific tag).

Notes

  • The planning-skill benchmark harness is agent-agnostic. benchmark/planning/runtime/ makes the worker/reviewer/analyzer launch, session-id extraction, and token telemetry pluggable per CLI: the active agent defaults to codex and is selected with BENCHMARK_AGENT (opencode, claude), with a shared launcher (lib-agent.sh) owning all setsid/timeout/process-group control. See benchmark/planning/runtime/README.md for the contract and first-time setup.
  • Skills are instructions, not standalone applications. They add no dependencies unless a skill explicitly documents one.
  • resource-limited-testing's platform behaviour is described under Supported platforms; its SKILL.md documents each fallback in detail.
  • Read and review third-party skills before enabling them in an agent with access to sensitive files, credentials, or external systems.

License

Distributed under the MIT License.

Source 2 files
hooks/register.tsx 305 lines
1import type { Register } from 'claude-code'
2import { update } from 'claude-code'
3
4// The brainstorms the brainstorm skill recorded: each is a `brainstorm.md` in a
5// plan's folder, the project's own `.plans` first and the global plans after.
6// The list is shown first; a brainstorm opens as formatted text, with a button
7// back to the list. The chosen one is kept in $.state, so a redraw keeps it.
8// Toggled by `enabled` in settings.json pluginConfigs["brainstorm-board"].options.
9
10const PANE = 'brainstorm-board'
11const TOOL = 'show_brainstorm_board'
12const READ = 'read_brainstorm_board'
13const SCROLL = 'scroll_brainstorm_board'
14const pick = { plugin: 'brainstorm-board', key: 'pick' } as const
15
16type Entry = { dir: string; name: string; scope: 'project' | 'global'; mtimeMs: number; firstLine: string }
17
18// The part of `$.fs` the reading needs.
19type Fs = {
20  exists: (path: string) => Promise<boolean>
21  list: (path?: string) => Promise<{ name: string; kind: string }[]>
22  read: (path: string) => Promise<string>
23  stat: (path: string) => Promise<{ mtimeMs: number }>
24}
25
26type Line = { style: 'heading' | 'quote' | 'body' | 'blank'; text: string }
27
28// Inline markers the pane cannot draw are removed, so `**word**` reads as `word`.
29function plain(text: string): string {
30  return text
31    .replace(/\*\*(.+?)\*\*/g, '$1')
32    .replace(/__(.+?)__/g, '$1')
33    .replace(/`([^`]+)`/g, '$1')
34    .replace(/(^|\s)\*(\S[^*]*)\*/g, '$1$2')
35}
36
37// The Markdown of a brainstorm, line by line, with the planning skill's `§`
38// section numbers taken out, which a reader does not need.
39function markdownLines(markdown: string): Line[] {
40  return markdown
41    .split('\n')
42    .filter(raw => !raw.trimStart().startsWith('§'))
43    .map((raw): Line => {
44      const line = raw.trimEnd()
45      if (line.trim() === '') return { style: 'blank', text: '' }
46      if (/^\s*-{3,}\s*$/.test(line)) return { style: 'quote', text: '─'.repeat(24) }
47      const heading = /^#{1,6}\s+(.*)$/.exec(line)
48      if (heading) return { style: 'heading', text: plain(heading[1] ?? '') }
49      const task = /^(\s*)[-*]\s+\[( |x|X)\]\s+(.*)$/.exec(line)
50      if (task) {
51        const box = task[2] === ' ' ? '☐' : '☑'
52        return { style: 'body', text: `${task[1] ?? ''}${box} ${plain(task[3] ?? '')}` }
53      }
54      const bullet = /^(\s*)[-*]\s+(.*)$/.exec(line)
55      if (bullet) return { style: 'body', text: `${bullet[1] ?? ''}• ${plain(bullet[2] ?? '')}` }
56      return { style: 'body', text: plain(line) }
57    })
58}
59
60// The first heading of a brainstorm, which names it; its folder name otherwise.
61function titleOf(markdown: string, fallback: string): string {
62  const heading = markdown.split('\n').find(line => /^#{1,6}\s+/.test(line))
63  return heading ? plain(heading.replace(/^#{1,6}\s+/, '').trim()) : fallback
64}
65
66// The brainstorms under one folder, most recently changed first.
67async function listBrainstorms(fs: Fs, base: string, scope: 'project' | 'global'): Promise<Entry[]> {
68  if (!(await fs.exists(base))) return []
69  const entries: Entry[] = []
70  for (const folder of await fs.list(base)) {
71    if (folder.kind !== 'dir') continue
72    const file = `${base}/${folder.name}/brainstorm.md`
73    if (!(await fs.exists(file))) continue
74    // A file that vanishes between the checks is skipped, not allowed to fail the list.
75    const text = await fs.read(file).catch(() => null)
76    const mtimeMs = await fs.stat(file).then(stat => stat.mtimeMs).catch(() => 0)
77    if (text === null) continue
78    entries.push({
79      dir: `${base}/${folder.name}`,
80      name: folder.name,
81      scope,
82      mtimeMs,
83      firstLine: titleOf(text, folder.name),
84    })
85  }
86  return entries.sort((a, b) => b.mtimeMs - a.mtimeMs)
87}
88
89// The redraw timer's cancel handle, kept so a re-registered session replaces the
90// timer rather than adding a second one.
91let tick: { cancel: () => void } | undefined
92
93export const register: Register = (on, options) => {
94  if (options.enabled === false) return
95
96  const plansDir = String(options.plansDir ?? '')
97
98  on('session.start', async ($, e, next) => {
99    await $.command.register({
100      name: 'brainstorm-board',
101      description: 'Show the brainstorms in a pane; `/brainstorm-board close` hides it',
102    })
103    await $.tool.register({
104      name: TOOL,
105      description:
106        'Show the brainstorms recorded for this project and the global plans, in a pane, and return the list as text for the chat.',
107      inputSchema: { type: 'object', properties: {} },
108    })
109    await $.tool.register({
110      name: READ,
111      description:
112        'Read which brainstorm the person has picked in the brainstorm board, and the brainstorms recorded, as text, without opening the pane.',
113      inputSchema: { type: 'object', properties: {} },
114    })
115    await $.tool.register({
116      name: SCROLL,
117      description:
118        'Scroll the brainstorm board to a paragraph of the brainstorm it shows, by words in that paragraph. Says when no line matches.',
119      inputSchema: {
120        type: 'object',
121        properties: { text: { type: 'string', description: 'Words in the paragraph to scroll to.' } },
122        required: ['text'],
123      },
124    })
125    // A brainstorm recorded while the pane is open shows up on the next redraw.
126    tick?.cancel()
127    tick = $.clock.every(5000, () => $.ui.invalidate('ui.render'))
128    return next(e)
129  })
130
131  on('command.run', { command: 'brainstorm-board' }, async ($, e) => {
132    if (e.args.trim().toLowerCase() === 'close') {
133      await $.ui.close({ id: PANE })
134      return { text: 'Brainstorm board closed.' }
135    }
136    await $.ui.open({ id: PANE, title: 'Brainstorms' })
137
138    return { text: 'Brainstorm board opened.' }
139  })
140
141  // The agent's way to show the board. It opens the pane and returns the list.
142  on('tool.call', { tool: `mcp__brainstorm-board__${TOOL}` }, async $ => {
143    const home = (await $.env.get('HOME')) ?? ''
144    const xdg = (await $.env.get('XDG_CONFIG_HOME')) ?? ''
145    const project = await $.session.root()
146    const global = plansDir || `${xdg || `${home}/.config`}/tsch-ai-skills/plans`
147    const fs: Fs = {
148      exists: path => $.fs.exists(path),
149      list: path => $.fs.list(path),
150      read: path => $.fs.read(path),
151      stat: path => $.fs.stat(path),
152    }
153    const all = [
154      ...(await listBrainstorms(fs, `${project}/.plans`, 'project')),
155      ...(await listBrainstorms(fs, global, 'global')),
156    ]
157    await $.ui.open({ id: PANE, title: 'Brainstorms' })
158
159    const listed = all.map(entry => `${entry.scope}: ${entry.firstLine} (${entry.name})`)
160    return {
161      result: [
162        all.length === 0 ? 'No brainstorms recorded.' : 'Brainstorms recorded:',
163        ...listed,
164      ].join('\n'),
165    }
166  })
167
168  // The agent's way to move the board to a paragraph of the picked brainstorm: the
169  // first drawn line holding the words. Keys match the reading view's lines.
170  on('tool.call', { tool: `mcp__brainstorm-board__${SCROLL}` }, async ($, e) => {
171    const home = (await $.env.get('HOME')) ?? ''
172    const xdg = (await $.env.get('XDG_CONFIG_HOME')) ?? ''
173    const project = await $.session.root()
174    const global = plansDir || `${xdg || `${home}/.config`}/tsch-ai-skills/plans`
175    const fs: Fs = {
176      exists: path => $.fs.exists(path),
177      list: path => $.fs.list(path),
178      read: path => $.fs.read(path),
179      stat: path => $.fs.stat(path),
180    }
181    const { value: chosenDir } = await $.state.get(pick)
182    const all = [
183      ...(await listBrainstorms(fs, `${project}/.plans`, 'project')),
184      ...(await listBrainstorms(fs, global, 'global')),
185    ]
186    const chosen = all.find(entry => entry.dir === chosenDir)
187    if (!chosen) return { result: 'No brainstorm is picked in the board.' }
188    const text = await fs.read(`${chosen.dir}/brainstorm.md`).catch(() => null)
189    if (text === null) return { result: 'The picked brainstorm could not be read.' }
190
191    const wanted = String(e.text ?? '').trim().toLowerCase()
192    const drawn = markdownLines(text)
193    const index = drawn.findIndex(line => line.style !== 'blank' && line.text.toLowerCase().includes(wanted))
194    if (index < 0) return { result: `Nothing matching "${wanted}" in the brainstorm.` }
195    await $.ui.open({ id: PANE, title: 'Brainstorms', focus: true })
196    await $.ui.scroll({ to: { key: `brainstorm-${index}` }, in: PANE, block: 'start' })
197    return { result: `Scrolled to "${drawn[index]?.text ?? ''}".` }
198  })
199
200  // The agent's read of the board's pick: the brainstorm the person chose, its
201  // file, and the list. Read-only; the pane is not opened.
202  on('tool.call', { tool: `mcp__brainstorm-board__${READ}` }, async $ => {
203    const home = (await $.env.get('HOME')) ?? ''
204    const xdg = (await $.env.get('XDG_CONFIG_HOME')) ?? ''
205    const project = await $.session.root()
206    const global = plansDir || `${xdg || `${home}/.config`}/tsch-ai-skills/plans`
207    const fs: Fs = {
208      exists: path => $.fs.exists(path),
209      list: path => $.fs.list(path),
210      read: path => $.fs.read(path),
211      stat: path => $.fs.stat(path),
212    }
213    const { value: chosenDir } = await $.state.get(pick)
214    const all = [
215      ...(await listBrainstorms(fs, `${project}/.plans`, 'project')),
216      ...(await listBrainstorms(fs, global, 'global')),
217    ]
218    const chosen = all.find(entry => entry.dir === chosenDir)
219    const lines = [
220      chosen ? 'Picked in the board: one brainstorm' : 'Picked in the board: none (the list is shown)',
221      `Brainstorms recorded: ${all.length}`,
222      ...all.map(entry => `${entry.scope}: ${entry.firstLine} (${entry.name})`),
223    ]
224    if (chosen) lines.push(`Picked: ${chosen.scope}: ${chosen.firstLine}`, `File: ${chosen.dir}/brainstorm.md`)
225    const live = await $.ui.selection().catch(() => undefined)
226    lines.push(`Highlighted in the board: ${live?.text ?? 'none'}`)
227    return { result: lines.join('\n') }
228  })
229
230  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
231    const { Box, Button, Text } = $.ui.resolve(e)
232    const rendered = (markdown: string) =>
233      markdownLines(markdown).map((line, index) => {
234        const key = `brainstorm-${index}`
235        if (line.style === 'blank') return <Box key={key}><Text> </Text></Box>
236        if (line.style === 'heading')
237          return (
238            <Box key={key}>
239              <Text bold underline color="cyan">
240                {line.text}
241              </Text>
242            </Box>
243          )
244        if (line.style === 'quote') return <Box key={key}><Text dimColor>{line.text}</Text></Box>
245        return <Box key={key}><Text>{line.text}</Text></Box>
246      })
247
248    const home = (await $.env.get('HOME')) ?? ''
249    const xdg = (await $.env.get('XDG_CONFIG_HOME')) ?? ''
250    const project = await $.session.root()
251    const global = plansDir || `${xdg || `${home}/.config`}/tsch-ai-skills/plans`
252    const fs: Fs = {
253      exists: path => $.fs.exists(path),
254      list: path => $.fs.list(path),
255      read: path => $.fs.read(path),
256      stat: path => $.fs.stat(path),
257    }
258    const { value: chosenDir } = await $.state.get(pick)
259    const all = [
260      ...(await listBrainstorms(fs, `${project}/.plans`, 'project')),
261      ...(await listBrainstorms(fs, global, 'global')),
262    ]
263    const chosen = all.find(entry => entry.dir === chosenDir)
264    // A file removed between the listing and this read is treated as missing, so
265    // the pane shows the list instead of drawing nothing.
266    const text = chosen ? await fs.read(`${chosen.dir}/brainstorm.md`).catch(() => null) : null
267
268    return (
269      <Box flexDirection="column">
270        <Box flexDirection="row" justifyContent="space-between">
271          <Text bold inverse>
272            Brainstorms
273          </Text>
274          <Button role="dismiss" onPress={() => $.ui.close({ id: PANE })}>
275            Close
276          </Button>
277        </Box>
278        <Text> </Text>
279        {chosen && text !== null ? (
280          <Box flexDirection="column">
281            <Button variant="primary" onPress={() => update($, pick, () => null)}>
282              back to brainstorms
283            </Button>
284            <Text dimColor>{`${chosen.scope} plan: ${chosen.name}`}</Text>
285            <Text> </Text>
286            {rendered(text)}
287          </Box>
288        ) : (
289          <Box flexDirection="column">
290            {all.length === 0 && <Text dimColor>No brainstorms recorded yet.</Text>}
291            {all.map(entry => (
292              <Button
293                key={entry.dir}
294                onPress={() => update($, pick, () => entry.dir)}
295              >
296                {`${entry.scope}: ${entry.firstLine}  (${entry.name})`}
297              </Button>
298            ))}
299          </Box>
300        )}
301      </Box>
302    )
303  })
304}
305
types/index.d.ts 6 lines
1// The brainstorm the board shows, by its folder. Null means the list.
2declare module 'claude-code' {
3  interface PluginState {
4    'brainstorm-board': { pick: string | null }  }
5}
6