pi-bro 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/grill.ts CHANGED
@@ -101,106 +101,94 @@ export async function openGrillModal(
101
101
  ? "Agy inspection sandbox can still write project files. No-edits is prompt-only on Agy."
102
102
  : "";
103
103
 
104
- const runTurn = async (reply: string, replaced?: GrillTurn) => {
104
+ // Both interview turns and consolidations share a current backend snapshot and disclosure.
105
+ const prepareRun = async (signal: AbortSignal) => {
106
+ const [settings, preferences] = await Promise.all([readSettings(), readPreferences()]);
107
+ if (closed || signal.aborted) return;
108
+ const backend = capabilityBackend(settings, "btw");
109
+ activeBackend = backend;
110
+ refreshHeader();
111
+ modal.setNotice(permissionNotice(backend), thread.fullAccess || backend === "agy" ? "warning" : "info");
112
+ const selection = selectionForCapability(settings, "btw");
113
+ thread.model = selectionLabel(selection);
114
+ thread.preferences = Boolean(preferences);
115
+ modal.setModel(`${thread.model}${thread.preferences ? " · prefs" : ""}`);
116
+ return { backend, selection, preferences };
117
+ };
118
+
119
+ // Both operations share one model-call lifecycle. Only their prompts,
120
+ // progress presentation and completed results differ.
121
+ type Operation = { kind: "turn"; reply: string; replace: boolean } | { kind: "consolidate"; replace: boolean };
122
+ const runOperation = async (operation: Operation) => {
105
123
  if (controller || closed) return;
106
- thread.retry = { reply, replace: Boolean(replaced) };
124
+ if (operation.kind === "consolidate" && !thread.turns.length) {
125
+ modal.setNotice("Start the interview before consolidating.", "warning");
126
+ return;
127
+ }
128
+ const turn = operation.kind === "turn";
129
+ thread.retry = turn
130
+ ? { reply: operation.reply, replace: operation.replace }
131
+ : { consolidate: true, replace: operation.replace };
107
132
  const attempt = new AbortController();
108
133
  controller = attempt;
109
134
  modal.setRunning(true);
110
- pendingReply = reply;
135
+ if (turn) pendingReply = operation.reply;
111
136
  try {
112
- const [settings, preferences] = await Promise.all([readSettings(), readPreferences()]);
113
- if (closed || attempt.signal.aborted) return;
114
- const backend = capabilityBackend(settings, "btw");
115
- activeBackend = backend;
116
- refreshHeader();
117
- modal.setNotice(permissionNotice(backend), thread.fullAccess || backend === "agy" ? "warning" : "info");
118
- const selection = selectionForCapability(settings, "btw");
119
- thread.model = selectionLabel(selection);
120
- thread.preferences = Boolean(preferences);
121
- modal.setModel(`${thread.model}${thread.preferences ? " · prefs" : ""}`);
122
- if (!thread.context && !thread.turns.length) {
137
+ const prepared = await prepareRun(attempt.signal);
138
+ if (!prepared) return;
139
+ const { backend, selection, preferences } = prepared;
140
+ if (turn && !thread.context && !thread.turns.length)
123
141
  thread.context = captureShowTranscript(ctx, BTW_CONTEXT_TURNS, BTW_CONTEXT_MAX)?.text;
124
- }
125
- const history = replaced ? thread.turns.slice(0, -1) : [...thread.turns];
142
+
143
+ const history = operation.replace ? thread.turns.slice(0, -1) : [...thread.turns];
126
144
  const prompt = buildGrillPrompt({
127
- topic: thread.topic, reply, depth: thread.depth, context: thread.context,
128
- history, preferences, fullAccess: thread.fullAccess,
145
+ topic: thread.topic, depth: thread.depth, context: thread.context, history,
146
+ preferences, fullAccess: thread.fullAccess,
147
+ ...(turn ? { reply: operation.reply } : { consolidate: true }),
129
148
  });
130
- pendingTurn = { question: reply, answer: "…" };
131
- modal.setText(transcript());
132
- modal.scrollToEnd();
133
- const outcome = await executeBackend({
134
- ...grillExecution(thread.fullAccess), cwd: ctx.cwd, prompt,
135
- }, selection, attempt.signal, (event) => {
136
- if (!closed && !attempt.signal.aborted && event.kind === "text") {
137
- pendingTurn!.answer = event.text;
149
+ if (turn) {
150
+ pendingTurn = { question: operation.reply, answer: "…" };
151
+ modal.setText(transcript());
152
+ modal.scrollToEnd();
153
+ }
154
+ const outcome = await executeBackend(
155
+ { ...grillExecution(thread.fullAccess), cwd: ctx.cwd, prompt },
156
+ selection, attempt.signal, (event) => {
157
+ if (closed || attempt.signal.aborted || event.kind !== "text") return;
158
+ if (turn) pendingTurn!.answer = event.text;
159
+ else pendingSummary = event.text;
138
160
  modal.setText(transcript());
139
- }
140
- });
161
+ if (!turn) modal.scrollToEnd();
162
+ },
163
+ );
141
164
  if (closed || attempt.signal.aborted) return;
142
165
  if (outcome.status !== "success") throw new Error(outcome.message);
143
- if (replaced) thread.turns.pop();
144
- thread.turns.push({ question: reply, answer: outcome.text });
145
- modal.setNotice(permissionNotice(backend), thread.fullAccess || backend === "agy" ? "warning" : "info");
146
- delete thread.draft;
166
+ if (operation.replace) thread.turns.pop();
167
+ thread.turns.push({ question: turn ? operation.reply : "/consolidate", answer: outcome.text });
147
168
  delete thread.retry;
169
+ if (turn) {
170
+ delete thread.draft;
171
+ modal.setNotice(permissionNotice(backend), thread.fullAccess || backend === "agy" ? "warning" : "info");
172
+ } else {
173
+ modal.setNotice("Brief ready. Keep talking or use /copy.", "success");
174
+ }
148
175
  } catch (error) {
149
176
  if (!closed && !attempt.signal.aborted) {
150
177
  modal.setNotice(errorMessage(error), "error");
151
- if (!modal.getComposerText().trim()) modal.setComposerText(reply);
178
+ if (turn && !modal.getComposerText().trim()) modal.setComposerText(operation.reply);
152
179
  }
153
180
  } finally {
154
181
  pendingTurn = undefined;
182
+ pendingSummary = undefined;
155
183
  pendingReply = undefined;
156
184
  if (controller === attempt) controller = undefined;
157
185
  if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
158
186
  }
159
187
  };
160
188
 
161
- const consolidate = async (replace = false) => {
162
- if (controller || closed) return;
163
- if (!thread.turns.length) { modal.setNotice("Start the interview before consolidating.", "warning"); return; }
164
- thread.retry = { consolidate: true, replace };
165
- const attempt = new AbortController();
166
- controller = attempt;
167
- modal.setRunning(true);
168
- try {
169
- const [settings, preferences] = await Promise.all([readSettings(), readPreferences()]);
170
- if (closed || attempt.signal.aborted) return;
171
- activeBackend = capabilityBackend(settings, "btw");
172
- refreshHeader();
173
- modal.setNotice(permissionNotice(activeBackend), thread.fullAccess || activeBackend === "agy" ? "warning" : "info");
174
- const selection = selectionForCapability(settings, "btw");
175
- thread.model = selectionLabel(selection);
176
- thread.preferences = Boolean(preferences);
177
- modal.setModel(`${thread.model}${thread.preferences ? " · prefs" : ""}`);
178
- const prompt = buildGrillPrompt({
179
- topic: thread.topic, depth: thread.depth, context: thread.context,
180
- history: replace ? thread.turns.slice(0, -1) : thread.turns, preferences, consolidate: true, fullAccess: thread.fullAccess,
181
- });
182
- const outcome = await executeBackend({ ...grillExecution(thread.fullAccess), cwd: ctx.cwd, prompt },
183
- selection, attempt.signal, (event) => {
184
- if (!closed && !attempt.signal.aborted && event.kind === "text") {
185
- pendingSummary = event.text;
186
- modal.setText(transcript());
187
- modal.scrollToEnd();
188
- }
189
- });
190
- if (closed || attempt.signal.aborted) return;
191
- if (outcome.status !== "success") throw new Error(outcome.message);
192
- if (replace) thread.turns.pop();
193
- thread.turns.push({ question: "/consolidate", answer: outcome.text });
194
- delete thread.retry;
195
- modal.setNotice("Brief ready. Keep talking or use /copy.", "success");
196
- } catch (error) {
197
- if (!closed && !attempt.signal.aborted) modal.setNotice(errorMessage(error), "error");
198
- } finally {
199
- pendingSummary = undefined;
200
- if (controller === attempt) controller = undefined;
201
- if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
202
- }
203
- };
189
+ const runTurn = (reply: string, replaced?: GrillTurn) =>
190
+ runOperation({ kind: "turn", reply, replace: Boolean(replaced) });
191
+ const consolidate = (replace = false) => runOperation({ kind: "consolidate", replace });
204
192
 
205
193
  const copy = async () => {
206
194
  const text = thread.turns.at(-1)?.answer || "";
@@ -77,7 +77,7 @@ export function createOverthinkQuestionEditor(options: EditorOptions) {
77
77
  : scroller.view(list, rows),
78
78
  notice,
79
79
  hints: mode === "edit" ? "Enter apply · Esc cancel edit" :
80
- "↑/↓ select · Enter edit · Ctrl+N add · Ctrl+X delete · Alt+↑/↓ move · Ctrl+D reset · Ctrl+S save · Esc close",
80
+ "↑/↓ select · Enter edit · Ctrl+N add · Ctrl+X delete · Ctrl+↑/↓ move · Ctrl+D reset · Ctrl+S save · Esc close",
81
81
  fill: true,
82
82
  });
83
83
  },
@@ -108,11 +108,11 @@ export function createOverthinkQuestionEditor(options: EditorOptions) {
108
108
  questions.splice(cursor, 1); cursor = Math.min(cursor, Math.max(0, questions.length - 1));
109
109
  warn("Question removed from draft. Ctrl+S to save."); return;
110
110
  }
111
- if (matchesKey(data, "alt+up") && cursor > 0) {
111
+ if (matchesKey(data, "ctrl+up") && cursor > 0) {
112
112
  [questions[cursor - 1], questions[cursor]] = [questions[cursor]!, questions[cursor - 1]!];
113
113
  cursor--; tui.requestRender(); return;
114
114
  }
115
- if (matchesKey(data, "alt+down") && cursor < questions.length - 1) {
115
+ if (matchesKey(data, "ctrl+down") && cursor < questions.length - 1) {
116
116
  [questions[cursor + 1], questions[cursor]] = [questions[cursor]!, questions[cursor + 1]!];
117
117
  cursor++; tui.requestRender(); return;
118
118
  }
@@ -8,24 +8,29 @@ import { isRecord } from "./util.ts";
8
8
  export const OVERTHINK_ENTRY = "bro-overthink";
9
9
  export const OVERTHINK_DEFAULTS_FILE = "bro-overthink-defaults.json";
10
10
  export const FACTORY_QUESTIONS = [
11
- "Are we going in the right direction?",
12
- "Where are we now, where do we want to be, and where are we actually going?",
13
- "Are we solving the real problem, or just completing the tasks in front of us?",
14
- "What are we taking for granted that might be wrong?",
15
- "What important risks or failure modes are we overlooking?",
16
- "Have we drifted from the original intent or added complexity without enough value?",
17
- "What is the most useful correction or next move we can make now?",
11
+ "Are we solving the right problem and moving toward the intended outcome?",
12
+ "What important assumptions or conclusions might be wrong or insufficiently verified?",
13
+ "What material risks, unintended changes, or needless complexity have we introduced?",
14
+ "What correction, decision, or next step would most improve the outcome?",
18
15
  ] as const;
16
+ export const FACTORY_LENSES = ["Direction", "Evidence", "Risks", "Next move"] as const;
19
17
 
20
18
  export const MAX_OVERTHINK_QUESTIONS = 32;
21
19
  export const MAX_OVERTHINK_QUESTION_CHARS = 500;
22
- const MAX_NOTE_CHARS = 8000;
20
+ const MAX_NOTE_CHARS = 32000;
21
+ export type OverthinkAssessment = {
22
+ summary: string;
23
+ /** Questions at the moment of the check, not the potentially edited current list. */
24
+ questions: string[];
25
+ answers: string[];
26
+ };
23
27
  export type OverthinkUsage = { cacheRead?: number; cacheWrite?: number; input?: number; output?: number; reasoning?: number; costTotal?: number };
24
28
  export type OverthinkNote = {
25
29
  text: string; checkedAt: string; model: string; questionKey: string;
26
30
  /** Last model-relevant session entry at the time of the assessment. */
27
31
  sourcePosition?: string;
28
32
  usage?: OverthinkUsage;
33
+ assessment?: OverthinkAssessment;
29
34
  };
30
35
  export type OverthinkSession = { questions?: string[]; note?: OverthinkNote; initialized: boolean };
31
36
 
@@ -89,6 +94,22 @@ export function resolveOverthinkSession(branch: readonly SessionEntry[]): Overth
89
94
  }
90
95
  note.usage = usage;
91
96
  }
97
+ if (isRecord(data.assessment)) {
98
+ const candidate = data.assessment;
99
+ try {
100
+ const questions = checkQuestions(candidate.questions);
101
+ if (questions.length && typeof candidate.summary === "string" &&
102
+ candidate.summary.trim() && candidate.summary.length <= 1200 &&
103
+ Array.isArray(candidate.answers) && candidate.answers.length === questions.length &&
104
+ candidate.answers.every((a: unknown) => typeof a === "string" && a.trim().length > 0 && a.length <= 1200)) {
105
+ note.assessment = {
106
+ summary: candidate.summary.trim(),
107
+ questions,
108
+ answers: candidate.answers.map((a: string) => a.trim()),
109
+ };
110
+ }
111
+ } catch { /* Historical or damaged structured entry: keep its plain-text note. */ }
112
+ }
92
113
  state.note = note;
93
114
  }
