@robhowley/pi-remembrancer 0.3.0 → 0.5.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.
@@ -4,6 +4,8 @@ import { StringEnum, Type } from '@earendil-works/pi-ai';
4
4
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
5
5
  import { CheckpointStore } from './checkpoints.js';
6
6
  import { loadRemembrancerConfig } from './config.js';
7
+ import { captureOutgoing, CAPTURE_BUDGET_MS } from './capture.js';
8
+ import { openProposals } from './proposal-ui.js';
7
9
  import { discoverSources } from './discovery.js';
8
10
  import {
9
11
  renderReviewCall,
@@ -13,7 +15,6 @@ import {
13
15
  } from './render.js';
14
16
  import { copyWarnings, warningMessages, type WarningRecord } from './warnings.js';
15
17
  import {
16
- branchEvidence,
17
18
  prepareReview,
18
19
  resolveSeedSince,
19
20
  ReviewBudget,
@@ -24,13 +25,21 @@ import {
24
25
  type Source,
25
26
  type Tip,
26
27
  } from './evidence.js';
27
-
28
- type Selected = {
29
- sessionId: string;
30
- branchId: string;
31
- entryId: string;
32
- editId: string | null;
33
- };
28
+ import {
29
+ boundedEvidencePage,
30
+ frozenContext,
31
+ groupEvidencePage,
32
+ serializedResponse,
33
+ type Selected,
34
+ } from './review-pages.js';
35
+
36
+ export {
37
+ REVIEW_RESPONSE_MAX_BYTES,
38
+ boundedEvidencePage,
39
+ groupEvidencePage,
40
+ type EvidencePageEntry,
41
+ type PageCursor,
42
+ } from './review-pages.js';
34
43
 
35
44
  type ReviewArgs = {
36
45
  action: 'begin' | 'next' | 'finish' | 'cancel' | 'context';
@@ -60,7 +69,7 @@ type Batch = {
60
69
 
61
70
  export const REMEMBRANCER_COMMAND_NAME = 'remembrancer';
62
71
  export const REMEMBRANCER_COMMAND_USAGE =
63
- 'Usage: /remembrancer seed <Nd>\n /remembrancer help';
72
+ 'Usage: /remembrancer seed <Nd>\n /remembrancer proposals\n /remembrancer help';
64
73
  export const REMEMBRANCER_HELP = [
65
74
  REMEMBRANCER_COMMAND_USAGE,
66
75
  'Seed saved-session evidence from a bounded historical window, then follow the Remembrancer skill.',
@@ -68,6 +77,7 @@ export const REMEMBRANCER_HELP = [
68
77
  ].join('\n');
69
78
 
70
79
  const REMEMBRANCER_SUBCOMMANDS = [
80
+ { value: 'proposals', label: 'proposals', description: 'Review stored task proposals locally' },
71
81
  {
72
82
  value: 'seed ',
73
83
  label: 'seed',
@@ -85,6 +95,7 @@ const REMEMBRANCER_SEED_DURATIONS = [
85
95
 
86
96
  type RemembrancerCommandArgs =
87
97
  | { ok: true; mode: 'help' }
98
+ | { ok: true; mode: 'proposals' }
88
99
  | { ok: true; mode: 'seed'; duration: string }
89
100
  | { ok: false; message: string };
90
101
 
@@ -94,6 +105,7 @@ export function parseRemembrancerCommandArgs(args: string): RemembrancerCommandA
94
105
 
95
106
  if (tokens.length === 0 || (subcommand === 'help' && tokens.length === 1))
96
107
  return { ok: true, mode: 'help' };
108
+ if (subcommand === 'proposals' && tokens.length === 1) return { ok: true, mode: 'proposals' };
97
109
  if (subcommand === 'help')
98
110
  return { ok: false, message: `Help does not accept arguments. ${REMEMBRANCER_COMMAND_USAGE}` };
99
111
  if (subcommand !== 'seed')
@@ -152,26 +164,16 @@ const selectedParameters = Type.Object({
152
164
  editId: Type.Union([Type.String(), Type.Null()]),
153
165
  });
154
166
 
155
- // Return every character, even when one message is larger than an entire page.
156
- function page(batch: Batch) {
157
- const entries = [];
158
- let remaining = 12000;
159
- while (remaining > 0 && entries.length < 40 && batch.index < batch.evidence.length) {
160
- const evidence = batch.evidence[batch.index];
161
- if (!evidence) break;
162
- const { text, ...source } = evidence;
163
- const start = batch.offset;
164
- const excerpt = text.slice(start, start + remaining);
165
- remaining -= excerpt.length;
166
- batch.offset += excerpt.length;
167
- const continues = batch.offset < text.length;
168
- entries.push({ ...source, text: excerpt, offset: start, continues });
169
- if (!continues) {
170
- batch.index++;
171
- batch.offset = 0;
172
- }
173
- }
174
- return { batch: batch.token, entries, hasMore: batch.index < batch.evidence.length };
167
+ function page(batch: Batch, envelope: Record<string, unknown> = {}) {
168
+ const result = boundedEvidencePage(batch.evidence, batch, (entries, cursor) => ({
169
+ batch: batch.token,
170
+ groups: groupEvidencePage(entries),
171
+ hasMore: cursor.index < batch.evidence.length,
172
+ ...envelope,
173
+ }));
174
+ batch.index = result.cursor.index;
175
+ batch.offset = result.cursor.offset;
176
+ return result.data;
175
177
  }
176
178
 
177
179
  function sourceKey(source: Pick<Source, 'sessionId' | 'file'>): string {
@@ -189,39 +191,6 @@ function usesDefaultSessionDir(ctx: ExtensionContext): boolean {
189
191
  return manager.usesDefaultSessionDir();
190
192
  }
191
193
 
192
- function contextPage(items: Evidence[], offset: number) {
193
- const total = items.reduce((length, item) => length + item.text.length, 0);
194
- if (offset > total) throw new Error('Context offset is beyond the requested range');
195
-
196
- const entries = [];
197
- let position = 0;
198
- let remaining = 12000;
199
- let written = 0;
200
- for (const item of items) {
201
- const end = position + item.text.length;
202
- if (offset >= end) {
203
- position = end;
204
- continue;
205
- }
206
- const localOffset = Math.max(0, offset - position);
207
- const text = item.text.slice(localOffset, localOffset + remaining);
208
- if (text.length === 0) break;
209
- entries.push({
210
- ...item,
211
- text,
212
- offset: localOffset,
213
- continues: localOffset + text.length < item.text.length,
214
- });
215
- written += text.length;
216
- remaining -= text.length;
217
- position = end;
218
- if (remaining === 0) break;
219
- }
220
-
221
- const nextOffset = offset + written < total ? offset + written : null;
222
- return { entries, nextOffset };
223
- }
224
-
225
194
  export default function remembrancer(pi: ExtensionAPI) {
226
195
  let db: CheckpointStore | undefined;
227
196
  let batch: Batch | undefined;
@@ -245,7 +214,7 @@ export default function remembrancer(pi: ExtensionAPI) {
245
214
 
246
215
  function result(data: object, details: ReviewResultDetails) {
247
216
  return {
248
- content: [{ type: 'text' as const, text: JSON.stringify(data) }],
217
+ content: [{ type: 'text' as const, text: serializedResponse(data) }],
249
218
  details,
250
219
  };
251
220
  }
@@ -263,7 +232,7 @@ export default function remembrancer(pi: ExtensionAPI) {
263
232
  }
264
233
 
265
234
  pi.registerCommand(REMEMBRANCER_COMMAND_NAME, {
266
- description: 'Start a bounded historical Remembrancer review',
235
+ description: 'Review stored task proposals or start a bounded historical review',
267
236
  getArgumentCompletions: getRemembrancerArgumentCompletions,
268
237
  handler: async (args, ctx) => {
269
238
  const parsed = parseRemembrancerCommandArgs(args);
@@ -282,6 +251,11 @@ export default function remembrancer(pi: ExtensionAPI) {
282
251
  );
283
252
  return;
284
253
  }
254
+ if (parsed.mode === 'proposals') {
255
+ if (ctx.mode !== 'tui') throw new Error('Task proposals require TUI mode');
256
+ await openProposals(ctx, store());
257
+ return;
258
+ }
285
259
  if (!ctx.isIdle()) {
286
260
  ctx.ui.notify(
287
261
  'Pi is busy. Wait for the current run to finish, then retry the seed command.',
@@ -367,79 +341,41 @@ export default function remembrancer(pi: ExtensionAPI) {
367
341
  : coverageChanged
368
342
  ? 'coverage-pending'
369
343
  : 'already-covered';
370
- return {
371
- ...page(batch),
344
+ return page(batch, {
372
345
  status,
373
346
  warnings,
374
347
  incomplete,
375
348
  coverageChanged,
376
349
  ...(requestedSince === null ? {} : { requestedSince }),
377
350
  capturedTips: batch.tips.length,
378
- };
351
+ });
379
352
  }
380
353
 
381
354
  function contextReview(args: ReviewArgs): object {
382
355
  if (!batch || args.batch !== batch.token)
383
356
  throw new Error('No matching open review in this Pi session.');
384
- const selected = args.selected;
385
- if (!selected) throw new Error('Context requires a selected evidence item.');
386
- const selectedEvidence = batch.evidence.find(
387
- (item) =>
388
- item.sessionId === selected.sessionId &&
389
- item.branchId === selected.branchId &&
390
- item.entryId === selected.entryId &&
391
- item.editId === selected.editId,
392
- );
393
- if (!selectedEvidence) throw new Error('Selected evidence is not in this review batch.');
394
-
395
- const snapshot = batch.snapshots.find(
396
- (candidate) =>
397
- candidate.source.sessionId === selected.sessionId &&
398
- resolve(candidate.source.file) === resolve(selectedEvidence.file),
399
- );
400
- if (!snapshot) throw new Error('Selected evidence snapshot is unavailable.');
401
-
402
- const branch = branchEvidence(
403
- snapshot.tree,
404
- {
405
- file: snapshot.source.file,
406
- sessionId: selected.sessionId,
407
- entryId: selected.branchId,
408
- },
409
- selectedEvidence.reviewedThrough,
410
- );
411
- const selectedIndex = branch.findIndex(
412
- (item) => item.entryId === selected.entryId && item.editId === selected.editId,
413
- );
414
- if (selectedIndex < 0) throw new Error('Selected evidence is not in the frozen branch.');
415
-
416
- const before = args.before ?? 1;
417
- const offset = args.offset ?? 0;
418
- if (!Number.isInteger(before) || before < 1 || before > 40)
419
- throw new Error('Context before must be an integer from 1 to 40.');
420
- if (!Number.isInteger(offset) || offset < 0)
421
- throw new Error('Context offset must be a nonnegative integer.');
422
-
423
- const items = branch.slice(Math.max(0, selectedIndex - before), selectedIndex);
424
- const paged = contextPage(items, offset);
425
- return {
426
- batch: batch.token,
427
- selected,
428
- contextOnly: true,
429
- entries: paged.entries,
430
- nextOffset: paged.nextOffset,
431
- };
357
+ return frozenContext(batch, batch.token, args);
432
358
  }
433
359
 
434
360
  pi.on('session_start', (_event, ctx) => {
435
361
  if (loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted()).disabled) return;
436
362
  registerReviewTool();
437
363
  enroll(ctx);
364
+ if (ctx.mode === 'tui') {
365
+ const count = store().proposalCount();
366
+ if (count) ctx.ui.notify(`${count} task proposals · /remembrancer proposals`, 'info');
367
+ }
438
368
  });
439
- pi.on('session_shutdown', () => {
440
- batch = undefined;
441
- db?.close();
442
- db = undefined;
369
+ pi.on('session_shutdown', async (_event, ctx) => {
370
+ const deadline = Date.now() + CAPTURE_BUDGET_MS;
371
+ try {
372
+ // Abandon manual coverage before capture claims the same process lock.
373
+ release();
374
+ await captureOutgoing(ctx, store, deadline);
375
+ } finally {
376
+ db?.close();
377
+ db = undefined;
378
+ }
443
379
  });
444
380
 
445
381
  function registerReviewTool() {
@@ -447,7 +383,7 @@ export default function remembrancer(pi: ExtensionAPI) {
447
383
  name: 'remembrancer_review',
448
384
  label: 'Remembrancer review',
449
385
  description:
450
- 'Read incremental cross-session evidence or finish a fully resolved review. Follow the remembrancer skill. Read every page before finishing.',
386
+ 'Read incremental cross-session evidence or finish a fully resolved review. Evidence is grouped by consecutive source and branch metadata. Each complete JSON response is capped at 50 KiB UTF-8. Follow the remembrancer skill and read every page before finishing.',
451
387
  renderCall: renderReviewCall,
452
388
  renderResult: renderReviewResult,
453
389
  parameters: Type.Object({
@@ -510,15 +446,9 @@ export default function remembrancer(pi: ExtensionAPI) {
510
446
  if (batch.index < batch.evidence.length)
511
447
  throw new Error('Read all evidence pages before finishing.');
512
448
 
513
- store().finish({
514
- sources: batch.stagedSources,
515
- sourceDefaults: batch.sourceDefaults,
516
- checkpoints: batch.checkpoints,
517
- });
518
449
  const reviewedTips = batch.tips.length;
519
450
  const finishedBatch = batch;
520
451
  const details = resultDetails('finish', finishedBatch);
521
- release();
522
452
  const response: Record<string, unknown> = { finished: true, reviewedTips };
523
453
  if (finishedBatch.requestedSince !== null || finishedBatch.incomplete) {
524
454
  response['coverageChanged'] = finishedBatch.coverageChanged;
@@ -532,7 +462,14 @@ export default function remembrancer(pi: ExtensionAPI) {
532
462
  if (finishedBatch.requestedSince !== null)
533
463
  response['requestedSince'] = finishedBatch.requestedSince;
534
464
  }
535
- return result(response, details);
465
+ const responseResult = result(response, details);
466
+ store().finish({
467
+ sources: finishedBatch.stagedSources,
468
+ sourceDefaults: finishedBatch.sourceDefaults,
469
+ checkpoints: finishedBatch.checkpoints,
470
+ });
471
+ release();
472
+ return responseResult;
536
473
  },
537
474
  });
538
475
  }
@@ -0,0 +1,275 @@
1
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { matchesKey, SelectList, Text } from '@earendil-works/pi-tui';
3
+ import type { CheckpointStore } from './checkpoints.js';
4
+ import { branchEvidence, readSession } from './evidence.js';
5
+ import { boundedEvidencePage } from './review-pages.js';
6
+ import { type Proposal, type ProposalDraft, validateDraft } from './proposals.js';
7
+ import {
8
+ applyProposal,
9
+ previewProposal,
10
+ requireTui,
11
+ resolveProposal,
12
+ type TaskExecutor,
13
+ type TaskPreview,
14
+ } from './taskwarrior.js';
15
+
16
+ // JSON preserves exact values without sending terminal controls (including C1) to the TUI.
17
+ function exact(value: unknown, indent?: number): string {
18
+ return Array.from(JSON.stringify(value ?? null, null, indent), (character) => {
19
+ const code = character.charCodeAt(0);
20
+ return code >= 0x7f && code <= 0x9f ? `\\u${code.toString(16).padStart(4, '0')}` : character;
21
+ }).join('');
22
+ }
23
+ function project(proposal: Proposal): string {
24
+ const draft = proposal.draft ?? proposal;
25
+ return (
26
+ (draft.change.operation !== 'complete' && draft.change.fields.project !== undefined
27
+ ? draft.change.fields.project
28
+ : draft.expected?.fields.project) ?? '(no project)'
29
+ );
30
+ }
31
+ function savedSourceText(source: Proposal['sources'][number]): string {
32
+ return `${source.role} ${exact(source.timestamp)} ${exact(source.locator)}\n${exact(source.quote)}\nFile: ${exact(source.file)}\nSession: ${exact(source.sessionId)}\nBranch: ${exact(source.branchId)}\nEntry: ${exact(source.entryId)}\nEdit: ${exact(source.editId)}\nExcerpt offset: ${source.offset}`;
33
+ }
34
+ // Called only by the deliberate Source action, never while rendering a preview.
35
+ export function sourceText(proposal: Proposal): string {
36
+ return proposal.sources
37
+ .map((source) => {
38
+ const saved = savedSourceText(source);
39
+ try {
40
+ const tree = readSession(source.file);
41
+ const branch = branchEvidence(tree, {
42
+ file: source.file,
43
+ sessionId: source.sessionId,
44
+ entryId: source.branchId,
45
+ });
46
+ const index = branch.findIndex(
47
+ (item) => item.entryId === source.entryId && item.editId === source.editId,
48
+ );
49
+ const selected = branch[index];
50
+ if (
51
+ !selected ||
52
+ selected.role !== source.role ||
53
+ selected.timestamp !== source.timestamp ||
54
+ selected.text.slice(source.offset, source.offset + source.quote.length) !== source.quote
55
+ )
56
+ throw new Error('Saved reference no longer matches');
57
+ const surrounding = branch.slice(Math.max(0, index - 2), index + 3);
58
+ const page = boundedEvidencePage(surrounding, { index: 0, offset: 0 }, (entries) => ({
59
+ entries,
60
+ }));
61
+ return `${saved}\n\nLocal context (up to two messages before and after, saved branch):\n${exact(page.data)}${page.cursor.index < surrounding.length ? '\nAdditional context omitted at the display limit.' : ''}`;
62
+ } catch {
63
+ return `${saved}\n\nExtra file context is unavailable: source missing, unreadable, over limits, or saved reference no longer matches.`;
64
+ }
65
+ })
66
+ .join('\n\n');
67
+ }
68
+ export function previewText(preview: TaskPreview): string {
69
+ const { proposal, task } = preview;
70
+ const draft = proposal.draft ?? proposal;
71
+ const change = draft.change;
72
+ const state =
73
+ proposal.state === 'applying' ? 'uncertain (unresolved applying claim)' : proposal.state;
74
+ const lines = [
75
+ `${change.operation.toUpperCase()} · ${state} · revision ${proposal.revision}`,
76
+ `Target: ${change.operation === 'add' ? (proposal.claim ?? '(new task)') : change.targetUuid}`,
77
+ `Description: ${exact(change.operation !== 'complete' && change.fields.description !== undefined ? change.fields.description : (task?.['description'] ?? draft.expected?.fields.description))}`,
78
+ `Project: ${exact(change.operation !== 'complete' && change.fields.project !== undefined ? change.fields.project : (task?.['project'] ?? '(no project)'))}`,
79
+ ];
80
+ if (change.operation !== 'complete')
81
+ for (const [field, value] of Object.entries(change.fields))
82
+ lines.push(`${field}: ${exact(task?.[field])} -> ${exact(value)}`);
83
+ lines.push(
84
+ `status: ${exact(task?.['status'])} -> ${exact(change.operation === 'complete' ? 'completed' : (task?.['status'] ?? 'pending'))}`,
85
+ );
86
+ lines.push(
87
+ `annotations: ${exact(task?.['annotations'] ?? [])}`,
88
+ `Append annotations (existing identical text is retained): ${exact(change.annotations)}`,
89
+ );
90
+ if (draft.question) lines.push(`Apply disabled: ${exact(draft.question)}`);
91
+ if (change.operation !== 'add' && !task) lines.push('Apply disabled: target missing');
92
+ lines.push(
93
+ `Why: ${exact(proposal.explanation)}`,
94
+ ...proposal.sources.map(
95
+ (source) =>
96
+ `${source.role} ${exact(source.timestamp)} ${exact(source.locator)}: ${exact(source.quote)}`,
97
+ ),
98
+ );
99
+ lines.push(`Current task: ${exact(task)}`);
100
+ if (proposal.draft)
101
+ lines.push('Edited draft. Press h for the saved proposal and revision history.');
102
+ if (proposal.result) lines.push(`Result: ${exact(proposal.result)}`);
103
+ if (['applying', 'uncertain'].includes(proposal.state))
104
+ lines.push(
105
+ 'No replay. Ctrl+A only verifies the current task and records already satisfied if it matches. Otherwise resolve the task manually.',
106
+ );
107
+ return lines.join('\n');
108
+ }
109
+ export async function openProposals(
110
+ ctx: ExtensionContext,
111
+ store: CheckpointStore,
112
+ execute?: TaskExecutor,
113
+ ): Promise<void> {
114
+ requireTui(ctx.mode);
115
+ let selected = 0;
116
+ let selectedId: string | undefined;
117
+ let message = '';
118
+ for (;;) {
119
+ requireTui(ctx.mode);
120
+ const proposals: Proposal[] = [];
121
+ for (let offset = 0; ; offset += 50) {
122
+ const page = store.proposals(undefined, offset, 50);
123
+ proposals.push(...page);
124
+ if (page.length < 50) break;
125
+ }
126
+ proposals.sort(
127
+ (a, b) =>
128
+ project(a).localeCompare(project(b)) ||
129
+ a.createdAt.localeCompare(b.createdAt) ||
130
+ a.id.localeCompare(b.id),
131
+ );
132
+ if (!proposals.length) {
133
+ ctx.ui.notify('No task proposals', 'info');
134
+ return;
135
+ }
136
+ if (selectedId)
137
+ selected = Math.max(
138
+ 0,
139
+ proposals.findIndex((item) => item.id === selectedId),
140
+ );
141
+ selected = Math.min(selected, proposals.length - 1);
142
+ const proposal = proposals[selected]!;
143
+ selectedId = proposal.id;
144
+ let preview: TaskPreview | undefined;
145
+ let previewError = '';
146
+ try {
147
+ preview = await previewProposal(store, proposal.id, execute);
148
+ } catch (error) {
149
+ previewError = String(error);
150
+ }
151
+ const action = await ctx.ui.custom<'apply' | 'edit' | 'dismiss' | 'navigate' | 'close'>(
152
+ (tui, theme, kb, done) => {
153
+ let detail: 'preview' | 'source' | 'history' = 'preview';
154
+ let sourceBody = '';
155
+ let scroll = 0;
156
+ let total = 0;
157
+ const list = new SelectList(
158
+ proposals.map((item) => {
159
+ const change = (item.draft ?? item).change;
160
+ return {
161
+ value: item.id,
162
+ label: `${exact(project(item))} · ${change.operation} · ${item.state === 'applying' ? 'uncertain' : item.state}`,
163
+ description: exact(
164
+ change.operation !== 'complete'
165
+ ? (change.fields.description ?? (item.draft ?? item).expected?.fields.description)
166
+ : (item.draft ?? item).expected?.fields.description,
167
+ ),
168
+ };
169
+ }),
170
+ 5,
171
+ {
172
+ selectedPrefix: (s) => theme.fg('accent', s),
173
+ selectedText: (s) => theme.fg('accent', s),
174
+ description: (s) => theme.fg('muted', s),
175
+ scrollInfo: (s) => theme.fg('dim', s),
176
+ noMatch: (s) => s,
177
+ },
178
+ );
179
+ list.setSelectedIndex(selected);
180
+ list.onSelectionChange = (item) => {
181
+ selectedId = item.value;
182
+ done('navigate');
183
+ };
184
+ list.onCancel = () => done('close');
185
+ return {
186
+ capturesViewportInput: true,
187
+ render(width: number) {
188
+ const body = new Text(
189
+ detail === 'source'
190
+ ? sourceBody
191
+ : detail === 'history'
192
+ ? `Saved proposal and revision history (drafts do not apply tasks):\n${exact(proposal, 2)}`
193
+ : preview
194
+ ? previewText(preview)
195
+ : `${exact(previewError)}\n${proposal.sources.map(savedSourceText).join('\n\n')}`,
196
+ 0,
197
+ 0,
198
+ ).render(width);
199
+ total = body.length;
200
+ scroll = Math.max(0, Math.min(scroll, Math.max(0, total - 12)));
201
+ return [
202
+ ...new Text(theme.fg('accent', 'Task proposals'), 0, 0).render(width),
203
+ ...list.render(width),
204
+ ...body.slice(scroll, scroll + 12),
205
+ ...new Text(
206
+ theme.fg(
207
+ 'dim',
208
+ `Details ${scroll + 1}-${Math.min(scroll + 12, total)}/${total} · PgUp/PgDn scroll\nCtrl+A Apply / verify unresolved · e Edit · d Dismiss · s Source · h History · Esc back/close\nEnter never applies. ${message ? exact(message) : ''}`,
209
+ ),
210
+ 0,
211
+ 0,
212
+ ).render(width),
213
+ ];
214
+ },
215
+ invalidate() {
216
+ list.invalidate();
217
+ },
218
+ handleInput(data: string) {
219
+ if (matchesKey(data, 'pageDown')) scroll += 12;
220
+ else if (matchesKey(data, 'pageUp')) scroll -= 12;
221
+ else if (data === 's') {
222
+ detail = detail === 'source' ? 'preview' : 'source';
223
+ if (detail === 'source') sourceBody = sourceText(proposal);
224
+ scroll = 0;
225
+ } else if (data === 'h') {
226
+ detail = detail === 'history' ? 'preview' : 'history';
227
+ scroll = 0;
228
+ } else if (detail !== 'preview' && kb.matches(data, 'tui.select.cancel')) {
229
+ detail = 'preview';
230
+ scroll = 0;
231
+ } else if (detail === 'preview' && matchesKey(data, 'ctrl+a')) done('apply');
232
+ else if (detail === 'preview' && data === 'e') done('edit');
233
+ else if (detail === 'preview' && data === 'd') done('dismiss');
234
+ else if (detail === 'preview' && !kb.matches(data, 'tui.select.confirm'))
235
+ list.handleInput(data);
236
+ tui.requestRender();
237
+ },
238
+ };
239
+ },
240
+ );
241
+ if (action === 'close') return;
242
+ message = '';
243
+ try {
244
+ requireTui(ctx.mode);
245
+ if (action === 'apply') {
246
+ if (!preview) throw new Error(previewError);
247
+ const resolved = ['applying', 'uncertain'].includes(preview.proposal.state)
248
+ ? await resolveProposal(store, preview, () => ctx.mode, execute)
249
+ : await applyProposal(store, preview, () => ctx.mode, execute);
250
+ message = resolved.state;
251
+ if (['applied', 'already_satisfied'].includes(resolved.state))
252
+ selectedId = proposals[Math.min(selected + 1, proposals.length - 1)]!.id;
253
+ } else if (action === 'dismiss') store.dismissProposal(proposal.id, proposal.revision);
254
+ else if (action === 'edit') {
255
+ if (proposal.state !== 'pending')
256
+ throw new Error(
257
+ 'Only pending proposals can be edited. Unresolved writes are never retried.',
258
+ );
259
+ const draft = proposal.draft ?? proposal;
260
+ const text = await ctx.ui.editor(
261
+ 'Edit proposal JSON (save draft only; dates use YYYYMMDDTHHMMSSZ)',
262
+ exact({ change: draft.change, expected: draft.expected, question: draft.question }, 2),
263
+ );
264
+ if (text !== undefined) {
265
+ const edited = JSON.parse(text) as ProposalDraft;
266
+ validateDraft(edited);
267
+ store.editProposal(proposal.id, proposal.revision, edited);
268
+ message = 'Draft saved. Review the new preview before applying.';
269
+ }
270
+ }
271
+ } catch (error) {
272
+ message = String(error);
273
+ }
274
+ }
275
+ }