SLOPSHOPPER

great-question

Side panel with the questions most likely to come up before a pitch, meeting or daily stand-up, with answers ranked by risk; listens along via Wispr Flow

paneguardcommandtoastprompttool
v0.17.0MITupdated 2026-10-24jsc2304/great-question
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · great-question
│ ┃ Great Question ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ No prepared questions yet │ great-question │ │ ┃ [ Listen live ] [ Find likely questions ] [ ⏺ Read(src/auth.ts) │ Great Question: finding likely questions … │ │ ┃ ⎿ Read 6 lines ╰────────────────────────────────────────────╯ │ ┃ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ╭──────────────────────────────────────────╮ ⏺ Bash(bun test) │ ┃ │ Where do you want to start? │ ⎿ 3 pass, 1 fail │ ┃ │ │ │ ┃ │ Prepare new questions in the background │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ▸ Likely questions about app │ │ ┃ │ ▸ Prepare my next meeting │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ▸ Prepare today's daily │ │ ┃ │ │ › /great-question-prep │ ┃ │ Or just listen to the meeting │ ⎿ great-question: Finding likely questions in the background (no o │ ┃ │ ▸ Listen live │ │ ┃ │ Questions then come from the live │ │ ┃ │ transcript only, answers from this │ │ ┃ │ repository. │ │ ┃ ╰──────────────────────────────────────────╯ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Great Question
No prepared questions yet [ Listen live ] [ Find likely questions ] [ More ▸ ] ╭──────────────────────────────────────────────────────────╮ │ Where do you want to start? │ │ │ │ Prepare new questions in the background │ │ ▸ Likely questions about app │ │ ▸ Prepare my next meeting │ │ ▸ Prepare today's daily │ │ │ │ Or just listen to the meeting │ │ ▸ Listen live │ │ Questions then come from the live transcript only, │ │ answers from this repository. │ ╰──────────────────────────────────────────────────────────╯
README

Great Question

Know the question before it is asked, and what you can safely say.

Release License: MIT Claude Code plugin

A side panel for Claude Code. Before a pitch, a customer meeting or the daily stand-up, it reads your repository, your tickets and, with Wispr Flow, earlier meetings, and shows the questions most likely to come up, each with answers ranked by risk and the source they rest on. During the meeting it listens along and predicts live which questions come next, with their answers ready before anyone asks.

  • Prepare any meeting with one command: likely questions, who asks them and why, and answers with their sources. No Wispr Flow needed.
  • Answer safely: every answer is marked say it, weak, only if covered or don't say, and the panel always offers something that is true and promises nothing, from what you worked on last.
  • Predict questions live during the meeting with Wispr Flow (macOS): the question just asked jumps to the top with its answers, looked up in your repository, and the questions likely to come next appear with their answers before they are asked.

Quick start

/plugin install great-question --marketplace jsc2304/great-question

Then, in the repository you work in:

/great-question-prep today's daily

The panel opens and the questions appear when the background agent is done. For a meeting, name it instead: /great-question-prep customer pitch Thursday. More under Installation and Usage.

Every answer carries its risk as a mark, a word and a colour, safest first:

MarkMeaning
● SAY IT · sourcedwell founded, with a source
○ WEAK · vaguetrue and binds us to nothing, but shallow
▲ ONLY IF COVERED · commitmentbinds us (date, price, scope); say it only when the documents back it
✖ DON'T SAY · riskyunsupported, attackable or contradicting the documents

What it looks like

A pitch prepared: what you worked on last as safe to say, then questions grouped by how surely they can be answered, each with its risk marks. An opened question says who is likely to ask, why, who answers on our side, and offers answers by risk, with their sources:

The Great Question panel: safe to say from my recent work, questions grouped by answer confidence, one opened with a sourced answer and a warning what not to say

Where the documents give no firm answer, the panel offers, safest first, what is harmless but shallow, what you may promise only if it is covered, and what to leave out:

An unsure question with three kinds of answer: weak, only if covered, don't say

Listening along: the question just asked appears with answers by risk, your recent work stays on show as safe to say, and the next likely questions appear below, each with its safest answer in one line:

Listening: the question asked now with its answers, my recent work, two likely next questions and two questions asked but not prepared

While a question is open, new ones wait behind a button instead of moving the list:

A held live list: the question asked now, my recent work, a button to take three new questions and the open question that holds the list

The pictures show the 0.12 layout. Since 0.13 the question asked now is drawn as a large card at the top, and the sections below it are folded while listening.

Screenshots show a fictional pitch for a fictional company; no real meeting was recorded.

Requirements

  • Claude Code in the terminal or the desktop app, tested with version 2.1.296.
  • Wispr Flow for the full feature set. Without Wispr Flow, Great Question prepares questions from the repository, tickets and other connected sources. With Wispr Flow you also get:
  • Listening along: while a recording runs, it reads the live transcript of the Wispr Flow app (Meeting Recorder, macOS) and suggests questions from the last two minutes.
  • Meetings and transcripts during preparation: through the Wispr Flow connector in Claude Code, /great-question-prep finds the upcoming meeting with its attendees and earlier conversations with the other side.

Installation

In a Claude Code session in the terminal, enter:

/plugin install great-question --marketplace jsc2304/great-question

Confirm the marketplace question with y and choose the scope User (Enter). The mod then applies to all projects, including sessions in the desktop app.

Without a running session, use the shell:

claude plugin marketplace add jsc2304/great-question
claude plugin install great-question@great-question --scope user

Sessions that were running before the installation only see the mod after a restart.

Updating

claude plugin update great-question@great-question

Then restart the session. The loaded version is shown top right in the panel (for example v0.9.0).

Usage

CommandEffect
/great-questionopens the panel without generating anything
/great-question-prep [occasion]finds likely questions with answers in the background, for example /great-question-prep steering committee Thursday

The desktop app does not list these commands in its suggestions. Type them in full and press Enter.

With nothing prepared yet, the panel asks where to start: Likely questions about <folder>, Prepare my next meeting (the background agent finds it in your calendar) or Prepare today's daily. Or just Listen live: questions then come from the live transcript only, answers from the repository.

Sources and the sources of answers are links where they point somewhere: a URL, a GitHub issue or pull request (owner/repo#12, #12), or a repository file, which opens on GitHub at its line (docs/ops.md:12). A file path counts from the session's folder; it becomes a link only when the file exists there and its repository's default branch on GitHub has it, otherwise it stays plain text.

Buttons in the panel:

  • Listen live: checks the running Wispr Flow recording every 3 seconds and shows the question asked now as a card, UP NEXT · FOR YOU, SAFE TO SAY · MY RECENT WORK and ASKED EARLIER. While listening, the button carries the status, for example "◉ Listening · 212 utterances · 12 s ago". Switching it off only pauses.
  • Find likely questions: like /great-question-prep without an occasion. A background agent reads the repository, connected sources and the newest 12,000 characters of this session's conversation (text only, no tool output) while your session stays free; the panel shows a turning ◐ with the time taken, and the questions appear when it is done.
  • Open all and Close all: open or close every visible question. Close all shows as soon as one question is open and closes them all at once.
  • More: shows the less frequent settings and actions:
  • Language: Auto / DE / EN of questions and answers. Auto uses the language the meeting is held in (from the invitation, slides and earlier transcripts when generating, from the conversation when listening). Applies to everything generated from then on, live included; nothing already shown is translated. Notes and reasons are in English.
  • Model: who answers while listening and how hard it thinks: Fast (Haiku), Balanced (Sonnet, low effort) or Thorough (Sonnet, high effort). Applies to finding the questions asked (always with low effort), the answers from the repository and the model of the ASKED NOW lookup; the background preparation keeps the session's model. Slower levels answer later: a step still running when the next is due is skipped.
  • Sort: by answer confidence (safest to answer) or by likelihood (most likely asked).
  • Meeting / Practice: Meeting shows the strongest first, Practice turns the order round and puts the weakest questions on top.
  • Legend: what the risk marks mean.
  • Export: writes the panel as Markdown to question-sets/YYYY-MM-DD-HHMM-<title>.md in the project folder.
  • Clear (only while paused): deletes the live results.

While listening, the panel follows the questions you have to answer:

  • New lines are checked every 3 seconds. A question mark, your name, a question word at the start or a tag such as "oder?" or "right?" starts a step at once; other lines wait at most 12 seconds.
  • A step has two parts. A quick one finds which questions were asked, which one is on the table, who it is for and what comes next, and shows them at once, the new rows marked answering …. A second one then writes 2–3 answers per question, safest first. Meanwhile the next question can already be detected.
  • Every question says who it is for (you, everyone or someone else) and who asked, by role or first name as heard. Questions to someone else are listed with that mark but never take the card at the top. In a video call your voice is the microphone; your git user name helps the model spot questions addressed to you by name.
  • The question asked now gets a card: ASKED OF YOU, ASKED · EVERYONE or ASKED NOW, who asked and how long ago, the best answer with its source, one ✖ Don't say line, and the other answers behind ▸ N more answers. In the desktop app the card uses larger text; the terminal keeps one size.
  • UP NEXT · FOR YOU shows at most 3 questions likely to come next: yours first, marked · you, then by likelihood, then newest, each with its best answer in one line.
  • SAFE TO SAY · MY RECENT WORK lists what you worked on last, true whatever is asked: from the preparation (commits, pull requests, tickets or meetings, each with its source), or, when the preparation has none, your last five commits in the folder (author = your git email, merges left out).
  • Live answers come safest first. A closed question shows the one that binds you to nothing before a promise; a commitment is offered only when the question asks for a date, an owner or a scope, and never with a date or name nobody gave.

While listening, answers come from the repository too:

  • For every new question from the call, the mod searches the session's repository for its key words (git grep, exports left out). The answers are written from the lines found, the prepared questions, your recent work and the briefing (see Data and confidentiality). A SAY IT answer then names its file and line, for example docs/offer.md:42.
  • For the question asked now, unless the prepared answers already rest on sources, a read-only subagent looks it up in more depth, alongside the two parts of the step. While it runs, the card says checking the repository …; its answers then replace the quick ones, marked from the repository.
  • Only the repository is searched live. Slides in Drive, Jira and other connected sources come in through the preparation only.

While listening, the list only grows, it is never rebuilt:

  • New questions arrive closed and show their best answer in one line. A question keeps its wording even when the model rephrases it slightly.
  • Below UP NEXT, four sections are folded to one line each: SAFE TO SAY · MY RECENT WORK, ASKED EARLIER (questions from the call that were not prepared, newest first), PREPARED (the prepared questions, grouped as before, with the sort order in its title) and SOURCES. A press on a section title unfolds it. Paused, PREPARED and SAFE TO SAY stand open.
  • An asked question stays in place, marked ✓. Only when paused does it move to ALREADY ASKED.
  • While a question is open, the live sections stand still. New ones collect behind ↻ take N new in the title row of UP NEXT and arrive by themselves once all questions are closed. The card for the question asked now always stays live.

What gets prepared depends on the project: with slides, a pitch preparation or a meeting at hand it prepares the meeting; otherwise the daily stand-up from commits, pull requests and open tickets.

Data and confidentiality

  • Record only with consent. Wispr Flow records through this computer's microphone and system audio; no bot appears in the video call, so the others cannot see that it is being transcribed. Get the consent of everyone in the meeting before recording. In Germany, recording the privately spoken word without consent is a criminal offence (§ 201 StGB).
  • Transcription by Wispr Flow. Recording happens locally, transcription happens in Wispr Flow's cloud (Wispr: on-device recording, as of 14.10.2026). Great Question reads the finished transcript from the Wispr Flow app's local file.
  • Prepared questions are stored locally per project folder. They stay on the computer. A new session does not reopen them by itself: the panel asks first whether to show them, prepare new ones or listen live.
  • Listening along sends the last two minutes of the transcript, the prepared questions, the repository lines found for new questions, your git user name, your last five commit subjects and a briefing from the folder to a Claude model through the same access as the session: Haiku by default, Sonnet when chosen under More → Model. The briefing holds, when they exist, the sections "Status", "Offene Fäden" and "Tickets" of the project's Second Brain hub (~/projects/second-brain/projects/<repo>/<repo>.md, 8,000 characters, first; it wins on a ticket's state), the first 6,000 characters of memory/MEMORY.md, the two newest files in memory/daily-logs/ (3,000 characters each) and the last 15 commit subjects, at most 24,000 characters, re-read at most once a minute. A lookup for the question asked now runs as a read-only subagent with the same model in the session's folder. Speaker names from Wispr Flow are not sent; names mentioned in the conversation are in the text.
  • Training data, only when you ask for it. If the folder ~/.claude/great-question/labels/ exists, listening appends every step's decisions to <day>.jsonl in it: the two-minute transcript excerpt, your git user name, the questions listed at that moment and what the model decided (which questions were asked, whom they were for, what comes next). The rows are meant for training a local decision model and stay on the computer. Without the folder nothing is written; delete it to stop.
  • Exports with live results contain questions from the conversation, names included. In projects with confidential content, add question-sets/ to .gitignore or review it before committing.

Development

Check:

claude plugin validate .
claude plugin test .

A change reaches running sessions only with a release, since the mod installs from this repository on GitHub: raise version in .claude-plugin/plugin.json and add the CHANGELOG.md section in the same pull request, merge, tag vX.Y.Z, then run claude plugin marketplace update great-question and claude plugin update great-question@great-question and restart the session. The desktop app loads the mod from the plugin cache, not from the working folder, so unmerged work never reaches it; test it with claude plugin test ..

Measure the live step before and after a prompt or model change. The script runs detectTask from hooks/live.ts through the engine (claude -p with the small plugin in scripts/bench/plugin) on hand-checked transcript excerpts and reports how often the model names the right addressee, and how long a call takes. The excerpts are meeting content and stay outside the repository: label rows in ~/.claude/great-question/labels/backfill.jsonl, hand labels in ~/.claude/great-question/laya/eval.json ({"rows": [{"i": <row>, "a": "me"|"all"|"other"|"none"}]}).

node --no-warnings scripts/bench/bench.ts haiku,sonnet 3

Measure through the engine, not with claude -p --model: the CLI thinks differently and reported Haiku at 11 s per call where the engine took 7 s (23.10.2026).

FileContents
hooks/register.tsxcommands, the question-set tool, panel, export
hooks/live.tslistening along: read the transcript, fold in the model's reply
types/index.d.tsdata types and the panel's state
tests/tests for panel, export and listening along
scripts/bench/measures the live step on hand-checked excerpts

Feedback

Questions, ideas and meeting stories go to Discussions; bugs to Issues. If Great Question saved you in a meeting, a star helps others find it.

License

MIT, see LICENSE.

Source 3 files
hooks/register.tsx 1336 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { Addressee, Answer, Fact, Lang, Quality, Live, Question, QuestionSet, Risk, Source, SourceKind } from '../types'
5import {
6  GROUND_SYSTEM,
7  IDLE,
8  SYSTEM,
9  applyAnswers,
10  applyReply,
11  asText,
12  detectTask,
13  githubBase,
14  grepArgs,
15  ground,
16  isTrigger,
17  labelOf,
18  knowledge,
19  languageRule,
20  logArgs,
21  lookupPrompt,
22  parseIdent,
23  parseLog,
24  parseTranscript,
25  recentOf,
26  rowKey,
27  parseSource,
28  settleLookup,
29  toAnswers,
30  topHits,
31  withRisks,
32} from './live'
33
34const PANE = 'great-question'
35const TOOL = 'mcp__great-question__show_questions'
36const current = atom({ plugin: 'great-question', key: 'set' } as const, null)
37// Keyed by question text, so a row keeps its state while predictions and groups reshuffle around it.
38const opened = atom({ plugin: 'great-question', key: 'open' } as const, [])
39// While a row is open the live sections stand still; new rows wait behind the "take new" button.
40const held = atom({ plugin: 'great-question', key: 'held' } as const, null)
41const more = atom({ plugin: 'great-question', key: 'more' } as const, false)
42// A background agent is finding likely questions: since when, for which occasion. `tick` drives its spinner.
43const preparing = atom({ plugin: 'great-question', key: 'preparing' } as const, null)
44const tick = atom({ plugin: 'great-question', key: 'tick' } as const, 0)
45// Where sources point, by label, worked out with git when questions arrive; '' for nowhere. Read while drawing.
46const links = atom({ plugin: 'great-question', key: 'links' } as const, {})
47// meeting: surest answers first, to answer from; practice: weakest first, to practise.
48const view = atom({ plugin: 'great-question', key: 'view' } as const, 'meeting')
49const live = atom({ plugin: 'great-question', key: 'live' } as const, IDLE)
50// confidence: grouped by answer confidence; likelihood: grouped by how likely the question comes. Relevance leads inside a group.
51const sortBy = atom({ plugin: 'great-question', key: 'sortBy' } as const, 'confidence')
52// Language of new questions and answers; nothing already shown is translated.
53const lang = atom({ plugin: 'great-question', key: 'lang' } as const, 'auto')
54const LANGS: Lang[] = ['auto', 'de', 'en']
55const version = atom({ plugin: 'great-question', key: 'version' } as const, '')
56// The set a fresh session finds stored for its folder: offered on the start screen, not shown until asked for.
57const previous = atom({ plugin: 'great-question', key: 'previous' } as const, null)
58// Sections folded the other way round from their default; see `isUnfolded` in the pane.
59const toggled = atom({ plugin: 'great-question', key: 'toggled' } as const, [])
60
61// How often listening looks at the transcript; Wispr writes a line about a second after it was said.
62const TICK_MS = 3_000
63// New lines without a question mark, my name or a question's opening wait this long for a model step.
64const STEP_MS = 12_000
65const LINK_MS = 20_000
66const BRIEF_MS = 60_000
67// A step whose model call failed waits this long before the same lines try again.
68const RETRY_MS = 6_000
69// A recording counts as running while Wispr wrote its live transcript this recently.
70const FRESH_MS = 3 * 60_000
71const quality = atom({ plugin: 'great-question', key: 'quality' } as const, 'fast')
72// Who answers live and how hard it thinks. A slower level answers later: a step still running when the next is due skips it.
73// A completion has no time limit of its own: one that never answered held the listening step, and every later one, for good.
74const QUALITY: Record<Quality, { label: string; model: string; effort?: 'low' | 'high'; timeoutMs: number }> = {
75  fast: { label: 'Fast (Haiku)', model: 'haiku', effort: 'low', timeoutMs: 30_000 },
76  balanced: { label: 'Balanced (Sonnet, low)', model: 'sonnet', effort: 'low', timeoutMs: 45_000 },
77  thorough: { label: 'Thorough (Sonnet, high)', model: 'sonnet', effort: 'high', timeoutMs: 90_000 },
78}
79const QUALITIES = Object.keys(QUALITY) as Quality[]
80// Reads that come from an older version or a hand edit fall back to the fast level.
81const levelOf = async ($: EngineInterface) => QUALITY[await read($, quality)] ?? QUALITY.fast
82
83// Display order: safest first, so the answer to give leads and the warning closes. A thin answer that binds us to
84// nothing comes before a promise: a closed row's one-line answer is never a commitment while a safer one exists.
85// `action` says what to do with the answer in the room; `label` is the risk class.
86const RISKS: Record<Risk, { mark: string; label: string; action: string; color: string }> = {
87  sourced: { mark: '●', label: 'sourced', action: 'SAY IT', color: 'success' },
88  vague: { mark: '○', label: 'vague', action: 'WEAK', color: 'inactive' },
89  commitment: { mark: '▲', label: 'commitment', action: 'ONLY IF COVERED', color: 'warning' },
90  risky: { mark: '✖', label: 'risky', action: "DON'T SAY", color: 'error' },
91}
92const ORDER = Object.keys(RISKS) as Risk[]
93// The card's label by who the question is for; unknown reads ASKED NOW.
94const TO: Record<Addressee, string> = { me: 'ASKED OF YOU', all: 'ASKED · EVERYONE', other: 'ASKED · SOMEONE ELSE' }
95// UP NEXT draws this many; more would bury the next one.
96const MAX_SHOWN_NEXT = 3
97
98// Grouped by answer confidence, surest first; relevance breaks ties.
99const GROUPS = [
100  { label: 'Safe to answer', min: 5 },
101  { label: 'Well sourced', min: 4 },
102  { label: 'Partly sourced', min: 3 },
103  { label: 'Unsure', min: 1 },
104]
105
106// Sets stored before `confidence` existed: a sourced answer counts as well covered.
107const LIKELY_GROUPS = [
108  { label: 'Very likely', min: 5 },
109  { label: 'Likely', min: 4 },
110  { label: 'Possible', min: 3 },
111  { label: 'Rather rare', min: 1 },
112]
113
114const confidenceOf = (q: Question) => q.confidence ?? (q.answers.some(a => a.risk === 'sourced') ? 4 : 2)
115const bySurest = (a: Question, b: Question) => confidenceOf(b) - confidenceOf(a) || b.relevance - a.relevance
116
117const SCHEMA = {
118  type: 'object',
119  required: ['title', 'mode', 'questions'],
120  properties: {
121    title: { type: 'string', description: 'Occasion, e.g. "Customer pitch, 14.10." or "Daily 13.10."' },
122    language: { type: 'string', enum: ['de', 'en'], description: 'Language the questions and answers are written in' },
123    mode: { type: 'string', enum: ['pitch', 'meeting', 'standup'] },
124    sources: {
125      type: 'array',
126      description: 'Sources read, each with its origin',
127      items: {
128        type: 'object',
129        required: ['kind', 'label'],
130        properties: {
131          kind: {
132            type: 'string',
133            enum: ['meeting', 'repo', 'ticket', 'doc', 'calendar', 'other'],
134            description: 'meeting: meeting notes and transcripts; repo: files in the repository; ticket: issues, pull requests, Jira; doc: documents outside the repository (Drive, offer, mail); calendar: appointments; other: the rest',
135          },
136          label: { type: 'string', description: 'What exactly, e.g. file path, meeting with date, ticket number' },
137        },
138      },
139    },
140    recent: {
141      type: 'array',
142      description: 'What I (the person preparing) worked on most recently, newest first: each one sentence that is certainly true and can be said in any meeting',
143      items: {
144        type: 'object',
145        required: ['text', 'source'],
146        properties: {
147          text: { type: 'string' },
148          source: { type: 'string', description: 'The commit, pull request, ticket or meeting with date that shows it' },
149        },
150      },
151    },
152    questions: {
153      type: 'array',
154      items: {
155        type: 'object',
156        required: ['question', 'relevance', 'confidence', 'answers'],
157        properties: {
158          question: { type: 'string' },
159          relevance: { type: 'integer', minimum: 1, maximum: 5, description: 'Likelihood × weight, 5 = highest' },
160          confidence: {
161            type: 'integer',
162            minimum: 1,
163            maximum: 5,
164            description: 'Answer confidence: how well the documents support a sourced answer; 5 = firm, sourced answer, 1 = no reliable answer',
165          },
166          who: { type: 'string', description: 'Who on the other side is likely to ask, as a role without names' },
167          why: { type: 'string', description: 'Why we expect the question: trigger or evidence (slide, gap, objection, earlier meeting)' },
168          answerer: {
169            type: 'string',
170            description: 'Who on our side answers, per briefing, speaker plan or responsibility; leave out when the documents name nobody',
171          },
172          answers: {
173            type: 'array',
174            items: {
175              type: 'object',
176              required: ['text', 'risk'],
177              properties: {
178                text: { type: 'string' },
179                risk: { type: 'string', enum: ['sourced', 'vague', 'commitment', 'risky'] },
180                note: { type: 'string', description: 'What to watch out for' },
181                source: { type: 'string', description: 'Evidence (slide, document, figure)' },
182              },
183            },
184          },
185        },
186      },
187    },
188  },
189}
190
191// How the prepared questions come back: from a background agent as its reply, from the session through the tool.
192const REPLY_AS_JSON = `Reply with one JSON object only, no text before or after it, in this shape (JSON Schema): ${JSON.stringify(SCHEMA)}`
193const CALL_THE_TOOL = `Load the tool ${TOOL} with ToolSearch and call it with the result. Afterwards, only one line in the chat.`
194
195// How much of the session's conversation the background agent gets, newest kept.
196const CONVERSATION_CHARS = 12_000
197
198/** The session's conversation as plain text, newest last, cut from the front to `max` characters; tool calls left out. */
199export const conversationOf = (messages: { role: string; text: string }[], max = CONVERSATION_CHARS) => {
200  const text = messages
201    .filter(m => m.text.trim())
202    .map(m => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.text.trim()}`)
203    .join('\n\n')
204  return text.length > max ? `…${text.slice(-max)}` : text
205}
206
207const prepPrompt = (occasion: string, language: Lang, finish: string, conversation = '') => `Great Question: find the likely questions${occasion ? ` for: ${occasion}` : ''}.
208${conversation ? `\nThe session's conversation so far (user and assistant text, tool calls left out, oldest part cut). It is context like the other sources: what was worked out here (estimates, decisions, open points) may come up; name it as source "this session's conversation".\n<conversation>\n${conversation}\n</conversation>\n` : ''}
209Language: ${language === 'auto' ? 'Write "question" and the answer "text"s in the language the meeting is held in (invitation, slides, earlier transcripts with the other side); if unsure, German.' : languageRule(language)} who, why, answerer, note and title in English. Return the language used as "language".
210
2111. Choose the mode. Is a pitch, presentation or meeting coming up (slides, pitch preparation, agenda, calendar entry, occasion above)? Then "pitch" or "meeting". Otherwise "standup": daily stand-up preparation from the commits and pull requests of the last working days, open and own issues/tickets, blockers.
2122. Gather context, only from sources you read in this session: README, slides and speaker notes, Q&A/FAQ preparation, offer, decisions, open risks, issues; connected sources (Jira, Drive) where they fit the occasion. Project rules (AGENTS.md, CLAUDE.md) apply.
213   Meeting transcripts from Wispr Flow, if connected: find matching meetings with search_meetings (title, attendees, period; the search only matches title and summary, not the transcript), then read get_meeting with view_transcript, not just the notes. What matters: earlier meetings with the other side (which questions and objections came up, what was promised) and internal preparation rounds (open points, agreements). Find the upcoming meeting and its attendees with list_upcoming_meetings. For "standup", the meetings since the last working day. If the other side asked a question before, its relevance rises; name the meeting and date in why.
2143. 8 to 15 questions the other side is most likely to ask, with relevance 1 to 5 (likelihood × weight) and confidence 1 to 5 (how well our documents support a sourced answer; 5 = firm, sourced answer, 1 = no reliable answer, open points lower it). Per question: who (who on the other side asks, as a role, no names of customer people), why (why we expect the question), answerer (who on our side answers, only when a briefing, speaker plan or responsibility names them), 2 to 4 answer options, each with a risk:
215   - sourced: well founded, source in "source" (slide, document, figure); low risk
216   - vague: harmless and shallow; low risk, but weak
217   - commitment: binds us (date, price, scope, people); only when the documents cover it
218   - risky: unsupported, contradicts the documents or is attackable; as a warning of what not to say
219   Optional "note": what to watch out for.
2204. "recent": 3 to 6 things I (the person preparing: the git user, my own tickets) did most recently, newest first, in the language of the answers. Each one sentence I can say in any meeting whatever is asked, and certainly true: only what a commit, pull request, ticket or meeting you read shows, with it as "source".
2215. ${finish}`
222
223const storeKey = async ($: EngineInterface) => `set:${await $.session.cwd()}`
224
225/** The set stored for a folder, in today's shape; sets from before 0.10 carry no folder: the one they are stored under is it. */
226const storedSet = async ($: EngineInterface, folder: string) => {
227  const saved = (await $.store.get(`set:${folder}`)) as QuestionSet | undefined
228  return saved && toSet(saved as unknown as Record<string, unknown>, saved.generatedAt, saved.folder ?? folder)
229}
230
231/** One git command's output, trimmed; null when git says no. A command that cannot run at all throws. */
232const git = async ($: EngineInterface, args: readonly string[], cwd: string) => {
233  const ran = await $.process.run(['git', ...args], { cwd, timeoutMs: 5000 })
234  return ran.exitCode === 0 ? ran.stdout.trim() : null
235}
236
237/**
238 * A source's https address: a URL as is, an issue, or a file that exists here and in its repository's default branch
239 * on GitHub, at its line. A label's path is relative to the session's folder, which need not be a repository's root.
240 */
241const resolveLink = async ($: EngineInterface, label: string, cwd: string): Promise<string | null> => {
242  const ref = parseSource(label)
243  if (!ref) return null
244  if ('url' in ref) return ref.url
245  if ('repo' in ref) return `https://github.com/${ref.repo}/issues/${ref.issue}`
246  if ('issue' in ref) {
247    const base = githubBase(await git($, ['remote', 'get-url', 'origin'], cwd))
248    return base && `${base}/issues/${ref.issue}`
249  }
250  const abs = ref.path.startsWith('/') ? ref.path : `${cwd}/${ref.path}`
251  if (!(await $.fs.exists(abs))) return null
252  const root = await git($, ['rev-parse', '--show-toplevel'], abs.slice(0, abs.lastIndexOf('/')))
253  if (!root || !abs.startsWith(`${root}/`)) return null
254  const base = githubBase(await git($, ['remote', 'get-url', 'origin'], root))
255  if (!base) return null
256  const rel = abs.slice(root.length + 1)
257  // Only a file the remote has: one that exists just locally, or on a local branch, would 404 on GitHub.
258  for (const ref_ of ['origin/HEAD', 'origin/main', 'origin/master']) {
259    if ((await git($, ['cat-file', '-e', `${ref_}:${rel}`], root)) !== null) return `${base}/blob/HEAD/${rel}${ref.line ? `#L${ref.line}` : ''}`
260  }
261  return null
262}
263
264// Labels being resolved now, so a redraw does not start them twice; whether a failure was reported this session.
265const resolving = new Set<string>()
266let isFailureLogged = false
267
268/**
269 * Works out the links of labels not seen yet and keeps them, so drawing only looks them up. A label whose lookup
270 * failed (git could not run) is not kept, so the next drawing tries again.
271 */
272const linkAll = async ($: EngineInterface, labels: readonly (string | undefined)[], folder?: string) => {
273  // Paths count from the folder the questions were prepared in: the session's own moves with its shell.
274  const cwd = folder ?? (await $.session.cwd())
275  const known = await read($, links)
276  const fresh = [...new Set(labels.filter((l): l is string => !!l))].filter(l => !(l in known) && !resolving.has(l))
277  if (!fresh.length) return
278  fresh.forEach(l => resolving.add(l))
279  const found: [string, string][] = []
280  for (const l of fresh) {
281    try {
282      found.push([l, (await resolveLink($, l, cwd)) ?? ''])
283    } catch (err) {
284      if (!isFailureLogged) $.ui.log(`Great Question: could not resolve source links: ${String(err).slice(0, 200)}`)
285      isFailureLogged = true
286    } finally {
287      resolving.delete(l)
288    }
289  }
290  if (found.length) await update($, links, k => ({ ...k, ...Object.fromEntries(found) }))
291}
292
293const answerSources = (questions: readonly Question[]) => questions.flatMap(q => q.answers.map(a => a.source))
294const setLabels = (set: QuestionSet) => [...set.sources.map(src => asSource(src).label), ...answerSources(set.questions), ...(set.recent ?? []).map(f => f.source)]
295
296/** Links for every source the pane can show that has none yet. Runs from a timer: drawing may not write state. */
297const linkPending = async ($: EngineInterface) => {
298  const stored = await read($, current)
299  const ear = { ...IDLE, ...(await read($, live)) }
300  if (stored) await linkAll($, setLabels(stored), stored.folder)
301  await linkAll($, [...answerSources([...ear.added, ...ear.next]), ...Object.values(ear.deep ?? {}).flatMap(list => list.map(a => a.source))])
302}
303
304// The background agent finding likely questions, and the spinner's clock while it runs.
305let prepAgent: string | null = null
306let stopTick: { cancel: () => void } | null = null
307
308/**
309 * Finds likely questions in a background agent, so the session stays free; without one, the session does it as before.
310 * `label` names the occasion in the spinner when `occasion` is a whole brief.
311 */
312const startPrep = async ($: EngineInterface, occasion: string, label = occasion) => {
313  if (await read($, preparing)) {
314    $.ui.toast('Great Question: already finding likely questions …')
315    return
316  }
317  const language = await read($, lang)
318  const cwd = await $.session.cwd()
319  // The agent starts fresh; the fallback below runs in the session and sees the conversation itself.
320  const conversation = conversationOf(await $.session.messages().catch(() => []))
321  const spawned = await $.agent
322    .spawn({ prompt: prepPrompt(occasion.trim(), language, REPLY_AS_JSON, conversation), description: 'Great Question: finding likely questions', subagentType: 'general-purpose' })
323    .catch(() => null)
324  if (!spawned || !('agentId' in spawned) || !spawned.agentId) {
325    void $.prompt.submit({ text: prepPrompt(occasion.trim(), language, CALL_THE_TOOL) })
326    $.ui.toast('Great Question: finding likely questions …')
327    return
328  }
329  prepAgent = spawned.agentId
330  ours.add(spawned.agentId)
331  const since = await $.clock.now()
332  await update($, preparing, () => ({ since, occasion: label.trim(), folder: cwd }))
333  stopTick?.cancel()
334  stopTick = $.clock.every(1000, () => void update($, tick, t => t + 1))
335  $.ui.toast('Great Question: finding likely questions in the background …')
336}
337
338/** The prepared questions from a background agent's reply; null when it is not the asked-for JSON or holds none. */
339export const fromReply = (reply: string, generatedAt: string, folder?: string): QuestionSet | null => {
340  try {
341    const set = toSet(JSON.parse(reply.slice(reply.indexOf('{'), reply.lastIndexOf('}') + 1)) as Record<string, unknown>, generatedAt, folder)
342    return set.questions.length ? set : null
343  } catch {
344    return null
345  }
346}
347
348/** Shows the set a fresh session found stored, every row closed; nothing happens when it has gone. */
349const showPrevious = async ($: EngineInterface) => {
350  const found = await read($, previous)
351  const set = found && (await storedSet($, found.folder))
352  if (!set) return
353  await update($, current, () => set)
354  await setOpen($, () => [])
355  await linkAll($, setLabels(set), set.folder)
356}
357
358/** Stores prepared questions for this folder and shows them, the surest one open. */
359const showSet = async ($: EngineInterface, set: QuestionSet) => {
360  // Under the folder they were prepared in, which the session may have moved away from since.
361  await $.store.set(set.folder ? `set:${set.folder}` : await storeKey($), set)
362  await update($, current, () => set)
363  await update($, held, () => null)
364  await setOpen($, () => [set.questions[0]!.question])
365  await linkAll($, setLabels(set), set.folder)
366  await $.ui.open({ id: PANE, title: 'Great Question' })
367}
368
369const SOURCE_KINDS: Record<SourceKind, string> = {
370  meeting: 'Meetings & transcripts',
371  repo: 'Repository',
372  ticket: 'Issues & tickets',
373  doc: 'Documents',
374  calendar: 'Calendar',
375  other: 'Other',
376}
377
378// ponytail: keyword guess for plain-string sources (old sets, or a model that skips `kind`)
379const guessKind = (label: string): SourceKind =>
380  /wispr|transkript|meeting|termin \d|rehe?arsal/i.test(label) ? 'meeting'
381  : /kalender|calendar/i.test(label) ? 'calendar'
382  : /decision|issue|#\d|jira|pull request/i.test(label) ? 'ticket'
383  : /\.(md|html?|pdf|json|ts|tsx|py)\b|\//.test(label) ? 'repo'
384  : /drive|angebot|anhang|mail|rfp/i.test(label) ? 'doc'
385  : 'other'
386
387// Source kinds as stored by 0.8 and earlier.
388const OLD_KINDS: Record<string, SourceKind> = { kalender: 'calendar', andere: 'other' }
389
390const asSource = (src: unknown): Source =>
391  typeof src === 'object' && src !== null && 'label' in src
392    ? {
393        kind: (src as Source).kind in SOURCE_KINDS ? (src as Source).kind : (OLD_KINDS[String((src as Source).kind)] ?? guessKind(String((src as Source).label))),
394        label: String((src as Source).label),
395      }
396    : { kind: guessKind(String(src)), label: String(src) }
397
398const clamp = (n: unknown) => Math.min(5, Math.max(1, Math.round(Number(n) || 1)))
399
400const stamp = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace('T', ' ')
401
402const toSet = (input: Record<string, unknown>, generatedAt: string, folder?: string): QuestionSet => {
403  const raw = Array.isArray(input.questions) ? (input.questions as Question[]) : []
404  const questions = raw
405    .filter(q => typeof q?.question === 'string')
406    .map(q => ({
407      ...q,
408      who: asText(q.who),
409      why: asText(q.why),
410      answerer: asText(q.answerer),
411      relevance: clamp(q.relevance),
412      confidence: q.confidence === undefined ? undefined : clamp(q.confidence),
413      answers: toAnswers(q.answers),
414    }))
415    .sort(bySurest)
416
417  return {
418    title: String(input.title ?? 'Question set'),
419    language: input.language === 'en' || input.language === 'de' ? input.language : undefined,
420    mode: String(input.mode ?? ''),
421    generatedAt,
422    sources: Array.isArray(input.sources) ? input.sources.map(asSource) : [],
423    questions,
424    folder: folder ?? (typeof input.folder === 'string' ? input.folder : undefined),
425    recent: Array.isArray(input.recent)
426      ? (input.recent as Fact[]).filter(f => typeof f?.text === 'string').map(f => ({ text: f.text, source: asText(f.source) }))
427      : undefined,
428  }
429}
430
431/** Opening the first row freezes the live sections as they stand; closing the last lets them run again. */
432const setOpen = async ($: EngineInterface, change: (list: string[]) => string[]) => {
433  const list = await update($, opened, change)
434  const { next, added } = { ...IDLE, ...(await read($, live)) }
435  await update($, held, h => (list.length ? (h ?? { next, added }) : null))
436}
437
438const age = (ms: number) => (ms < 90_000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60_000)} min`)
439
440/** The Wispr recording whose live transcript changed last, with when it changed, if that was within FRESH_MS. */
441const runningRecording = async ($: EngineInterface, now: number) => {
442  const root = `${await $.env.get('HOME')}/Library/Application Support/Wispr Flow/meetings`
443  let best: { path: string; mtimeMs: number } | null = null
444  for (const entry of await $.fs.list(root)) {
445    if (entry.kind !== 'dir' || entry.name.startsWith('.')) continue
446    const path = `${root}/${entry.name}/live.ndjson`
447    if (!(await $.fs.exists(path))) continue
448    const { mtimeMs } = await $.fs.stat(path)
449    if (!best || mtimeMs > best.mtimeMs) best = { path, mtimeMs }
450  }
451
452  return best && now - best.mtimeMs < FRESH_MS ? best : null
453}
454
455// The transcript as last read: read again only when its file changed.
456let heard: { path: string; mtimeMs: number; text: string } | null = null
457
458/** The running recording's transcript; an unchanged file is not read again. */
459const transcript = async ($: EngineInterface, path: string, mtimeMs: number) => {
460  if (heard?.path !== path || heard.mtimeMs !== mtimeMs) heard = { path, mtimeMs, text: (await $.fs.read(path)) as string }
461  return heard.text
462}
463
464// What the repository says is current, by folder, read at most once a minute.
465let briefed: { folder: string; at: number; text: string } | null = null
466
467/**
468 * The repository's Second Brain hub (status, open threads, tickets), then the folder's memory file, its two newest daily
469 * logs and its last commits, newest first; nothing where they are missing.
470 */
471const readBriefing = async ($: EngineInterface, folder: string, now: number) => {
472  if (briefed?.folder === folder && now - briefed.at < BRIEF_MS) return briefed.text
473  const head = async (path: string, max: number) =>
474    (await $.fs.exists(path).catch(() => false)) ? String((await $.fs.read(path).catch(() => '')) ?? '').slice(0, max) : ''
475  // The hub is named after the main checkout's folder, so a worktree finds the same one.
476  const common = await git($, ['rev-parse', '--path-format=absolute', '--git-common-dir'], folder).catch(() => null)
477  const repo = (common?.replace(/\/\.git$/, '') ?? folder).split('/').pop()
478  const hub = (await head(`${await $.env.get('HOME')}/projects/second-brain/projects/${repo}/${repo}.md`, 200_000))
479    .split(/^(?=## )/m)
480    .filter(s => /^## (Status|Offene Fäden|Tickets)\b/.test(s))
481    .join('')
482  const logs = `${folder}/memory/daily-logs`
483  // Dated names sort by day; a README beside them is no log.
484  const days = (await $.fs.exists(logs).catch(() => false))
485    ? (await $.fs.list(logs).catch(() => [])).filter(e => e.kind === 'file' && /^\d/.test(e.name)).map(e => e.name).sort().reverse().slice(0, 2)
486    : []
487  const parts: [string, string][] = [
488    ['Second Brain hub (it wins where others disagree on a ticket\'s state)', hub.slice(0, 8_000)],
489    ['memory/MEMORY.md', await head(`${folder}/memory/MEMORY.md`, 6_000)],
490    ...(await Promise.all(days.map(async d => [`memory/daily-logs/${d}`, await head(`${logs}/${d}`, 3_000)] as [string, string]))),
491    ['git log --oneline -15', (await git($, ['log', '--oneline', '-15'], folder).catch(() => null)) ?? ''],
492  ]
493  const text = parts.filter(([, t]) => t.trim()).map(([label, t]) => `${label}:\n${t.trim()}`).join('\n\n').slice(0, 24_000)
494  briefed = { folder, at: now, text }
495  return text
496}
497
498/** Lines in the session's repository that carry a question's words; none outside a git repository. */
499const repoHits = async ($: EngineInterface, terms: readonly string[]) => {
500  const { exitCode, stdout } = await $.process.run(grepArgs(terms), { timeoutMs: 5000 }).catch(() => ({ exitCode: 2, stdout: '' }))
501  return exitCode === 0 ? topHits(stdout, terms) : []
502}
503
504/** My name and latest commits in the folder the questions are about; nothing outside a git repository. */
505const myWork = async ($: EngineInterface, cwd: string) => {
506  try {
507    const me = parseIdent(await git($, ['var', 'GIT_AUTHOR_IDENT'], cwd))
508    return { name: me?.name ?? '', recent: me ? parseLog(await git($, logArgs(me.email), cwd)) : [] }
509  } catch {
510    return { name: '', recent: [] }
511  }
512}
513
514// My work by folder, asked of git at most once a minute: ticks with waiting lines need my name every 3 s.
515let worked: { folder: string; at: number; me: Awaited<ReturnType<typeof myWork>> } | null = null
516
517const myWorkNow = async ($: EngineInterface, folder: string, now: number) => {
518  if (worked?.folder !== folder || now - worked.at >= BRIEF_MS) worked = { folder, at: now, me: await myWork($, folder) }
519  return worked.me
520}
521
522// Questions whose answers are being written now: a later step leaves them to the call already under way.
523const answering = new Set<string>()
524// A failed model step holds the next one off until then, so a trigger in the unread lines cannot fire every tick.
525let retryAt = 0
526
527// Repository lookups by subagent: agent id to the question it looks up. A notification of one of them is dropped.
528const lookups = new Map<string, string>()
529const ours = new Set<string>()
530
531/** Starts a read-only subagent on the question asked now, unless the prepared answers already rest on sources. */
532const lookUp = async ($: EngineInterface, question: string, set: QuestionSet | null, ear: Live) => {
533  const prepared = set?.questions.find(q => q.question === question)
534  if (prepared && confidenceOf(prepared) >= 4) return
535  if (ear.looking.includes(question) || ear.deep[question]) return
536  // ponytail: spawn takes a model but no effort; a registered agent type per level if the lookup needs more thought
537  const { model } = await levelOf($)
538  const spawned = await $.agent
539    .spawn({ prompt: lookupPrompt(question, await read($, lang)), description: 'Great Question: repository lookup', subagentType: 'Explore', model })
540    .catch(() => null)
541  if (!spawned || !('agentId' in spawned) || !spawned.agentId) return
542  lookups.set(spawned.agentId, question)
543  ours.add(spawned.agentId)
544  await update($, live, l => ({ ...l, looking: [...l.looking, question] }))
545}
546
547// The detect call running now and the lines it read. A question heard while it runs cuts it, so the step starts over
548// with the newer lines; the restarted step runs to its end, so a lively meeting cannot cut every step.
549let detecting: { controller: AbortController; path: string; lines: number; names: string[]; isCuttable: boolean } | null = null
550let isRestart = false
551
552/** On a tick while a step runs: cut its detect call when lines written since hold something worth a step. */
553const cutForNewLines = async ($: EngineInterface) => {
554  const step = detecting
555  if (!step?.isCuttable) return
556  const recording = await runningRecording($, await $.clock.now())
557  if (recording?.path !== step.path) return
558  const { fresh } = parseTranscript(await transcript($, step.path, recording.mtimeMs), step.lines)
559  if (fresh.length && isTrigger(fresh, step.names) && detecting === step) step.controller.abort()
560}
561
562/**
563 * Appends a detect step's decisions to `~/.claude/great-question/labels/<day>.jsonl`, training data for a local decision
564 * model. Only where that folder exists: the rows hold the meeting's words, so nobody gets them without asking.
565 */
566const saveLabel = async ($: EngineInterface, label: ReturnType<typeof labelOf>) => {
567  const dir = `${await $.env.get('HOME')}/.claude/great-question/labels`
568  if (!(await $.fs.exists(dir))) return
569  await $.process.run(['sh', '-c', 'cat >> "$1"', 'sh', `${dir}/${label.at.slice(0, 10)}.jsonl`], { stdin: `${JSON.stringify(label)}\n`, timeoutMs: 5000 })
570}
571
572/**
573 * One listening tick:read the transcript when it changed and, when the new lines may hold a question (or have waited
574 * STEP_MS), run a step. A step first lets a small model find who asks what (DETECT) and paints that, then writes the
575 * answers for every question still waiting (ANSWER) while a subagent looks up the question asked now.
576 */
577const listen = async ($: EngineInterface) => {
578  const state = { ...IDLE, ...(await read($, live)) }
579  const set = await read($, current)
580  if (!state.isOn) return
581  const now = await $.clock.now()
582  const recording = await runningRecording($, now)
583  if (!recording) {
584    await update($, live, l => ({ ...l, status: 'no running Wispr recording found' }))
585    return
586  }
587  const { path, mtimeMs } = recording
588  const base = state.meeting === path ? state : { ...IDLE, isOn: true, meeting: path }
589  const { lines: total, tail, fresh } = parseTranscript(await transcript($, path, mtimeMs), base.lines)
590  // The file's time is when the last line was written; written every tick, so the age stays true while nobody speaks.
591  const reading = (l: Live) => {
592    const left = l.pending.filter(q => !answering.has(q)).length
593    return `listening · ${total} utterances · last utterance ${age(now - mtimeMs)} ago${left ? ` · ${left} unanswered` : ''}`
594  }
595  const folder = set?.folder ?? (await $.session.cwd())
596  const me = fresh.length ? await myWorkNow($, folder, now) : { name: '', recent: [] }
597  const names = me.name.split(/\s+/).filter(n => n.length >= 3)
598  if (!fresh.length || now < retryAt || !(isTrigger(fresh, names) || now - base.steppedAt >= STEP_MS)) {
599    await update($, live, l => (l.isOn ? { ...l, changedAt: mtimeMs, status: reading(l), phase: l.phase === 'idle' ? 'listening' : l.phase } : l))
600    return
601  }
602
603  await update($, live, l => (l.isOn ? { ...l, phase: 'detecting' } : l))
604  const language = await read($, lang)
605  // The same opening for both calls, so the second reads it from the cache.
606  // ponytail: the whole two-minute tail every step; only the marked lines plus a summary if the cost shows
607  const known = knowledge(set, { ...base, recent: me.recent }, await readBriefing($, folder, now))
608  const controller = new AbortController()
609  detecting = { controller, path, lines: total, names, isCuttable: !isRestart }
610  isRestart = false
611  const reply = await $.model.complete(
612    {
613      // The level's model, always thinking little: on 82 checked excerpts (23.10.2026) Haiku and Sonnet decided equally
614      // well, Sonnet in about 4.2 s against 7.3 s (median).
615      model: (await levelOf($)).model,
616      effort: 'low',
617      system: SYSTEM,
618      prompt: [{ text: known, cache: true }, { text: detectTask(tail, language, me.name) }],
619      // Thinking counts against the cap: room for a short think and the JSON.
620      maxTokens: 1200,
621      timeoutMs: 15_000,
622    },
623    { signal: controller.signal },
624  )
625  detecting = null
626  // Cut for a question heard meanwhile: the lines stay unread and the next tick steps over them all at once.
627  if (controller.signal.aborted) {
628    isRestart = true
629    await update($, live, l => (l.isOn ? { ...l, status: 'new lines heard; reading again', phase: l.pending.length ? 'answering' : 'listening' } : l))
630    return
631  }
632  const text = reply.isAnswered ? reply.text : ''
633  const applied = reply.isAnswered ? applyReply(base, set, text, now, fresh) : base
634  // No answer, or not the asked-for JSON: the lines stay unread, so a step after RETRY_MS tries them again.
635  if (applied === base) {
636    retryAt = now + RETRY_MS
637    const why = reply.isAnswered ? 'model reply was no JSON; trying again' : `model gave no answer (${reply.reason})`
638    await update($, live, l => (l.isOn ? { ...l, status: why, phase: l.pending.length ? 'answering' : 'listening' } : l))
639    return
640  }
641  void saveLabel($, labelOf(now, path, me.name, set, base, tail, text)).catch(() => {})
642  const heardNow = { lines: total, changedAt: mtimeMs, recent: me.recent }
643  // Folded into the state as it stands now: answers, lookups and rows an earlier step's answer call wrote meanwhile stay.
644  const step = await update($, live, l => {
645    if (!l.isOn) return l
646    const folded = l.meeting === path ? applyReply({ ...IDLE, ...l }, set, text, now, fresh) : applied
647    return { ...folded, ...heardNow, status: reading({ ...folded, pending: [] }) }
648  })
649  if (!step.isOn) return
650  const isNewCurrent = !!step.current && step.current !== base.current
651  if (isNewCurrent && !(await read($, opened)).length) await $.ui.scroll({ in: PANE, to: 'start', block: 'start' }).catch(() => {})
652
653  // Detached: the next tick may detect while answers are being written. It writes rows, pending and phase only; the
654  // status line belongs to the ticks.
655  const answer = async () => {
656    const rows = [...step.added, ...step.next]
657    const waiting = step.pending
658      .filter(q => !answering.has(q))
659      .map(q => rows.find(r => r.question === q))
660      .filter((q): q is Question => !!q)
661    const questions = waiting.map(q => q.question)
662    if (questions.length) {
663      questions.forEach(q => answering.add(q))
664      try {
665        const items = await Promise.all(waiting.map(async q => ({ question: q.question, hits: q.search?.length ? await repoHits($, q.search) : [] })))
666        const { model, effort, timeoutMs } = await levelOf($)
667        const ask = async (part: typeof items) => {
668          const answers = await $.model.complete({
669            model,
670            effort,
671            system: GROUND_SYSTEM,
672            prompt: [{ text: known, cache: true }, { text: ground(part, language) }],
673            maxTokens: 3000,
674            timeoutMs,
675          })
676          if (answers.isAnswered) await update($, live, l => applyAnswers({ ...IDLE, ...l }, part.map(i => i.question), answers.text))
677        }
678        // The question asked now gets a call of its own, beside the one for the rest: its answers need not wait for theirs.
679        await Promise.all([items.filter(i => i.question === step.current), items.filter(i => i.question !== step.current)].filter(p => p.length).map(ask))
680      } finally {
681        // ponytail: a call that never settles keeps its questions here until the session restarts; timeoutMs bounds it
682        questions.forEach(q => answering.delete(q))
683      }
684    }
685    const after = { ...IDLE, ...(await read($, live)) }
686    void linkAll($, answerSources([...after.added, ...after.next]))
687  }
688  void answer().catch(() => {})
689  if (isNewCurrent) await lookUp($, step.current!, set, { ...IDLE, ...(await read($, live)) })
690}
691
692const slug = (text: string) =>
693  text
694    .toLowerCase()
695    .replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
696    .replace(/[^a-z0-9]+/g, '-')
697    .replace(/^-|-$/g, '')
698    .slice(0, 40)
699    .replace(/-$/, '')
700
701const mdQuestion = (q: Question) =>
702  [
703    `### ${q.question}`,
704    '',
705    ...[
706      q.who && `- Likely asked by: ${q.who}`,
707      q.why && `- Expected because: ${q.why}`,
708      q.answerer && `- Answered by us: ${q.answerer}`,
709      `- Likelihood ${q.relevance}/5 · Answer confidence ${confidenceOf(q)}/5`,
710    ].filter(Boolean),
711    '',
712    ...[...q.answers]
713      .sort((a, b) => ORDER.indexOf(a.risk) - ORDER.indexOf(b.risk))
714      .flatMap(a => [
715        `**${RISKS[a.risk].mark} ${RISKS[a.risk].action}** · ${RISKS[a.risk].label}`,
716        '',
717        a.text,
718        ...(a.note ? ['', `Note: ${a.note}`] : []),
719        ...(a.source ? ['', `Source: ${a.source}`] : []),
720        '',
721      ]),
722  ].join('\n')
723
724/** The pane as Markdown: the set by answer confidence, then whatever listening produced, then the sources. */
725export const toMarkdown = (set: QuestionSet | null, ear: Live, exportedAt: string, hrefs: Record<string, string> = {}) => {
726  const questions = [...(set?.questions ?? [])].sort(bySurest)
727  const section = (title: string, list: Question[]) => (list.length ? [`## ${title}`, '', ...list.map(mdQuestion)] : [])
728  const sources = (set?.sources ?? []).map(asSource)
729  const recent = recentOf(set, ear)
730
731  return [
732    `# ${set?.title ?? 'Questions from the conversation'}`,
733    '',
734    [set && `Prepared ${set.generatedAt} UTC`, `exported ${exportedAt} UTC`].filter(Boolean).join(' · '),
735    '',
736    `Legend: ${ORDER.map(r => `${RISKS[r].mark} ${RISKS[r].action.toLowerCase()} (${RISKS[r].label})`).join(' · ')}`,
737    '',
738    ...(recent.length ? ['## Safe to say: my recent work', '', ...recent.map(f => `- ${f.text}${f.source ? ` (${f.source})` : ''}`), ''] : []),
739    ...GROUPS.flatMap((g, k) =>
740      section(g.label, questions.filter(q => confidenceOf(q) >= g.min && (k === 0 || confidenceOf(q) < GROUPS[k - 1]!.min))),
741    ),
742    ...section('Asked in the meeting, not prepared', ear.added),
743    ...section('Likely next (latest state)', ear.next),
744    ...(ear.asked.length ? ['## Asked in the meeting', '', ...ear.asked.map(q => `- ${q}`), ''] : []),
745    ...(sources.length
746      ? [
747          '## Sources',
748          '',
749          ...(Object.keys(SOURCE_KINDS) as SourceKind[]).flatMap(kind => {
750            const items = sources.filter(src => src.kind === kind)
751            const line = (label: string) => (hrefs[label] ? `- [${label}](${hrefs[label]})` : `- ${label}`)
752            return items.length ? [`**${SOURCE_KINDS[kind]}**`, '', ...items.map(src => line(src.label)), ''] : []
753          }),
754        ]
755      : []),
756  ].join('\n')
757}
758
759const exportMarkdown = async ($: EngineInterface) => {
760  const set = await read($, current)
761  const ear = { ...IDLE, ...(await read($, live)) }
762  const now = stamp(await $.clock.now())
763  const path = `question-sets/${now.slice(0, 10)}-${now.slice(11, 16).replace(':', '')}-${slug(set?.title ?? 'conversation') || 'question-set'}.md`
764  // Absolute: a relative path is not reliably the session's working directory.
765  await $.fs.write(`${await $.session.cwd()}/${path}`, toMarkdown(set, ear, now, await read($, links)))
766  $.ui.toast(`Exported: ${path}`)
767}
768
769export const register: Register = on => {
770  let isListening = false
771  on('session.start', async ($, e, next) => {
772    await $.command.register({
773      name: 'great-question-prep',
774      description: 'Great Question: find the likely questions for a pitch, meeting or daily stand-up in the background (optionally name the occasion)',
775      argumentHint: '[occasion]',
776    })
777    await $.command.register({
778      name: 'great-question',
779      description: 'Great Question: open the pane (without preparing new questions)',
780    })
781    await $.tool.register({
782      name: 'show_questions',
783      description:
784        'Shows a question set (the most likely questions for a pitch, meeting or daily stand-up, with answer options by risk) in the Great Question pane and stores it for this repository.',
785      inputSchema: SCHEMA,
786    })
787    // What the last module read is gone with it: a new one reads the transcript and the briefing anew.
788    heard = null
789    briefed = null
790    worked = null
791    answering.clear()
792    retryAt = 0
793    // Links a first try missed (git not ready, a source new since) come with the next round.
794    $.clock.every(LINK_MS, () => void linkPending($))
795    $.clock.every(TICK_MS, () => {
796      if (isListening) return void cutForNewLines($).catch(() => {})
797      isListening = true
798      void listen($).finally(() => (isListening = false))
799    })
800    // Once the session has settled: links of the questions it starts with.
801    $.clock.after(1000, () => void linkPending($))
802    // The version as installed, read from the copy that actually runs (the plugin cache, not the source folder).
803    try {
804      const manifest = JSON.parse((await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as string)
805      await update($, version, () => String(manifest.version ?? ''))
806    } catch {
807      // no manifest to read (tests): the pane just shows no version
808    }
809    // State and sets from 0.8 and earlier carry German names: translate them once here.
810    await update($, view, v => (v === 'practice' || (v as string) === 'training' ? 'practice' : 'meeting'))
811    await update($, sortBy, v => (v === 'likelihood' || (v as string) === 'wahrscheinlich' ? 'likelihood' : 'confidence'))
812    // Links are worked out again when drawn: one kept from a failed lookup would stay wrong.
813    await update($, links, () => ({}))
814    // Background agents do not outlive the module: nothing is still being looked up or prepared.
815    await update($, preparing, () => null)
816    // Answers 0.10.2 and earlier kept as the model wrote them: an object among them blanked the pane, so they are cleaned here too.
817    const cleaned = (deep: Live['deep'] = {}) => Object.fromEntries(Object.entries(deep).map(([q, list]) => [q, toAnswers(list)]))
818    // A fresh session starts clean, on the start screen. Only a running listener stays: a reload mid-meeting must not drop it.
819    // ponytail: no event tells a reload from a new session; a listener left on in an old session resumes until paused
820    const isMeeting = (await read($, live)).isOn
821    if (!isMeeting) {
822      await update($, live, () => IDLE)
823      await update($, held, () => null)
824      await update($, opened, () => [])
825      await update($, current, () => null)
826    }
827    await update($, live, l => ({ ...IDLE, ...l, added: withRisks(l.added ?? []), next: withRisks(l.next ?? []), deep: cleaned(l.deep), looking: [] }))
828    await update($, held, h => h && { next: withRisks(h.next), added: withRisks(h.added) })
829    // Questions on show from before 0.10 know no folder: the key they are stored under names it.
830    const shown = await read($, current)
831    if (shown && !shown.folder) {
832      for (const key of (await $.store.keys().catch(() => [])).filter(k => k.startsWith('set:'))) {
833        const kept = (await $.store.get(key)) as QuestionSet | undefined
834        if (kept?.title === shown.title && kept.generatedAt === shown.generatedAt) {
835          await update($, current, c => c && { ...c, folder: key.slice(4) })
836          break
837        }
838      }
839    }
840    const folder = await $.session.cwd()
841    const saved = await storedSet($, folder)
842    await update($, previous, () => (saved ? { title: saved.title, count: saved.questions.length, generatedAt: saved.generatedAt, folder } : null))
843    if (saved) {
844      if (isMeeting) await update($, current, () => saved)
845      void $.ui.open({ id: PANE, title: 'Great Question' })
846    }
847
848    return next(e)
849  })
850
851  // A repository lookup ends as its subagent's turn: its answers replace the question's own while it is asked.
852  on('turn.complete', async ($, e, next) => {
853    const result = await next(e)
854    // The background agent that found likely questions: show them, or say nothing came back.
855    if (e.agentId && e.agentId === prepAgent) {
856      prepAgent = null
857      stopTick?.cancel()
858      stopTick = null
859      const folder = (await read($, preparing))?.folder
860      const set = e.reason === 'answer' ? fromReply(e.answer, stamp(await $.clock.now()), folder) : null
861      await update($, preparing, () => null)
862      if (set) await showSet($, set)
863      $.ui.toast(set ? `Great Question: ${set.questions.length} likely questions ready` : 'Great Question: no likely questions came back')
864      return result
865    }
866    const question = e.agentId ? lookups.get(e.agentId) : undefined
867    if (!question) return result
868    lookups.delete(e.agentId!)
869    await update($, live, l => settleLookup({ ...IDLE, ...l }, question, e.reason === 'answer' ? e.answer : null))
870    void linkAll($, ((await read($, live)).deep?.[question] ?? []).map(a => a.source))
871    return result
872  })
873
874  // The notification of a finished lookup would start a turn of the main model mid-meeting: it stays out.
875  on('prompt.submit', async ($, e, next) => {
876    if (e.origin?.kind === 'task-notification' && [...ours].some(id => e.text.includes(id))) return { drop: 'Great Question: repository lookup done' }
877    return next(e)
878  })
879
880  on('command.run', { command: 'great-question' }, async $ => {
881    const { isPlaced } = await $.ui.open({ id: PANE, title: 'Great Question' })
882
883    return { text: isPlaced ? 'Great Question opened.' : 'Great Question opened but not shown: make the window wider.' }
884  })
885
886  on('command.run', { command: 'great-question-prep' }, async ($, e) => {
887    await $.ui.open({ id: PANE, title: 'Great Question' })
888    await startPrep($, e.args)
889
890    return { text: `Finding likely questions in the background${e.args.trim() ? ` (occasion: ${e.args.trim()})` : ' (no occasion given)'}.` }
891  })
892
893  on('tool.call', { tool: TOOL }, async ($, e) => {
894    const set = toSet(e as unknown as Record<string, unknown>, stamp(await $.clock.now()), await $.session.cwd())
895    if (set.questions.length === 0) return { deny: 'No questions in the input: give questions[] with question, relevance, answers.' }
896    await showSet($, set)
897
898    return { result: `${set.questions.length} questions shown in the Great Question pane.` }
899  })
900
901  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
902    const { Box, Text, Button, Link } = $.ui.resolve(e)
903    const stored = await read($, current)
904    const hrefs = await read($, links)
905    // A source as a link where it points somewhere a surface can open, plain text otherwise.
906    const sourceOf = (label: string, prefix: string, key: string, size?: 'caption') => {
907      const href = hrefs[label]
908      return href ? (
909        <Box key={key} flexDirection="row" columnGap={1}>
910          <Text dimColor size={size}>{prefix}</Text>
911          <Link href={href} label={label} />
912        </Box>
913      ) : (
914        <Text key={key} dimColor size={size}>
915          {prefix} {label}
916        </Text>
917      )
918    }
919    const openList = await read($, opened)
920    const frozen = await read($, held)
921    const isMore = await read($, more)
922    const folder = (await $.session.cwd()).split('/').filter(Boolean).pop() ?? 'this folder'
923    const prep = await read($, preparing)
924    const frame = ['◐', '◓', '◑', '◒'][(await read($, tick)) % 4]
925    const now = await $.clock.now()
926    const folds = await read($, toggled)
927    const took = prep ? Math.max(0, Math.round((now - prep.since) / 1000)) : 0
928    const isPractice = (await read($, view)) === 'practice'
929    const isByLikely = (await read($, sortBy)) === 'likelihood'
930    const language = await read($, lang)
931    const level = await read($, quality)
932    // Spread over IDLE: a value from an older version of the mod may lack newer fields.
933    const ear: Live = { ...IDLE, ...(await read($, live)) }
934    const shown = await read($, version)
935    const lastTime = await read($, previous)
936    const recent = recentOf(stored, ear)
937    const hasLive = ear.asked.length + ear.added.length + ear.next.length > 0
938
939    // Without a set the pane still listens; it just has nothing prepared to match.
940    const set: QuestionSet = stored ?? { title: 'No prepared questions yet', mode: '', generatedAt: '', sources: [], questions: [] }
941
942    // A dim rule above each section header; truncated so it never wraps on a narrow or proportional surface.
943    const rule = '─'.repeat(Math.max(8, Number(e.props.bodyColumns) || 60))
944    const heading = (text: string) => (
945      <>
946        <Text dimColor wrap="truncate">{rule}</Text>
947        <Text bold dimColor>{text}</Text>
948      </>
949    )
950    // Stopping only pauses: what the call produced stays until Clear; a new recording starts afresh.
951    const toggleEar = () =>
952      update($, live, l => ({
953        ...l,
954        isOn: !l.isOn,
955        status: l.isOn ? `paused · ${l.lines} utterances read · results stay` : 'starting …',
956      }))
957    const isOpen = (q: Question) => openList.includes(q.question)
958    const toggle = (q: Question) => setOpen($, list => (list.includes(q.question) ? list.filter(t => t !== q.question) : [...list, q.question]))
959    const answerRow = (a: Answer, j: number) => (
960      <Box key={`a${j}`} flexDirection="column" marginTop={1}>
961        <Text>
962          <Text color={RISKS[a.risk].color} bold>
963            {RISKS[a.risk].mark} {RISKS[a.risk].action}
964          </Text>
965          <Text dimColor> · {RISKS[a.risk].label}</Text>
966        </Text>
967        <Box flexDirection="column" paddingLeft={2}>
968          {/* Colour repeats the mark and the word above, so nothing rests on colour alone. */}
969          <Text color={RISKS[a.risk].color}>{a.text}</Text>
970          {a.note && <Text dimColor>Note: {a.note}</Text>}
971          {a.source && sourceOf(a.source, 'Source:', `src${j}`)}
972        </Box>
973      </Box>
974    )
975    // A repository lookup's answers stand in for the question's own.
976    const byRisk = (q: Question) => [...(ear.deep[q.question] ?? q.answers)].sort((a, b) => ORDER.indexOf(a.risk) - ORDER.indexOf(b.risk))
977    const isAsked = (q: Question) => ear.asked.includes(q.question)
978    const isPending = (q: Question) => ear.pending.includes(q.question)
979    // Live rows show their best answer when closed, so a glance is enough and nothing opens by itself.
980    const questionRow = (q: Question, hasHint = false) => {
981      const k = rowKey(q.question)
982      const best = byRisk(q)[0]
983      return (
984        <Box key={`r${k}`} flexDirection="column" marginBottom={1}>
985          <Button key={`t${k}`} plain onPress={() => toggle(q)}>
986            {isOpen(q) ? '▾ ' : '▸ '}
987            {isAsked(q) ? <Text dimColor>✓ </Text> : ''}
988            <Text bold color={isAsked(q) ? undefined : 'text'} dimColor={isAsked(q)}>
989              {q.question}
990            </Text>
991            {/* A live row says whether it is for me; a prepared one shows its answers' marks. */}
992            {hasHint ? '' : ' '}
993            {hasHint ? (q.to === 'me' ? <Text dimColor> · you</Text> : '') : byRisk(q).map(a => <Text color={RISKS[a.risk].color}>{RISKS[a.risk].mark}</Text>)}
994          </Button>
995          {!isOpen(q) && hasHint && isPending(q) && (
996            <Box paddingLeft={2}>
997              <Text dimColor color="warning">
998                answering …
999              </Text>
1000            </Box>
1001          )}
1002          {!isOpen(q) && hasHint && !isPending(q) && best && (
1003            // The mark in a box of its own that never shrinks: inside one truncated line the desktop broke it apart.
1004            <Box paddingLeft={2} flexDirection="row" columnGap={1}>
1005              <Box flexShrink={0}>
1006                <Text color={RISKS[best.risk].color}>
1007                  {RISKS[best.risk].mark} {RISKS[best.risk].action}:
1008                </Text>
1009              </Box>
1010              <Box flexShrink={1} minWidth={0}>
1011                <Text dimColor wrap="truncate">
1012                  {best.text}
1013                </Text>
1014              </Box>
1015            </Box>
1016          )}
1017          {isOpen(q) && (
1018            <Box flexDirection="column" paddingLeft={2}>
1019              {/* The question leads; these lines step back as far as the theme allows. */}
1020              {q.who && <Text color="subtle" dimColor italic>Likely asked by: {q.who}</Text>}
1021              {q.why && <Text color="subtle" dimColor italic>Expected because: {q.why}</Text>}
1022              {q.answerer && <Text color="subtle" dimColor italic>Answered by us: {q.answerer}</Text>}
1023              <Text color="subtle" dimColor italic>
1024                Likelihood {q.relevance}/5 · Answer confidence {confidenceOf(q)}/5
1025              </Text>
1026              {byRisk(q).map(answerRow)}
1027            </Box>
1028          )}
1029        </Box>
1030      )
1031    }
1032    const order = isPractice ? -1 : 1
1033    const groupKey = isByLikely ? (q: Question) => q.relevance : confidenceOf
1034    const groupList = isByLikely ? LIKELY_GROUPS : GROUPS
1035    // While listening an asked question stays where it is, marked ✓; paused, it moves to the end.
1036    const isSinking = (q: Question) => !ear.isOn && isAsked(q)
1037    const listed = groupList
1038      .map((g, k) => ({
1039        ...g,
1040        items: set.questions
1041          .filter(q => !isSinking(q))
1042          .filter(q => groupKey(q) >= g.min && (k === 0 || groupKey(q) < groupList[k - 1]!.min))
1043          .sort((a, b) => order * (groupKey(b) - groupKey(a) || b.relevance - a.relevance || confidenceOf(b) - confidenceOf(a))),
1044      }))
1045      .filter(g => g.items.length > 0)
1046      .sort((a, b) => order * (b.min - a.min))
1047    const asked = set.questions.filter(isSinking)
1048    // The live sections as drawn: held while a row is open, so nothing moves under the reader.
1049    const source = frozen ?? ear
1050    const inSet = (q: Question) => set.questions.some(k => k.question === q.question)
1051    const nextRows = source.next.filter(q => !inSet(q))
1052    const addedRows = source.added.filter(q => !inSet(q) && !nextRows.some(k => k.question === q.question))
1053    const drawn = new Set([...nextRows, ...addedRows].map(q => q.question))
1054    const waiting = frozen ? [...ear.next, ...ear.added].filter(q => !drawn.has(q.question) && !inSet(q)).length : 0
1055    // Questions for me lead, then the likelier, then the newer; a few, so the next one is found at a glance.
1056    const upNext = [...nextRows]
1057      .sort((a, b) => Number(b.to === 'me') - Number(a.to === 'me') || b.relevance - a.relevance || (b.heardAt ?? 0) - (a.heardAt ?? 0))
1058      .slice(0, MAX_SHOWN_NEXT)
1059    // The question on the table, always live; its row stays in its section too.
1060    const nowRow = ear.current ? [...set.questions, ...ear.added].find(q => q.question === ear.current) : undefined
1061    // Newest first; the question asked now has the card.
1062    const earlier = [...addedRows].reverse().filter(q => q.question !== ear.current).sort((a, b) => (b.heardAt ?? 0) - (a.heardAt ?? 0))
1063    const rows = [...nextRows, ...addedRows, ...listed.flatMap(g => g.items), ...asked]
1064    // Two buttons, not one toggle: closing must never mean opening every row first.
1065    const isAllOpen = rows.length > 0 && rows.every(isOpen)
1066    const isAnyOpen = rows.some(isOpen)
1067    const sorting = isPractice
1068      ? `Practice: ${isByLikely ? 'rarest' : 'least certain'} first`
1069      : isByLikely ? 'most likely first' : 'surest first'
1070    // While listening the status rides on the ear button; anything else it says stays a line of its own.
1071    const isHeard = ear.isOn && ear.status.startsWith('listening')
1072    const earLabel = !ear.isOn ? 'Listen live' : isHeard ? `◉ L${ear.status.slice(1).replace('last utterance ', '')}` : '◉ Listening'
1073    // Listening folds every section below the card; paused, the prepared questions and my recent work stand open.
1074    const isUnfolded = (key: string) => (!ear.isOn && (key === 'prepared' || key === 'safe')) !== folds.includes(key)
1075    const fold = (key: string, title: string, body: () => RenderChildren) => (
1076      <Box key={key} flexDirection="column">
1077        <Text dimColor wrap="truncate">{rule}</Text>
1078        <Button key={`fold:${key}`} plain onPress={() => update($, toggled, t => (t.includes(key) ? t.filter(k => k !== key) : [...t, key]))}>
1079          <Text bold dimColor>
1080            {isUnfolded(key) ? '▾ ' : '▸ '}
1081            {title}
1082          </Text>
1083        </Button>
1084        {isUnfolded(key) && body()}
1085      </Box>
1086    )
1087    // The card: who the question is for, the answer to give, the one to avoid; the rest behind a button.
1088    const card = (q: Question) => {
1089      const answers = byRisk(q)
1090      const best = answers[0]
1091      const risky = answers.find(a => a.risk === 'risky' && a !== best)
1092      const rest = answers.filter(a => a !== best && a !== risky)
1093      const isOther = q.to === 'other'
1094      const label = [
1095        (q.to && TO[q.to]) || 'ASKED NOW',
1096        ...(q.asker ? [`by ${q.asker}`] : []),
1097        ...(ear.currentAt > 0 ? [`${age(now - ear.currentAt)} ago`] : []),
1098      ].join(' · ')
1099      return (
1100        <>
1101          <Text size="caption" dimColor>
1102            {label}
1103          </Text>
1104          <Text size="title" weight={isOther ? 'regular' : 'semibold'} dimColor={isOther}>
1105            {q.question}
1106          </Text>
1107          {isPending(q) ? (
1108            <Text dimColor color="warning">
1109              answering …
1110            </Text>
1111          ) : ear.looking.includes(q.question) ? (
1112            <Text dimColor>checking the repository …</Text>
1113          ) : (
1114            ear.deep[q.question] && <Text dimColor>from the repository</Text>
1115          )}
1116          {isOpen(q)
1117            ? answers.map(answerRow)
1118            : best && (
1119                <Box flexDirection="column" marginTop={1}>
1120                  <Text size="heading" weight="semibold" color={RISKS[best.risk].color}>
1121                    {RISKS[best.risk].mark} {RISKS[best.risk].action}
1122                  </Text>
1123                  <Text size="heading" color={RISKS[best.risk].color}>
1124                    {best.text}
1125                  </Text>
1126                  {best.source && sourceOf(best.source, 'Source:', 'now-src', 'caption')}
1127                  {best.risk !== 'sourced' && best.note && (
1128                    <Text size="footnote" dimColor>
1129                      Note: {best.note}
1130                    </Text>
1131                  )}
1132                </Box>
1133              )}
1134          {!isOpen(q) && risky && (
1135            <Text size="footnote" color="error" wrap="truncate">
1136              ✖ Don't say: {risky.text}
1137            </Text>
1138          )}
1139          {rest.length > 0 && (
1140            <Button key="now-more" plain onPress={() => toggle(q)}>
1141              {isOpen(q) ? '▾ fewer' : `▸ ${rest.length} more answers`}
1142            </Button>
1143          )}
1144        </>
1145      )
1146    }
1147
1148    return (
1149      <Box flexDirection="column" gap={1}>
1150        <Box flexDirection="column">
1151          <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
1152            <Text>
1153              <Text bold>{set.title}</Text>
1154              {stored ? <Text dimColor> · {set.questions.length} prepared{set.language ? ` · ${set.language.toUpperCase()}` : ''}</Text> : ''}
1155            </Text>
1156            {shown && <Text dimColor>v{shown}</Text>}
1157          </Box>
1158          {/* Wraps onto further rows on a narrow pane instead of pushing buttons out of view. */}
1159          <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
1160            <Button
1161              key="ear"
1162              variant={ear.isOn ? 'primary' : 'secondary'}
1163              label={earLabel}
1164              onPress={toggleEar}
1165            />
1166            <Button key="gen" label={prep ? 'Finding …' : 'Find likely questions'} onPress={() => startPrep($, '')} />
1167            {rows.length > 0 && !isAllOpen && <Button key="open-all" label="Open all" onPress={() => setOpen($, () => rows.map(q => q.question))} />}
1168            {isAnyOpen && <Button key="close-all" label="Close all" onPress={() => setOpen($, () => [])} />}
1169            <Button key="more" dimColor label={isMore ? 'More ▾' : 'More ▸'} onPress={() => update($, more, m => !m)} />
1170          </Box>
1171        </Box>
1172        {isMore && (
1173          <Box flexDirection="column" rowGap={1}>
1174            <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
1175              <Button
1176                key="lang"
1177                label={`Language: ${language === 'auto' ? 'Auto' : language.toUpperCase()}`}
1178                onPress={() => update($, lang, l => LANGS[(LANGS.indexOf(l) + 1) % LANGS.length]!)}
1179              />
1180              <Button
1181                key="quality"
1182                label={`Model: ${QUALITY[level]?.label ?? QUALITY.fast.label}`}
1183                onPress={() => update($, quality, q => QUALITIES[(QUALITIES.indexOf(q) + 1) % QUALITIES.length]!)}
1184              />
1185              <Button
1186                key="sort"
1187                label={isByLikely ? 'Sort: most likely asked' : 'Sort: safest to answer'}
1188                onPress={() => update($, sortBy, v => (v === 'likelihood' ? 'confidence' : 'likelihood'))}
1189              />
1190              <Button
1191                key="view"
1192                variant={isPractice ? 'primary' : 'secondary'}
1193                label={isPractice ? 'Practice' : 'Meeting'}
1194                onPress={() => update($, view, v => (v === 'practice' ? 'meeting' : 'practice'))}
1195              />
1196              {(stored || hasLive) && <Button key="export" label="Export" onPress={() => exportMarkdown($)} />}
1197              {!ear.isOn && hasLive && (
1198                <Button
1199                  key="clear"
1200                  label="Clear"
hooks/live.ts 400 lines
1import type { Addressee, Answer, Fact, Lang, Live, Question, QuestionSet, Risk } from '../types'
2
3export const IDLE: Live = { isOn: false, status: '', meeting: null, lines: 0, changedAt: 0, asked: [], current: null, added: [], next: [], deep: {}, looking: [], recent: [], phase: 'idle', pending: [], currentAt: 0, steppedAt: 0 }
4
5const RISKS: readonly Risk[] = ['sourced', 'commitment', 'vague', 'risky']
6// Risk classes as stored by 0.8 and earlier, which used German names.
7const OLD_RISKS: Record<string, Risk> = { belegt: 'sourced', zusage: 'commitment', vage: 'vague', riskant: 'risky' }
8
9/** A risk class from a model reply or an older stored set; anything unknown counts as vague. */
10export const asRisk = (risk: unknown): Risk =>
11  RISKS.includes(risk as Risk) ? (risk as Risk) : (OLD_RISKS[String(risk)] ?? 'vague')
12
13/** Questions from state an older version wrote: their risk classes in today's names, their notes and sources text or nothing. */
14export const withRisks = (list: Question[]): Question[] => list.map(q => ({ ...q, answers: toAnswers(q.answers) }))
15
16/** A model's free text as the pane draws it: a string, or nothing. An object drawn as text makes the engine refuse every redraw. */
17export const asText = (v: unknown) => (typeof v === 'string' ? v : undefined)
18
19const WINDOW_MS = 120_000
20const MAX_LINES = 60
21const MAX_NEXT = 5
22
23// A line without a source is nobody in particular: labelled Mic, every question in it read as mine and was left out.
24const SPEAKERS: Record<string, string> = { system: 'Call', mic: 'Mic' }
25
26type Utterance = { text?: string; timestamp?: string; endRecordingMs?: number; speaker?: { source?: string } }
27
28/**
29 * Wispr's live.ndjson: a meta line, then one utterance per line. The tail is the last two minutes of the
30 * recording. Names stay out; `system` is call audio, `mic` this machine's microphone (us, or a whole room).
31 * Rows from `since` on are new since the last step: their texts are `fresh`, and the tail marks them with `> `.
32 */
33export const parseTranscript = (ndjson: string, since = 0) => {
34  const rows = ndjson
35    .split('\n')
36    .map(line => {
37      try {
38        return JSON.parse(line) as Utterance
39      } catch {
40        return null
41      }
42    })
43    .filter((u): u is Utterance => typeof u?.text === 'string')
44  const end = Number(rows.at(-1)?.endRecordingMs) || 0
45  const recent = rows
46    .map((u, i) => ({ u, isNew: i >= since }))
47    .filter(({ u }) => !end || Number(u.endRecordingMs) >= end - WINDOW_MS)
48    .slice(-MAX_LINES)
49
50  return {
51    lines: rows.length,
52    tail: recent
53      .map(({ u, isNew }) => `${isNew ? '> ' : ''}[${u.timestamp ?? ''}] ${SPEAKERS[u.speaker?.source ?? ''] ?? 'Unknown'}: ${u.text}`)
54      .join('\n'),
55    fresh: rows.slice(since).map(u => u.text!),
56  }
57}
58
59const QUESTION_WORDS = 'wer|was|wann|wo|wie|warum|wieso|weshalb|welche|welcher|welches|wem|wen|wessen|who|what|when|where|why|how|which|whom'
60const AUXILIARIES =
61  'ist|sind|bist|seid|hast|habt|haben|hat|kannst|könnt|können|könnte|wird|werden|gibt|sollen|sollte|würde|müssen|do|does|did|is|are|was|were|can|could|will|would|should|have|has|shall'
62const FILLER = 'yeah|yes|so|okay|ok|uh|um|well|and|alright|ja|also|und|äh|ähm|na|gut'
63const OPENER = new RegExp(`^[\\s"'„“(-]*(?:(?:${FILLER})[\\s,.!]+)*(?:${QUESTION_WORDS}|(?:${AUXILIARIES})(?:n['’]t)?)(?!\\p{L})`, 'iu')
64// After another word: a lone "Okay." is a reply, not a tag question.
65const TAG = /[\p{L}\p{N}][\s,;:–-]+(?:oder|ne|gell|nicht wahr|right|okay|ok|correct)[\s.,!?…]*$/iu
66const asWord = (name: string) => new RegExp(`(?<!\\p{L})${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?!\\p{L})`, 'iu')
67
68/**
69 * Whether new lines may hold a question worth a model step now: a question mark, one of my names, a question word or
70 * verb at the start, or a tag such as "oder?" or "right?" at the end. Errs towards yes; the model judges the rest.
71 */
72// ponytail: word lists for German and English only; another meeting language waits for the STEP_MS fallback
73export const isTrigger = (texts: readonly string[], names: readonly string[]) => {
74  const mine = names.map(asWord)
75  return texts.some(t => t.includes('?') || mine.some(n => n.test(t)) || OPENER.test(t) || TAG.test(t))
76}
77
78/** A row's address, from its text: focus and open state stay with the question when rows around it change. */
79export const rowKey = (question: string) => {
80  let h = 5381
81  for (const c of question) h = ((h * 33) ^ c.charCodeAt(0)) >>> 0
82  return `q:${h.toString(36)}`
83}
84
85const words = (text: string) =>
86  new Set(
87    text
88      .toLowerCase()
89      .replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
90      .split(/[^a-z0-9]+/)
91      .filter(w => w.length > 2),
92  )
93
94// ponytail: word overlap catches the model rewording a question between steps; embeddings if it misses too much
95export const isSameQuestion = (a: string, b: string) => {
96  if (a.toLowerCase() === b.toLowerCase()) return true
97  const x = words(a)
98  const y = words(b)
99  const shared = [...x].filter(w => y.has(w)).length
100  return x.size > 0 && y.size > 0 && shared / (x.size + y.size - shared) >= 0.7
101}
102
103/**
104 * Whether at least 70 % of a question's words were said in these lines. Haiku's own "new" list agreed with hand labels
105 * on whom a question is for in 0.54 of 82 rows, filtered this way in 0.87 (measured 23.10.2026).
106 */
107export const isSaid = (question: string, lines: readonly string[]) => {
108  const q = words(question)
109  const heard = words(lines.join(' '))
110  return q.size > 0 && [...q].filter(w => heard.has(w)).length / q.size >= 0.7
111}
112
113export const SYSTEM =
114  'You are listening to a meeting in progress and help me anticipate the questions I will have to answer, and answer them safely. Reply with a JSON object only, no text before or after it.'
115
116/** What I worked on last: what the prepared set says, else my latest commits found while listening. */
117export const recentOf = (set: QuestionSet | null, live: Live): Fact[] => (set?.recent?.length ? set.recent : (live.recent ?? []))
118
119/** What the model knows before it reads the transcript; `briefing` is what the repository says is current. */
120export const knowledge = (set: QuestionSet | null, live: Live, briefing = '') =>
121  [
122    set && set.questions.length
123      ? [
124          'Prepared question set with sourced answers (number: question | answers with risk):',
125          ...set.questions.map(
126            (q, i) =>
127              `${i}: ${q.question} | ${q.answers.map(a => `[${a.risk}] ${a.text}${a.source ? ` (source: ${a.source})` : ''}`).join(' / ')}`,
128          ),
129        ].join('\n')
130      : 'No prepared question set.',
131    '',
132    'Questions already asked in the meeting that are not in the set:',
133    ...(live.added.length ? live.added.map(q => `- ${q.question}`) : ['- none']),
134    '',
135    'What I worked on most recently, each certainly true:',
136    ...recentOf(set, live).map(f => `- ${f.text}${f.source ? ` (source: ${f.source})` : ''}`),
137    ...(briefing ? ['', 'Current facts from the repository, newest first (briefing):', briefing] : []),
138  ].join('\n')
139
140/** Questions and answers in the meeting's language; who, why and notes stay English for the team. */
141export const languageRule = (lang: Lang) =>
142  lang === 'de'
143    ? 'Write "question" and the answer "text"s in German.'
144    : lang === 'en'
145      ? 'Write "question" and the answer "text"s in English.'
146      : 'Write "question" and the answer "text"s in the language the meeting is held in.'
147
148/**
149 * The answer options every live prompt asks for, safest first: one that is true and binds us to nothing always comes,
150 * a promise only when the question asks for one. `sourced` says what counts as a source in that prompt.
151 */
152const answerRules = (sourced: string) => `- "sourced": ${sourced}
153- "vague": true and binding us to nothing: what we know, what is still open. When nothing is sourced, the first option is this one.
154- "commitment": only when the question asks for a date, an owner or a scope; never a date, name or promise nobody gave in the meeting or the material.
155- "risky": at most one, as a warning of what not to say.
156Only a "commitment" may promise anything: no "I will send …", "we will check …" or date in any other option.
157Every option but "sourced" has a "note".`
158
159/** The first half of a step: which questions were asked, whom they were for, what comes next; no answers, so it is quick. */
160export const detectTask = (tail: string, lang: Lang = 'auto', me = '') => `The last two minutes of the transcript. I am the person this pane is for${me ? `: ${me}` : ''}. "Mic" is this computer's microphone: me in a video call, everyone in the room in an on-site meeting. "Call" is audio from the video call: everyone else. "Unknown" is anyone. Lines marked ">" are new since the last look; the others are context.
161${tail}
162
163Who a question is for:
164- A line from "Mic" is me speaking.
165- A question in the line right after my own turn, by the speaker who spoke before me, is probably for me.
166- The transcription may mishear my name: a near spelling counts as my name.
167- "you", "du" or "Sie" alone is a weak cue.
168
169Task:
1701. "asked": numbers of the questions from the question set that were asked, in substance, in this excerpt.
1712. "new": questions asked in this excerpt, neither in the question set nor among those already asked (at most 3), whoever they are for.
1723. "current": the question from the set or from "new" that was asked last in this excerpt and is for me or for everyone, never one for someone else: {"set": number} or {"new": index in "new"}; null when the excerpt asks none of those.
1734. "next": 2 to 3 questions I will most likely have to answer next, given how the conversation is going and what I worked on recently, also outside the set.
174For every question in "new" and "next":
175- "to": "me" (asked of me, by name, or about my ticket or my work), "all" (asked of everyone) or "other" (asked of someone else).
176- "asker": who asked, as a role or the first name as heard; leave it out when unknown.
177- "why": short, tied to the conversation.
178- "search": 2 to 4 distinctive words likely to appear in our repository where the answer would be written (product and component names, file names, figures), in the language the repository is most likely written in.
179- "relevance" 1 to 5: 5 = addressed to me by name or about my ticket or work; 4 = my topic or area; 3 = asked of everyone; 2 = someone else's topic I could add to; 1 = clearly someone else's.
180- "confidence" 1 to 5: how well the material above supports a sourced answer.
181No answers: a second step writes them.
182Language: ${languageRule(lang)} "why" in English.
183Format: {"asked": [], "new": [{"question": "", "to": "me", "asker": "", "why": "", "search": [""], "relevance": 5, "confidence": 2}], "current": null, "next": [{"question": "", "to": "all", "why": "", "search": [""], "relevance": 3, "confidence": 2}]}`
184
185const clamp = (n: unknown) => Math.min(5, Math.max(1, Math.round(Number(n) || 1)))
186const ADDRESSEES: readonly Addressee[] = ['me', 'all', 'other']
187
188/** Answer options from a model reply, a prepared set or older state; every caller's answers pass here before they are drawn. */
189export const toAnswers = (raw: unknown): Answer[] =>
190  (Array.isArray(raw) ? (raw as Answer[]) : [])
191    .filter(a => typeof a?.text === 'string')
192    .map(a => ({ text: a.text, risk: asRisk(a.risk), note: asText(a.note), source: asText(a.source) }))
193
194const toQuestions = (raw: unknown, limit: number): Question[] =>
195  (Array.isArray(raw) ? (raw as Question[]) : [])
196    .filter(q => typeof q?.question === 'string')
197    .slice(0, limit)
198    .map(q => ({
199      question: q.question,
200      relevance: clamp(q.relevance),
201      confidence: clamp(q.confidence),
202      why: asText(q.why),
203      to: ADDRESSEES.includes(q.to as Addressee) ? q.to : undefined,
204      asker: asText(q.asker)?.trim() || undefined,
205      search: Array.isArray(q.search) ? q.search.filter(t => typeof t === 'string' && t.trim()).slice(0, 4) : undefined,
206      answers: toAnswers(q.answers),
207    }))
208
209/**
210 * Folds one model reply into the live state; a reply that is not the asked-for JSON leaves the state as it was.
211 * The catalogue only grows: new rows go to the end, a row keeps its wording, nothing is dropped but a prediction.
212 * Rows still without answers wait in `pending` for the answer step.
213 */
214export const applyReply = (live: Live, set: QuestionSet | null, reply: string, now = 0, said?: readonly string[]): Live => {
215  let data: { asked?: unknown; new?: unknown; current?: { set?: unknown; new?: unknown } | null; next?: unknown }
216  try {
217    data = JSON.parse(reply.slice(reply.indexOf('{'), reply.lastIndexOf('}') + 1))
218  } catch {
219    return live
220  }
221  const questions = set?.questions ?? []
222  const isKnown = (q: string, list: Question[]) => list.some(k => isSameQuestion(k.question, q))
223
224  // The model's "new" also lists questions from the context lines; with `said` given, only those said in the new lines count.
225  const isNew = (q: Question) => !said || isSaid(q.question, said)
226  const fresh = toQuestions(data.new, 3).map(q => ({ ...q, heardAt: now }))
227  const added = [...live.added]
228  for (const q of fresh) if (isNew(q) && !isKnown(q.question, [...questions, ...added])) added.push(q)
229
230  const asked = new Set(live.asked)
231  for (const n of Array.isArray(data.asked) ? data.asked : []) {
232    const q = questions[Number(n)]
233    if (q) asked.add(q.question)
234  }
235
236  const pick = data.current
237  // A new question matched to one already listed takes that row's wording, so it points at a row on screen.
238  const asListed = (q: string) => [...questions, ...added].find(k => isSameQuestion(k.question, q))?.question ?? q
239  const fromSet = pick && typeof pick.set === 'number' ? questions[pick.set]?.question : undefined
240  const pickedNew = !fromSet && pick && typeof pick.new === 'number' ? fresh[pick.new] : undefined
241  const fromNew = pickedNew && isNew(pickedNew) ? pickedNew : undefined
242  const picked = fromSet || fromNew?.question || null
243  // Without a usable pick, the question this reply saw asked last stands in: keeping the old one left it on screen for good.
244  const seen = [...added.slice(live.added.length).filter(q => q.to !== 'other').map(q => q.question), ...[...asked].filter(q => !live.asked.includes(q))].at(-1)
245  // A question for someone else never takes the place of the one I still have to answer.
246  const current = fromNew?.to === 'other' ? live.current : picked ? asListed(picked) : (seen ?? live.current)
247  if (current) asked.add(current)
248
249  // Predictions stay until asked; new ones join at the end, and past MAX_NEXT the oldest not predicted again goes.
250  const isAsked = (q: string) => [...asked].some(a => isSameQuestion(a, q)) || isKnown(q, added)
251  const predicted = toQuestions(data.next, 3).map(q => ({ ...q, heardAt: now })).filter(q => !isAsked(q.question) && !isKnown(q.question, questions))
252  const next = live.next.filter(q => !isAsked(q.question))
253  const confirmed = new Set(next.filter(q => isKnown(q.question, predicted)).map(q => q.question))
254  for (const q of predicted) if (!isKnown(q.question, next)) next.push(q)
255  while (next.length > MAX_NEXT) {
256    const stale = next.findIndex(q => !confirmed.has(q.question))
257    next.splice(stale === -1 ? 0 : stale, 1)
258  }
259
260  const pending = [...added, ...next].filter(q => !q.answers.length).map(q => q.question)
261  const currentAt = current !== live.current ? now : live.currentAt
262  return { ...live, asked: [...asked], current, added, next, pending, phase: pending.length ? 'answering' : 'ready', currentAt, steppedAt: now }
263}
264
265/**
266 * One training row for a local decision model such as Laya: what a detect step read and what it decided, with the
267 * questions listed before it. Only for a reply `applyReply` took, so it parses.
268 */
269export const labelOf = (now: number, meeting: string, me: string, set: QuestionSet | null, live: Live, tail: string, reply: string) => ({
270  at: new Date(now).toISOString(),
271  meeting: meeting.split('/').at(-2) ?? meeting,
272  me,
273  tail,
274  set: (set?.questions ?? []).map(q => q.question),
275  added: live.added.map(q => q.question),
276  next: live.next.map(q => q.question),
277  decided: JSON.parse(reply.slice(reply.indexOf('{'), reply.lastIndexOf('}') + 1)) as unknown,
278})
279
280const MAX_HITS = 8
281
282/** git grep for a question's words in the session's repository; this mod's exports stay out, they hold earlier answers. */
283export const grepArgs = (terms: readonly string[]) => [
284  'git', 'grep', '-n', '-I', '-i', '-F', '--max-count=3',
285  ...terms.flatMap(t => ['-e', t]),
286  '--', '.', ':(exclude)question-sets', ':(exclude)fragensets',
287]
288
289/** The matching lines as `path:line: text`, files that hit the most words first, cut so a prompt stays small. */
290export const topHits = (stdout: string, terms: readonly string[]) => {
291  const byFile = new Map<string, string[]>()
292  for (const line of stdout.split('\n')) {
293    const m = /^([^:]+):(\d+):(.*)$/.exec(line)
294    if (!m) continue
295    byFile.set(m[1]!, [...(byFile.get(m[1]!) ?? []), `${m[1]}:${m[2]}: ${m[3]!.trim().slice(0, 200)}`])
296  }
297  const words = (lines: string[]) => terms.filter(t => lines.some(l => l.toLowerCase().includes(t.toLowerCase()))).length
298  return [...byFile.values()].sort((a, b) => words(b) - words(a)).flat().slice(0, MAX_HITS)
299}
300
301export const GROUND_SYSTEM = 'You answer questions from a meeting with lines from our repository. Reply with a JSON object only, no text before or after it.'
302
303/** The second half of a step: answers for the questions still waiting, from the repository's lines and what the knowledge says. */
304export const ground = (items: readonly { question: string; hits: string[] }[], lang: Lang) => `Questions from the meeting, each with lines from our repository (path:line: text):
305
306${items.map((it, i) => `${i}: ${it.question}\n${it.hits.length ? it.hits.join('\n') : 'no lines found'}`).join('\n\n')}
307
308For every question, 2 to 3 answer options, safest first, each with "risk":
309${answerRules('only when the lines above, the question set, my recent work or the briefing carry the answer; "source" is the path:line or the source named there.')}
310Language: ${languageRule(lang)} "note" in English.
311Format: {"answers": {"0": [{"text": "", "risk": "sourced", "source": "path:12", "note": ""}]}}, keyed by the question's number; leave out a question you cannot answer.`
312
313const parse = (reply: string) => JSON.parse(reply.slice(reply.indexOf('{'), reply.lastIndexOf('}') + 1)) as { answers?: unknown }
314
315/**
316 * Puts the answer step's answers on their rows; a sourced one lifts its confidence. An answered question leaves
317 * `pending`; one the model left out stays there for the next step.
318 */
319export const applyAnswers = (live: Live, questions: readonly string[], reply: string): Live => {
320  let lists: Record<string, unknown>
321  try {
322    const raw = parse(reply).answers
323    // A list by position only counts when it holds one entry per question: a short one would shift answers onto the wrong row.
324    lists = Array.isArray(raw) ? (raw.length === questions.length ? { ...raw } : {}) : raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
325  } catch {
326    return live
327  }
328  const found = new Map(questions.map((q, i) => [q, toAnswers(lists[i])] as const).filter(([, a]) => a.length > 0))
329  const swap = (q: Question): Question => {
330    const answers = found.get(q.question)
331    if (!answers) return q
332    const isSourced = answers.some(a => a.risk === 'sourced')
333    return { ...q, answers, confidence: isSourced ? Math.max(q.confidence ?? 1, 4) : q.confidence }
334  }
335  const pending = live.pending.filter(q => !found.has(q))
336  return { ...live, added: live.added.map(swap), next: live.next.map(swap), pending, phase: pending.length ? 'answering' : 'ready' }
337}
338
339/** The task for a read-only subagent that looks a question up in the repository while the meeting goes on. */
340export const lookupPrompt = (question: string, lang: Lang) => `Someone in a meeting just asked us: "${question}"
341Find the answer in this repository: search with Grep and Glob, then read what you find. Change nothing.
342Reply with a JSON object only: {"answers": [{"text": "", "risk": "sourced", "source": "path:line", "note": ""}]} with 1 to 3 answers, safest first, each with "risk":
343${answerRules('only for an answer a file you read carries; "source" is its path:line.')}
344${languageRule(lang)} "note" in English.`
345
346/** The answers in a subagent's reply; nothing when it is not the asked-for JSON. */
347export const parseAnswers = (reply: string): Answer[] => {
348  try {
349    return toAnswers(parse(reply).answers)
350  } catch {
351    return []
352  }
353}
354
355/** A finished lookup: no longer running, and its answers, if any, stand in for the question's own. */
356export const settleLookup = (live: Live, question: string, reply: string | null): Live => {
357  const answers = reply === null ? [] : parseAnswers(reply)
358  return {
359    ...live,
360    looking: live.looking.filter(q => q !== question),
361    deep: answers.length ? { ...live.deep, [question]: answers } : live.deep,
362  }
363}
364
365/** Name and email from `git var GIT_AUTHOR_IDENT`; null when the output is not that. */
366export const parseIdent = (out: string | null) => {
367  const m = /^(.+?) <([^>]+)>/.exec(out ?? '')
368  return m ? { name: m[1]!, email: m[2]! } : null
369}
370
371/** My last five commits on any branch, merges left out: what I worked on last, whatever the meeting asks. */
372export const logArgs = (email: string) => ['log', '--branches', '--remotes', '--no-merges', '-F', `--author=${email}`, '-n', '5', '--format=%h%x09%as%x09%s']
373
374export const parseLog = (out: string | null): Fact[] =>
375  (out ?? '')
376    .split('\n')
377    .map(line => line.split('\t'))
378    .filter(p => p.length >= 3 && p.slice(2).join('\t').trim())
379    .map(([sha, date, ...subject]) => ({ text: subject.join('\t').trim(), source: `commit ${sha}, ${date}` }))
380
381/** GitHub's https address of a repository from its origin remote; null for any other remote. */
382export const githubBase = (remote: string | null) => {
383  const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(remote ?? '')
384  return m ? `https://github.com/${m[1]}/${m[2]}` : null
385}
386
387/** What a source label points at: a URL, an issue in a named or the session's repository, or a file with its line. */
388export type SourceRef = { url: string } | { repo: string; issue: string } | { issue: string } | { path: string; line?: string }
389
390export const parseSource = (label: string): SourceRef | null => {
391  const url = /https:\/\/[^\s)]+/.exec(label)
392  if (url) return { url: url[0].replace(/[.,;]+$/, '') }
393  const ticket = /\b([\w.-]+\/[\w.-]+)#(\d+)\b/.exec(label)
394  if (ticket) return { repo: ticket[1]!, issue: ticket[2]! }
395  const own = /(?:^|\s)#(\d+)\b/.exec(label)
396  if (own) return { issue: own[1]! }
397  const file = /(?:^|[\s(])((?:[\w.-]+\/)*[\w-][\w.-]*\.[a-z]{1,6})(?::(\d+))?\b/i.exec(label)
398  return file ? { path: file[1]!, line: file[2] } : null
399}
400
types/index.d.ts 106 lines
1export type Risk = 'sourced' | 'vague' | 'commitment' | 'risky'
2export type Answer = { text: string; risk: Risk; note?: string; source?: string }
3/** Who a question heard in the meeting is for: me (by name, my ticket or my work), everyone, or someone else. */
4export type Addressee = 'me' | 'all' | 'other'
5export type Question = {
6  question: string
7  relevance: number
8  confidence?: number
9  who?: string
10  /** Who on our side answers; only when the material names them. */
11  answerer?: string
12  why?: string
13  answers: Answer[]
14  /** Words to look up in the repository, from a live step; not shown. */
15  search?: string[]
16  /** Who the question is for, as the model read the conversation; live rows only. */
17  to?: Addressee
18  /** Who asked, as a role or the first name heard in the call; nothing when unknown. Live rows only. */
19  asker?: string
20  /** When the row was heard or predicted, in ms since the epoch; live rows only. */
21  heardAt?: number
22}
23/** Something I certainly did, said as is in any meeting. */
24export type Fact = { text: string; source?: string }
25export type SourceKind = 'meeting' | 'repo' | 'ticket' | 'doc' | 'calendar' | 'other'
26export type Source = { kind: SourceKind; label: string }
27export type Lang = 'auto' | 'de' | 'en'
28/** Which model answers live and how hard it thinks: speed against depth. */
29export type Quality = 'fast' | 'balanced' | 'thorough'
30export type QuestionSet = {
31  title: string
32  mode: string
33  generatedAt: string
34  /** Strings in sets stored before sources had a kind. */
35  sources: (Source | string)[]
36  questions: Question[]
37  /** Language the questions and answers were written in. */
38  language?: 'de' | 'en'
39  /** The folder they were prepared in; source paths count from it. */
40  folder?: string
41  /** What I worked on most recently, newest first; sets from before 0.11 have none. */
42  recent?: Fact[]
43}
44
45/** Where listening stands, shown on the focus card: nothing heard yet, waiting for lines, reading them, writing answers, done. */
46export type Phase = 'idle' | 'listening' | 'detecting' | 'answering' | 'ready'
47
48export type Live = {
49  isOn: boolean
50  status: string
51  meeting: string | null
52  lines: number
53  /** When the transcript last grew, for the status line. */
54  changedAt: number
55  asked: string[]
56  current: string | null
57  added: Question[]
58  /** Predictions; they stay until asked, new ones join at the end. */
59  next: Question[]
60  /** Answers a repository lookup found for a question asked now, by question text; drawn instead of the question's own. */
61  deep: Record<string, Answer[]>
62  /** Questions a repository lookup is still running for. */
63  looking: string[]
64  /** My latest commits in the folder, read while listening. */
65  recent: Fact[]
66  /** Where the last listening step stands. */
67  phase: Phase
68  /** Live questions whose answers are still being written, by question text; the pane says "answering …" for them. */
69  pending: string[]
70  /** When `current` last changed: a fresh question is marked as such and the pane scrolls to it. */
71  currentAt: number
72  /** When the last model step ran; without a question mark or my name in the new lines, the next step waits. */
73  steppedAt: number
74}
75
76declare module 'claude-code' {
77  interface PluginState {
78    'great-question': {
79      set: QuestionSet | null
80      /** Question texts whose row is open; every row starts closed. */
81      open: string[]
82      /** The live rows as they stood when a row was opened; drawn instead of `live` until all rows close or the person takes the news. */
83      held: Pick<Live, 'next' | 'added'> | null
84      /** The second button row (language, sorting, view, export) is shown. */
85      more: boolean
86      /** A background agent is finding likely questions: when it started, for which occasion. */
87      preparing: { since: number; occasion: string; folder?: string } | null
88      /** Counts seconds while preparing, so the spinner turns. */
89      tick: number
90      /** Where sources point, by label; '' where nowhere. */
91      links: Record<string, string>
92      view: 'meeting' | 'practice'
93      sortBy: 'confidence' | 'likelihood'
94      lang: Lang
95      /** Model and effort of the live step, the repository answers and the ASKED NOW lookup. */
96      quality: Quality
97      live: Live
98      version: string
99      /** The set a fresh session found stored for its folder, offered on the start screen; null when there is none. */
100      previous: { title: string; count: number; generatedAt: string; folder: string } | null
101      /** Sections whose fold is the opposite of their default: 'safe', 'earlier', 'prepared', 'sources'. Listening folds all four; paused, 'prepared' and 'safe' stand open. */
102      toggled: string[]
103    }
104  }
105}
106