94
115
  }
@@ -172,18 +193,60 @@ export function saveOverthinkNote(pi: ExtensionAPI, note: OverthinkNote): void {
172
193
  export function overthinkPrompt(questions: readonly string[]): string {
173
194
  return [
174
195
  "[Bro Overthink: private second look]",
175
- "Reassess the current work using the preceding Pi conversation as evidence. Consider these user-written questions:",
196
+ "Review the settled work using the preceding Pi conversation as evidence. The following are the user's questions, in order:",
176
197
  ...questions.map((q, i) => String(i + 1) + ". " + q),
177
- "Find only material points that could change the next decision or the quality of the work.",
178
- "Prefer direction, assumptions, evidence, risks, coherence, and the next useful move. Do not fabricate problems, demand checks for hypothetical edge cases, or restate concerns already clear in the last assistant reply.",
179
- "Write in the user's language. Keep it short: at most three specific findings with evidence and a useful next move. Answer in plain text only; do not call tools or take actions. No mandatory template or question-by-question answers.",
180
- "When nothing material is worth bringing up, return exactly NONE.",
198
+ "",
199
+ "First decide whether there is a consequential point the user could easily miss that could change their next decision or the quality of the work.",
200
+ "Flag an unchecked conclusion, important assumption, meaningful risk, unintended scope/complexity, or a better next move ONLY when supported by the conversation.",
201
+ "Do not repeat concerns already clearly addressed, raise routine caveats, invent problems or demand tests for hypothetical edge cases. Most checks should produce no notification.",
202
+ "If NOTHING material merits attention, reply with exactly NONE and nothing else.",
203
+ "If something material merits attention, answer EVERY numbered question in order, even if most have no concern. For unaffected questions, write 'No material concern found' in the user's language. Do not manufacture criticism to fill the sections.",
204
+ "Reply with exactly one valid JSON object, without Markdown fences or other text:",
205
+ JSON.stringify({ summary: "Two or three short sentences about the material finding and its consequence.",
206
+ answers: questions.map((_q, i) => "Concise answer to question " + (i + 1)) }),
207
+ "The answers array must have exactly " + questions.length + " strings, one per question. Use the user's language.",
208
+ "Keep each answer to one or two brief sentences; name the concrete evidence or next move where relevant. Avoid repeating the summary. No need to force a severity rating.",
209
+ "Respond in plain text JSON only; do not call tools or take actions.",
181
210
  ].join("\n");
182
211
  }
183
- export function parseOverthinkAnswer(text: string): string {
184
- const cleaned = text.replace(/\u001b\[[0-9;]*m/g, "").trim();
185
- if (/^none\.?$/i.test(cleaned)) return "";
186
- return cleaned.slice(0, MAX_NOTE_CHARS);
212
+
213
+ /** Reject incomplete/misaligned output instead of showing the wrong answer under a question. */
214
+ export function parseOverthinkAssessment(raw: string, questions: readonly string[]): OverthinkAssessment | undefined {
215
+ const cleaned = raw.replace(/\u001b\[[0-9;]*m/g, "").trim();
216
+ if (/^none\.?$/i.test(cleaned)) return undefined;
217
+ // Tolerate a code fence, but never rely on the model using one.
218
+ const json = cleaned.replace(/^```(?:json)?\s*\n?/i, "").replace(/\n?```$/,"").trim();
219
+ let data: unknown;
220
+ try { data = JSON.parse(json) as unknown; }
221
+ catch { throw new Error("Overthink returned invalid JSON; retry the assessment."); }
222
+ if (!isRecord(data) || typeof data.summary !== "string" ||
223
+ !data.summary.trim() || data.summary.length > 1200 ||
224
+ !Array.isArray(data.answers) || data.answers.length !== questions.length ||
225
+ data.answers.some((answer: unknown) => typeof answer !== "string" || !answer.trim() || answer.length > 1200)) {
226
+ throw new Error("Overthink must return a short summary and one answer for each configured question.");
227
+ }
228
+ const assessment: OverthinkAssessment = {
229
+ summary: data.summary.trim(),
230
+ questions: [...questions],
231
+ answers: data.answers.map((a: string) => a.trim()),
232
+ };
233
+ if (formatOverthinkAssessment(assessment).length > MAX_NOTE_CHARS) {
234
+ throw new Error("Overthink assessment exceeds the maximum note size.");
235
+ }
236
+ return assessment;
237
+ }
238
+
239
+ /** Markdown is both the copy payload and a readable fallback for older viewers. */
240
+ export function formatOverthinkAssessment(assessment: OverthinkAssessment): string {
241
+ return [
242
+ "## Summary",
243
+ assessment.summary,
244
+ ...assessment.questions.flatMap((question, i) => [
245
+ "",
246
+ "### " + (i + 1) + ". " + question,
247
+ assessment.answers[i] ?? "",
248
+ ]),
249
+ ].join("\n");
187
250
  }
188
251
 
189
252
  /** Only use provider-reported values; absence means unknown, never zero. */
package/src/overthink.ts CHANGED
@@ -6,7 +6,8 @@ import { matchesKey, wrapTextWithAnsi, type Component, type TUI } from "@earendi
6
6
  import { modalHeight, openBroOverlay, renderFrame, Scroller, formatNotice, type Theme } from "./modal-kit.ts";
7
7
  import { hasBroCustomUi } from "./ui-capabilities.ts";
8
8
  import {
9
- FACTORY_QUESTIONS, ensureOverthinkSession, overthinkPrompt, parseOverthinkAnswer,
9
+ FACTORY_QUESTIONS, FACTORY_LENSES, ensureOverthinkSession, overthinkPrompt,
10
+ parseOverthinkAssessment, formatOverthinkAssessment,
10
11
  questionKey, readAutomaticChecks, readGlobalQuestions, readOverthinkUsage, resolveOverthinkSession,
11
12
  overthinkContextPosition, overthinkIsStale,
12
13
  saveOverthinkNote, saveSessionQuestions, writeGlobalQuestions,
@@ -59,11 +60,19 @@ function noteWidget(ctx: CheckContext, note?: string): void {
59
60
 
60
61
  export function questionStatus(note: OverthinkNote | undefined, questions: string[], position?: string): string {
61
62
  if (!note) return "No assessment yet.";
62
- const changed = note.questionKey !== questionKey(questions) ? " · questions changed since check" : "";
63
+ const changed = note.questionKey !== questionKey(questions) ? " · questions changed" : "";
63
64
  const freshness = overthinkIsStale(note, position)
64
- ? (note.sourcePosition ? " · OUTDATED: conversation has changed since this check" : " · source position not recorded")
65
- : " · current for this session position";
66
- return "Checked: " + note.checkedAt + " · " + note.model + freshness + changed;
65
+ ? (note.sourcePosition ? " · OUTDATED (later work)" : " · source position not recorded")
66
+ : " · current";
67
+ // The full timestamp and provider usage remain in the saved note; show only
68
+ // what helps orient someone opening the viewer after a long work session.
69
+ return "Checked " + note.checkedAt.slice(0, 16).replace("T", " ") + " · " + note.model + freshness + changed;
70
+ }
71
+
72
+ /** A saved question snapshot keeps old notes aligned even after session edits. */
73
+ export function overthinkQuestionLabel(question: string, position: number): string {
74
+ const index = (FACTORY_QUESTIONS as readonly string[]).indexOf(question);
75
+ return (position + 1) + ". " + (index < 0 ? "Question" : FACTORY_LENSES[index]);
67
76
  }
68
77
 
69
78
  /** A reported zero may mean a miss OR a provider that does not support cache accounting. */
@@ -90,6 +99,7 @@ export function createOverthinkViewer(
90
99
  ) {
91
100
  return (tui: TUI, theme: Theme, _keys: unknown, done: (action: ViewerAction) => void): Component => {
92
101
  let help = false;
102
+ let showUsage = false;
93
103
  let busy = false;
94
104
  let closed = false;
95
105
  let notice = "";
@@ -115,34 +125,70 @@ export function createOverthinkViewer(
115
125
  render(width: number) {
116
126
  const { questions, note, position } = read();
117
127
  const inner = Math.max(1, width - 2);
118
- const body = help
119
- ? [
120
- "Overthink checks substantive Pi tasks automatically with the active session model.",
121
- "Results are private and never enter the main conversation.",
122
- "",
123
- "Ctrl+R Force a fresh check (even after a small task)",
124
- "Ctrl+E Edit this session's questions",
125
- "? Toggle help",
126
- "Ctrl+C Copy latest findings",
127
- "Esc Close / back from help",
128
- "",
129
- "No separate backend or model picker. Cached input is measured when the provider reports it.",
130
- ]
131
- : [
132
- questionStatus(note, questions, position),
133
- "Questions: " + questions.length + (questions.length ? "" : " (checks disabled)"),
134
- ...usageStatus(note),
135
- "",
136
- busy ? "Checking the current Pi session…" : note
137
- ? note.text || "No material concerns found in the last check."
138
- : "No assessment yet. Bro checks automatically after meaningful work. Ctrl+R forces one now.",
139
- ];
140
- const lines = body.flatMap(line => wrapTextWithAnsi(line, inner));
141
- return renderFrame(theme, width, modalHeight(tui), {
142
- header: () => theme.fg("accent", theme.bold("Bro · Overthink")) + (busy ? " · running" : ""),
128
+ const lines: string[] = [];
129
+ const add = (value: string, color?: "accent" | "muted") => {
130
+ const styled = color ? theme.fg(color, color === "accent" ? theme.bold(value) : value) : value;
131
+ lines.push(...wrapTextWithAnsi(styled, inner));
132
+ };
133
+ if (help) {
134
+ [
135
+ "Overthink checks settled substantial work using the same Pi model.",
136
+ "It stays private and only notifies about consequential new concerns.",
137
+ "",
138
+ "Ctrl+R Retry with the current session",
139
+ "Ctrl+E Edit session questions",
140
+ "U Show or hide detailed token/cache/estimated cost usage",
141
+ "? Toggle help",
142
+ "Ctrl+C Copy the assessment as Markdown",
143
+ "Esc Close / back from help",
144
+ ].forEach(value => add(value));
145
+ } else {
146
+ add(questionStatus(note, questions, position), "muted");
147
+ if (showUsage) {
148
+ add("");
149
+ add("Usage details", "accent");
150
+ usageStatus(note).forEach(value => add(value));
151
+ }
152
+ add("");
153
+ if (busy) {
154
+ add("Checking the current Pi session…");
155
+ } else if (!note) {
156
+ add("No assessment yet. Bro checks after substantial work; Ctrl+R checks now.");
157
+ } else if (!note.text) {
158
+ add("No material concerns found in the last check.");
159
+ } else if (note.assessment) {
160
+ add("Summary", "accent");
161
+ add(note.assessment.summary);
162
+ note.assessment.questions.forEach((question, i) => {
163
+ add("");
164
+ add(overthinkQuestionLabel(question, i), "accent");
165
+ add(question, "muted");
166
+ add(note.assessment!.answers[i] ?? "");
167
+ });
168
+ } else {
169
+ // Historical notes were one free-form paragraph; never pretend
170
+ // their text supplies one verified answer per newer question.
171
+ add("Earlier assessment (plain text)", "accent");
172
+ note.text.split("\n").forEach(line => add(line));
173
+ }
174
+ }
175
+ // The prior full-height viewer left a large blank rectangle below short
176
+ // notes. Cap the frame to real content, but preserve scroll for long notes.
177
+ const hints = "↑/↓ scroll · Ctrl+R retry · Ctrl+E questions · U usage · ? help · Ctrl+C copy · Esc close";
178
+ // renderFrame reserves 5 frame rows plus the *wrapped* shortcuts and
179
+ // notices. Count them before capping or short notes lose their last line.
180
+ const hintRows = wrapTextWithAnsi(hints, inner).length;
181
+ const noticeRows = notice ? Math.min(3, wrapTextWithAnsi(notice, inner).length) : 0;
182
+ const cap = Math.max(8, lines.length + 5 + hintRows + noticeRows);
183
+ return renderFrame(theme, width, modalHeight(tui, undefined, cap), {
184
+ header: () => theme.fg("accent", theme.bold("Bro · Overthink")) +
185
+ (busy ? " · running" : "") +
186
+ (!help ? " · " + questions.length + (questions.length === 1 ? " question" : " questions") : "") +
187
+ (scroller.indicator() ? " · " + scroller.indicator() : ""),
143
188
  body: (rows) => scroller.view(lines, rows),
144
189
  notice,
145
- hints: "↑/↓ scroll · Ctrl+R retry · Ctrl+E session questions · ? help · Ctrl+C copy · Esc close",
190
+ hints,
191
+ fill: false,
146
192
  });
147
193
  },
148
194
  invalidate() {},
@@ -153,6 +199,7 @@ export function createOverthinkViewer(
153
199
  return;
154
200
  }
155
201
  if (matchesKey(data, "?")) { help = !help; scroller.toStart(); tui.requestRender(); return; }
202
+ if (matchesKey(data, "u") || matchesKey(data, "shift+u")) { showUsage = !showUsage; scroller.toStart(); tui.requestRender(); return; }
156
203
  if (matchesKey(data, "ctrl+r")) { void rerun(); return; }
157
204
  if (matchesKey(data, "ctrl+c")) { void copy(); return; }
158
205
  if (matchesKey(data, "ctrl+e") && !busy) { closed = true; done("edit"); return; }
@@ -250,15 +297,19 @@ export function registerOverthink(pi: ExtensionAPI, loadAutomaticChecks = readAu
250
297
  if (answer.stopReason !== "stop") throw new Error("Model did not finish its assessment (" + answer.stopReason + ").");
251
298
  const currentQuestions = resolveOverthinkSession(ctx.sessionManager.getBranch()).questions ?? [];
252
299
  if (questionKey(currentQuestions) !== questionKey(questions)) throw new Error("Questions changed during check; stale result discarded.");
253
- const text = parseOverthinkAnswer(answer.content.filter(part => part.type === "text").map(part => part.text).join(""));
300
+ const assessment = parseOverthinkAssessment(
301
+ answer.content.filter(part => part.type === "text").map(part => part.text).join(""), questions,
302
+ );
303
+ const text = assessment ? formatOverthinkAssessment(assessment) : "";
254
304
  const usage = readOverthinkUsage(answer.usage);
255
305
  const note: OverthinkNote = {
256
306
  text, checkedAt: new Date().toISOString(), model: name, questionKey: questionKey(questions),
257
307
  ...(position ? { sourcePosition: position } : {}),
258
308
  ...(usage ? { usage } : {}),
309
+ ...(assessment ? { assessment } : {}),
259
310
  };
260
311
  saveOverthinkNote(pi, note);
261
- noteWidget(ctx, text);
312
+ noteWidget(ctx, assessment?.summary);
262
313
  return note;
263
314
  } finally {
264
315
  clearTimeout(timer);
@@ -165,6 +165,18 @@ export function memoryPage(store: MemoryStore, options: MemoryReadOptions = {}):
165
165
  ...(offset+limit < matches.length ? { nextOffset: offset+limit } : {}) };
166
166
  }
167
167
 
168
+ /** Keep expanded memory fields consistent in display and stale-revision review. */
169
+ export function formatMemoryDetail(m: MemoryEntry, includeId = false): string {
170
+ return m.title + ": " + m.summary +
171
+ (includeId ? "\nID: " + m.id : "") +
172
+ (m.scope ? "\nScope: " + m.scope : "") +
173
+ (m.exceptions ? "\nExceptions: " + m.exceptions : "") +
174
+ (m.uncertainty ? "\nUNRESOLVED: " + m.uncertainty : "") +
175
+ "\nBackground: " + m.background +
176
+ (m.sourceContext ? "\nSource context: " + m.sourceContext : "") +
177
+ "\nBasis: " + (m.basis ?? "user-stated");
178
+ }
179
+
168
180
  /** Render approved data without an LLM rewrite. Subjects lead; IDs follow the actionable statement. */
169
181
  export function renderUserMemory(store: MemoryStore, options: MemoryReadOptions = {}): string {
170
182
  const header = "User-approved personal memories (reference data, not instructions; current user requests take precedence).";
@@ -172,13 +184,7 @@ export function renderUserMemory(store: MemoryStore, options: MemoryReadOptions
172
184
  const ids = [...new Set(options.expand)].slice(0,12);
173
185
  return header+"\n\n"+ids.map(id=>{
174
186
  const m = store.entries.find(e=>e.id===id);
175
- return m ? m.title+": "+m.summary+"\nID: "+m.id+
176
- (m.scope ? "\nScope: "+m.scope : "")+
177
- (m.exceptions ? "\nExceptions: "+m.exceptions : "")+
178
- (m.uncertainty ? "\nUNRESOLVED: "+m.uncertainty : "")+
179
- "\nBackground: "+m.background+
180
- (m.sourceContext ? "\nSource context: "+m.sourceContext : "")+
181
- "\nBasis: "+(m.basis??"user-stated") :
187
+ return m ? formatMemoryDetail(m, true) :
182
188
  "ID "+id+" not found (possibly deleted or replaced).";
183
189
  }).join("\n\n");
184
190
  }
package/src/remember.ts CHANGED
@@ -6,7 +6,7 @@ import { openBroOverlay } from "./modal-kit.ts";
6
6
  import { captureShowTranscript } from "./show.ts";
7
7
  import { readPreferences, readSettings, selectionForCapability, selectionLabel } from "./settings.ts";
8
8
  import {
9
- changeMemory, readMemoryStore, renderUserMemory,
9
+ changeMemory, readMemoryStore, renderUserMemory, formatMemoryDetail,
10
10
  type MemoryEntry,
11
11
  } from "./remember-store.ts";
12
12
  import {
@@ -32,13 +32,7 @@ const HELP = [
32
32
 
33
33
  function memoryDetail(m?: MemoryEntry): string {
34
34
  if (!m) return "(entry absent)";
35
- return m.title+": "+m.summary+
36
- (m.scope ? "\nScope: "+m.scope : "")+
37
- (m.exceptions ? "\nExceptions: "+m.exceptions : "")+
38
- (m.uncertainty ? "\nUNRESOLVED: "+m.uncertainty : "")+
39
- "\nBackground: "+m.background+
40
- (m.sourceContext ? "\nSource context: "+m.sourceContext : "")+
41
- "\nBasis: "+(m.basis??"user-stated");
35
+ return formatMemoryDetail(m);
42
36
  }
43
37
 
44
38
  export async function openRememberModal(ctx: ExtensionCommandContext, initial = ""): Promise<void> {