@robhowley/pi-remembrancer 0.5.0 → 0.6.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.
Files changed (29) hide show
  1. package/README.md +59 -18
  2. package/extensions/remembrancer/capture-artifacts.ts +211 -0
  3. package/extensions/remembrancer/capture-handoff.ts +712 -0
  4. package/extensions/remembrancer/capture-jobs.ts +111 -0
  5. package/extensions/remembrancer/capture-matches.ts +145 -0
  6. package/extensions/remembrancer/capture-notices.ts +51 -0
  7. package/extensions/remembrancer/capture-publication-lock.mjs +37 -0
  8. package/extensions/remembrancer/capture-review.ts +84 -12
  9. package/extensions/remembrancer/capture-sizing.ts +63 -0
  10. package/extensions/remembrancer/capture-submission.ts +289 -0
  11. package/extensions/remembrancer/capture-worker-bootstrap.mjs +53 -0
  12. package/extensions/remembrancer/capture-worker.ts +336 -0
  13. package/extensions/remembrancer/capture.ts +259 -140
  14. package/extensions/remembrancer/checkpoints.ts +603 -116
  15. package/extensions/remembrancer/config.ts +31 -1
  16. package/extensions/remembrancer/evidence.ts +318 -74
  17. package/extensions/remembrancer/index.ts +281 -16
  18. package/extensions/remembrancer/private-sqlite.mjs +17 -0
  19. package/extensions/remembrancer/proposal-read.ts +227 -0
  20. package/extensions/remembrancer/proposal-ui.ts +597 -191
  21. package/extensions/remembrancer/proposals.ts +44 -9
  22. package/extensions/remembrancer/review-findings.ts +178 -0
  23. package/extensions/remembrancer/review-pages.ts +59 -17
  24. package/extensions/remembrancer/review-plan.ts +27 -0
  25. package/extensions/remembrancer/reviewer-budget.ts +53 -0
  26. package/extensions/remembrancer/reviewer.ts +176 -33
  27. package/extensions/remembrancer/taskwarrior.ts +111 -19
  28. package/package.json +5 -4
  29. package/skills/remembrancer/SKILL.md +36 -18
@@ -1,8 +1,14 @@
1
1
  import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
- import { matchesKey, SelectList, Text } from '@earendil-works/pi-tui';
2
+ import {
3
+ matchesKey,
4
+ sliceByColumn,
5
+ truncateToWidth,
6
+ visibleWidth,
7
+ wrapTextWithAnsi,
8
+ } from '@earendil-works/pi-tui';
3
9
  import type { CheckpointStore } from './checkpoints.js';
4
10
  import { branchEvidence, readSession } from './evidence.js';
5
- import { boundedEvidencePage } from './review-pages.js';
11
+ import { boundedEvidencePage, safePrefixLength } from './review-pages.js';
6
12
  import { type Proposal, type ProposalDraft, validateDraft } from './proposals.js';
7
13
  import {
8
14
  applyProposal,
@@ -28,100 +34,172 @@ function project(proposal: Proposal): string {
28
34
  : draft.expected?.fields.project) ?? '(no project)'
29
35
  );
30
36
  }
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}`;
37
+ function title(proposal: Proposal): string {
38
+ const draft = proposal.draft ?? proposal;
39
+ return (
40
+ (draft.change.operation !== 'complete' ? draft.change.fields.description : undefined) ??
41
+ draft.expected?.fields.description ??
42
+ '(untitled task)'
43
+ );
33
44
  }
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');
45
+ function decided(proposal: Proposal): boolean {
46
+ return ['applied', 'already_satisfied', 'dismissed'].includes(proposal.state);
47
+ }
48
+ const SOURCE_QUOTE_UNITS = 2048;
49
+ // One saved reference and quote fragment, independent of the optional original transcript.
50
+ // Called only by deliberate Source navigation, never while rendering a preview.
51
+ export function sourceText(proposal: Proposal, index = 0, page = 0): string {
52
+ const source = proposal.sources[index];
53
+ if (!source) return 'No saved sources.';
54
+ const start = safePrefixLength(source.quote, 0, Math.max(0, page * SOURCE_QUOTE_UNITS));
55
+ const end = safePrefixLength(source.quote, 0, Math.max(0, (page + 1) * SOURCE_QUOTE_UNITS));
56
+ const saved = `Evidence ${index + 1}/${proposal.sources.length} · quote units ${start}-${end}/${source.quote.length} (UTF-16)\n${exact(source.role)} ${exact(source.timestamp)} ${exact(source.locator)}\nSaved quote fragment (JSON, exact):\n${exact(source.quote.slice(start, end))}\nFile: ${exact(source.file)}\nSession: ${exact(source.sessionId)}\nBranch: ${exact(source.branchId)}\nEntry: ${exact(source.entryId)}\nEdit: ${exact(source.editId)}\nExcerpt offset: ${source.offset}`;
57
+ try {
58
+ const tree = readSession(source.file);
59
+ const branch = branchEvidence(tree, {
60
+ file: source.file,
61
+ sessionId: source.sessionId,
62
+ entryId: source.branchId,
63
+ });
64
+ const index = branch.findIndex(
65
+ (item) => item.entryId === source.entryId && item.editId === source.editId,
66
+ );
67
+ const selected = branch[index];
68
+ if (
69
+ !selected ||
70
+ selected.role !== source.role ||
71
+ selected.timestamp !== source.timestamp ||
72
+ selected.text.slice(source.offset, source.offset + source.quote.length) !== source.quote
73
+ )
74
+ throw new Error('Saved reference no longer matches');
75
+ const surrounding = branch
76
+ .slice(Math.max(0, index - 2), index + 3)
77
+ .filter((item) => item !== selected);
78
+ const contextStart = safePrefixLength(
79
+ selected.text,
80
+ 0,
81
+ Math.max(0, source.offset + start - 256),
82
+ );
83
+ const contextEnd = safePrefixLength(selected.text, 0, source.offset + end + 256);
84
+ const page = boundedEvidencePage(surrounding, { index: 0, offset: 0 }, (entries) => ({
85
+ selected: {
86
+ ...selected,
87
+ text: selected.text.slice(contextStart, contextEnd),
88
+ offset: contextStart,
89
+ continues: contextEnd < selected.text.length,
90
+ },
91
+ entries,
92
+ }));
93
+ return `${saved}\n\nLocal context (selected message window and 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.' : ''}`;
94
+ } catch {
95
+ return `${saved}\n\nExtra file context is unavailable: source missing, unreadable, over limits, or saved reference no longer matches.`;
96
+ }
97
+ }
98
+ function savedReviewText(proposal: Proposal): string {
99
+ const quote = proposal.sources[0]?.quote;
100
+ const end = quote === undefined ? 0 : safePrefixLength(quote, 0, 240);
101
+ return [
102
+ `Saved title (not live verification): ${exact(title(proposal))}`,
103
+ `Why: ${exact(proposal.explanation)}`,
104
+ `Evidence: ${proposal.sources.length} saved reference(s). Press s for full saved quotes.`,
105
+ ...(quote === undefined
106
+ ? []
107
+ : [
108
+ `Supporting quote${end < quote.length ? ' (shortened)' : ''}: ${exact(quote.slice(0, end))}${end < quote.length ? '…' : ''}`,
109
+ ]),
110
+ ].join('\n');
67
111
  }
68
112
  export function previewText(preview: TaskPreview): string {
69
113
  const { proposal, task } = preview;
70
114
  const draft = proposal.draft ?? proposal;
71
115
  const change = draft.change;
72
- const state =
73
- proposal.state === 'applying' ? 'uncertain (unresolved applying claim)' : proposal.state;
116
+ const unresolved = ['applying', 'uncertain'].includes(proposal.state);
117
+ const status =
118
+ change.operation === 'complete'
119
+ ? 'completed'
120
+ : unresolved
121
+ ? (proposal.applicationBefore?.status ?? draft.expected?.status ?? 'pending')
122
+ : (task?.['status'] ?? 'pending');
74
123
  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)'))}`,
124
+ `${change.operation.toUpperCase()} · ${exact(proposal.state)} · revision ${proposal.revision}`,
125
+ `Proposal ID: ${exact(proposal.id)}`,
126
+ `Target UUID: ${exact(change.operation === 'add' ? (proposal.claim ?? '(new task)') : change.targetUuid)}`,
79
127
  ];
128
+ if (task) {
129
+ lines.push(
130
+ `Current UUID: ${exact(task['uuid'])}`,
131
+ `Current task ID: ${exact(task['id'])}`,
132
+ `Current description: ${exact(task['description'])}`,
133
+ `Project: ${exact(task['project'] ?? '(no project)')} (current)`,
134
+ );
135
+ } else if (change.operation === 'add') lines.push('New task. No current target.');
136
+ else lines.push('Apply disabled: target missing');
137
+ if (draft.expected)
138
+ lines.push(
139
+ `Saved fallback description (not current): ${exact(draft.expected.fields.description)}`,
140
+ `Saved fallback project (not current): ${exact(draft.expected.fields.project)}`,
141
+ );
142
+ lines.push('Exact changes (current -> proposed replacement):');
80
143
  if (change.operation !== 'complete')
81
144
  for (const [field, value] of Object.entries(change.fields))
82
145
  lines.push(`${field}: ${exact(task?.[field])} -> ${exact(value)}`);
83
146
  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)}`,
147
+ `status: ${exact(task?.['status'])} -> ${exact(status)}`,
148
+ 'Unmentioned fields are retained. Null clears the named field.',
149
+ 'Append annotations (existing identical text is retained; no semantic deduplication):',
150
+ ...change.annotations.map((annotation, index) => `${index + 1}. ${exact(annotation)}`),
89
151
  );
152
+ if (!change.annotations.length) lines.push('(none)');
90
153
  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)}`);
154
+ lines.push(savedReviewText(proposal));
100
155
  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))
156
+ lines.push('Edited draft. Press i to inspect the saved proposal and current draft.');
157
+ if (proposal.result) {
158
+ lines.push(`Result: ${exact(proposal.result.state)}`);
159
+ if (proposal.result.error) lines.push(`Result error: ${exact(proposal.result.error)}`);
160
+ }
161
+ if (unresolved)
104
162
  lines.push(
105
- 'No replay. Ctrl+A only verifies the current task and records already satisfied if it matches. Otherwise resolve the task manually.',
163
+ 'Unresolved write. No replay. Ctrl+A is verification only: records already satisfied if the requested result is present. Otherwise resolve the task manually.',
106
164
  );
107
165
  return lines.join('\n');
108
166
  }
167
+
109
168
  export async function openProposals(
110
169
  ctx: ExtensionContext,
111
170
  store: CheckpointStore,
112
171
  execute?: TaskExecutor,
113
172
  ): Promise<void> {
114
173
  requireTui(ctx.mode);
174
+ let proposals: Proposal[] = [];
115
175
  let selected = 0;
116
- let selectedId: string | undefined;
176
+ let expanded = false;
177
+ let preview: TaskPreview | undefined;
178
+ let previewError = '';
179
+ let loading = false;
180
+ let request = 0;
117
181
  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;
182
+ type View = 'inbox' | 'source' | 'history' | 'inspection';
183
+ let view: View = 'inbox';
184
+ const offsets: Record<View, number> = { inbox: 0, source: 0, history: 0, inspection: 0 };
185
+ let sourceBody = '';
186
+ let sourceIndex = 0;
187
+ let sourcePage = 0;
188
+ let historySelected = 0;
189
+ let historyEntries: Proposal[] = [];
190
+ let inspectionProposal: Proposal | undefined;
191
+ let inspectionReturn: 'inbox' | 'history' = 'inbox';
192
+
193
+ function reload(refreshed?: Proposal) {
194
+ const id = inbox()[selected]?.id;
195
+ if (refreshed) proposals[proposals.findIndex((item) => item.id === refreshed.id)] = refreshed;
196
+ else {
197
+ proposals = [];
198
+ for (let offset = 0; ; offset += 50) {
199
+ const page = store.proposals(undefined, offset, 50);
200
+ proposals.push(...page);
201
+ if (page.length < 50) break;
202
+ }
125
203
  }
126
204
  proposals.sort(
127
205
  (a, b) =>
@@ -129,147 +207,475 @@ export async function openProposals(
129
207
  a.createdAt.localeCompare(b.createdAt) ||
130
208
  a.id.localeCompare(b.id),
131
209
  );
132
- if (!proposals.length) {
133
- ctx.ui.notify('No task proposals', 'info');
134
- return;
210
+ const index = inbox().findIndex((item) => item.id === id);
211
+ if (index >= 0) selected = index;
212
+ else {
213
+ selected = Math.max(0, Math.min(selected, inbox().length - 1));
214
+ collapse();
135
215
  }
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'>(
216
+ }
217
+ const inbox = () => proposals.filter((proposal) => !decided(proposal));
218
+ function collapse() {
219
+ expanded = false;
220
+ preview = undefined;
221
+ previewError = '';
222
+ loading = false;
223
+ request++;
224
+ offsets.inbox = 0;
225
+ }
226
+ reload();
227
+ for (;;) {
228
+ requireTui(ctx.mode);
229
+ const action = await ctx.ui.custom<'edit' | 'close'>(
152
230
  (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,
231
+ let active = true;
232
+ let busy = false;
233
+ let pageSize = 1;
234
+ let lastWidth = 1;
235
+ let lastColumns = 0;
236
+ let viable = false;
237
+ let reveal = true;
238
+
239
+ async function loadPreview() {
240
+ const proposal = inbox()[selected];
241
+ if (!proposal) return;
242
+ const token = ++request;
243
+ const id = proposal.id;
244
+ loading = true;
245
+ preview = undefined;
246
+ previewError = '';
247
+ tui.requestRender();
248
+ try {
249
+ requireTui(ctx.mode);
250
+ const loaded = await previewProposal(store, id, execute);
251
+ if (!active || request !== token || !expanded || inbox()[selected]?.id !== id) return;
252
+ reload(loaded.proposal);
253
+ if (!expanded) {
254
+ reveal = true;
255
+ tui.requestRender();
256
+ } else preview = loaded;
257
+ } catch (error) {
258
+ if (!active || request !== token || !expanded || inbox()[selected]?.id !== id) return;
259
+ previewError = String(error);
260
+ } finally {
261
+ if (active && request === token) {
262
+ loading = false;
263
+ tui.requestRender();
264
+ }
265
+ }
266
+ }
267
+ function expand() {
268
+ expanded = true;
269
+ offsets.inbox = 0;
270
+ void loadPreview();
271
+ }
272
+ function openHistory() {
273
+ historyEntries = proposals.filter(decided);
274
+ historySelected = 0;
275
+ offsets.history = 0;
276
+ view = 'history';
277
+ reveal = true;
278
+ }
279
+ function showSource() {
280
+ const proposal = inbox()[selected];
281
+ if (!proposal) return;
282
+ sourceBody = sourceText(proposal, sourceIndex, sourcePage);
283
+ offsets.source = 0;
284
+ view = 'source';
285
+ }
286
+ function moveSource(direction: number, referenceOnly: boolean) {
287
+ const proposal = inbox()[selected];
288
+ const source = proposal?.sources[sourceIndex];
289
+ if (!proposal || !source) return;
290
+ const lastPage = Math.max(0, Math.ceil(source.quote.length / SOURCE_QUOTE_UNITS) - 1);
291
+ if (referenceOnly) {
292
+ const next = Math.max(
197
293
  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) : ''}`,
294
+ Math.min(proposal.sources.length - 1, sourceIndex + direction),
295
+ );
296
+ if (next === sourceIndex) return;
297
+ sourceIndex = next;
298
+ sourcePage = 0;
299
+ } else if (sourcePage + direction >= 0 && sourcePage + direction <= lastPage)
300
+ sourcePage += direction;
301
+ else {
302
+ const next = sourceIndex + direction;
303
+ if (next < 0 || next >= proposal.sources.length) return;
304
+ sourceIndex = next;
305
+ const quote = proposal.sources[next]!.quote;
306
+ sourcePage =
307
+ direction > 0 ? 0 : Math.max(0, Math.ceil(quote.length / SOURCE_QUOTE_UNITS) - 1);
308
+ }
309
+ showSource();
310
+ }
311
+ function inspect(proposal: Proposal, back: 'inbox' | 'history') {
312
+ inspectionProposal = proposal;
313
+ inspectionReturn = back;
314
+ offsets.inspection = 0;
315
+ view = 'inspection';
316
+ }
317
+ // Only service/store results establish a decided outcome. An unresolved item stays here.
318
+ function outcome(result: Proposal) {
319
+ message =
320
+ result.state === 'applied'
321
+ ? 'Applied and verified.'
322
+ : result.state === 'already_satisfied'
323
+ ? 'Already satisfied. No task write performed.'
324
+ : result.state === 'dismissed'
325
+ ? 'Dismissed. Task unchanged.'
326
+ : `Unresolved (${result.state}). No automatic retry; inspect the result.`;
327
+ reload();
328
+ if (!expanded) reveal = true;
329
+ }
330
+ async function authorize() {
331
+ if (!preview || loading || busy) return;
332
+ const approved = preview;
333
+ busy = true;
334
+ message = ['applying', 'uncertain'].includes(approved.proposal.state)
335
+ ? 'Verifying only. No write will be replayed.'
336
+ : 'Applying this proposal and verifying the result…';
337
+ tui.requestRender();
338
+ try {
339
+ requireTui(ctx.mode);
340
+ const result = ['applying', 'uncertain'].includes(approved.proposal.state)
341
+ ? await resolveProposal(store, approved, () => ctx.mode, execute)
342
+ : await applyProposal(store, approved, () => ctx.mode, execute);
343
+ outcome(result);
344
+ } catch (error) {
345
+ message = String(error);
346
+ // A claim may have persisted before an error. Refresh, never replay or discard it.
347
+ reload();
348
+ if (!expanded) reveal = true;
349
+ } finally {
350
+ busy = false;
351
+ if (expanded) await loadPreview();
352
+ tui.requestRender();
353
+ }
354
+ }
355
+ // Editor save reopens expanded, but the previous custom component no longer owns input.
356
+ if (expanded && !preview && !loading) void loadPreview();
357
+
358
+ const component = {
359
+ render(width: number): string[] {
360
+ lastWidth = width;
361
+ lastColumns = tui.terminal.columns;
362
+ const height = Math.max(1, tui.terminal.rows - 2);
363
+ const inner = Math.max(1, width - 2);
364
+ const bodyWidth = Math.max(1, inner - 1);
365
+ const wrap = (text: string) => wrapTextWithAnsi(text, inner);
366
+ const queue = inbox();
367
+ const proposal = queue[selected];
368
+ const summary = (item: Proposal, focused: boolean) => {
369
+ const change = (item.draft ?? item).change;
370
+ const effect =
371
+ change.operation === 'complete'
372
+ ? 'complete task'
373
+ : change.operation === 'add'
374
+ ? 'add task'
375
+ : `replace ${
376
+ Object.entries(change.fields)
377
+ .map(([field, value]) => `${field}=${exact(value)}`)
378
+ .join(', ') || 'no fields'
379
+ }`;
380
+ return [
381
+ truncateToWidth(`${focused ? '>' : ' '} ${exact(title(item))}`, inner),
382
+ truncateToWidth(
383
+ ` ${exact(project(item))} · ${exact(item.state)} · proposed ${effect}; ${change.annotations.length} annotation(s)`,
384
+ inner,
385
+ ),
386
+ ];
387
+ };
388
+ const header = wrap(
389
+ `Task proposals · ${view === 'inbox' ? 'Inbox' : view === 'source' ? 'Source' : view === 'history' ? 'History' : 'Proposal inspection'} · ${queue.length} Inbox · ${proposals.filter(decided).length} decided`,
390
+ );
391
+ if (view === 'inbox' && expanded && proposal) header.push(...summary(proposal, true));
392
+ if (view === 'source' && proposal?.sources[sourceIndex])
393
+ header.push(
394
+ ...wrap(
395
+ `Evidence ${sourceIndex + 1}/${proposal.sources.length} · quote page ${sourcePage + 1}/${Math.max(1, Math.ceil(proposal.sources[sourceIndex]!.quote.length / SOURCE_QUOTE_UNITS))}`,
209
396
  ),
210
- 0,
211
- 0,
212
- ).render(width),
397
+ );
398
+ let controls: string;
399
+ if (view === 'history')
400
+ controls =
401
+ '↑/↓ Select · Enter Inspect · PgUp/PgDn Scroll · Esc Back\nRead-only. No task writes.';
402
+ else if (view === 'source')
403
+ controls =
404
+ '←/→ Quote page · ↑/↓ Reference · PgUp/PgDn Scroll · Esc Back\nRead-only. No task writes.';
405
+ else if (view === 'inspection')
406
+ controls = 'PgUp/PgDn Scroll · Esc Back\nRead-only. No task writes.';
407
+ else {
408
+ controls = queue.length
409
+ ? `↑/↓ Focus · Enter ${expanded ? 'Collapse' : 'Expand'} · PgUp/PgDn Scroll\nCtrl+A ${!expanded ? 'Review' : loading ? 'Loading review' : !preview ? 'Preview unavailable' : ['applying', 'uncertain'].includes(preview.proposal.state) ? 'Verify only (no replay)' : 'Apply'}`
410
+ : 'Inbox empty.';
411
+ if (proposal?.state === 'pending') controls += ' · e Edit · d Dismiss';
412
+ if (proposal) controls += ' · s Source · i Inspect';
413
+ controls += ` · h History · Esc ${expanded ? 'Back' : 'Close'}\nEnter never applies.`;
414
+ }
415
+ const footer = wrap(controls);
416
+ const feedback = message ? wrap(`Feedback: ${exact(message)}`) : [];
417
+ const fixedFeedback =
418
+ feedback.length > 3
419
+ ? [...feedback.slice(0, 2), ...wrap('Full feedback is in the body.')]
420
+ : feedback;
421
+ let body: string[] = [];
422
+ let focusLine = 0;
423
+ if (view === 'source')
424
+ body = wrapTextWithAnsi(sourceBody || 'No saved sources.', bodyWidth);
425
+ else if (view === 'inspection') {
426
+ const saved = inspectionProposal;
427
+ body = wrapTextWithAnsi(
428
+ saved
429
+ ? `Saved proposal and current draft (read-only):\n${exact(
430
+ {
431
+ id: saved.id,
432
+ revision: saved.revision,
433
+ state: saved.state,
434
+ change: saved.change,
435
+ expected: saved.expected,
436
+ question: saved.question,
437
+ draft: saved.draft,
438
+ explanation: saved.explanation,
439
+ result: saved.result,
440
+ },
441
+ 2,
442
+ )}\nEvidence: ${saved.sources.length} saved reference(s).`
443
+ : 'No saved proposal.',
444
+ bodyWidth,
445
+ );
446
+ } else if (view === 'history') {
447
+ body.push('Decided proposals');
448
+ if (!historyEntries.length) body.push('(none)');
449
+ for (const [index, entry] of historyEntries.entries()) {
450
+ if (index === historySelected) focusLine = body.length;
451
+ body.push(
452
+ truncateToWidth(
453
+ `${index === historySelected ? '>' : ' '} revision ${entry.revision} · ${exact(entry.state)} · ${exact(title(entry))}`,
454
+ bodyWidth,
455
+ ),
456
+ );
457
+ }
458
+ } else if (expanded && proposal) {
459
+ body = wrapTextWithAnsi(
460
+ preview
461
+ ? previewText(preview)
462
+ : `${loading ? 'Loading current target…' : `Preview unavailable: ${exact(previewError)}`}\n${savedReviewText(proposal)}\nSaved proposed change (not verified): ${exact((proposal.draft ?? proposal).change, 2)}\nSaved unresolved question: ${exact((proposal.draft ?? proposal).question)}`,
463
+ bodyWidth,
464
+ );
465
+ } else {
466
+ body = queue.length
467
+ ? queue.flatMap((item, index) => summary(item, index === selected))
468
+ : ['No proposals in Inbox. History remains available.'];
469
+ focusLine = selected * 2;
470
+ }
471
+ if (feedback.length > 3) {
472
+ const fullFeedback = wrapTextWithAnsi(`Full feedback: ${exact(message)}`, bodyWidth);
473
+ body.push('', ...fullFeedback);
474
+ }
475
+ // Keep collapsed summaries whole at both paging endpoints.
476
+ if (view === 'inbox' && !expanded && body.length % 2) body.push('');
477
+ // Reserve the longest range cue before allocating the single local viewport.
478
+ const cueRows = wrap(
479
+ `Rows ${body.length}-${body.length}/${body.length} · above · more below`,
480
+ ).length;
481
+ pageSize = Math.max(
482
+ 1,
483
+ height - 2 - header.length - fixedFeedback.length - footer.length - cueRows,
484
+ );
485
+ viable =
486
+ width >= 28 &&
487
+ height >= 12 &&
488
+ pageSize >= 4 &&
489
+ 2 + header.length + fixedFeedback.length + footer.length + cueRows + 4 <= height;
490
+ if (!viable) {
491
+ return wrapTextWithAnsi(
492
+ 'Resize terminal to review safely. Application blocked. Esc back/close.',
493
+ Math.max(1, width),
494
+ ).slice(0, height);
495
+ }
496
+ if (view === 'inbox' && !expanded) pageSize = Math.max(2, pageSize - (pageSize % 2));
497
+ const maxOffset = Math.max(0, body.length - pageSize);
498
+ let offset = Math.max(0, Math.min(offsets[view], maxOffset));
499
+ if (reveal && ((view === 'inbox' && !expanded) || view === 'history')) {
500
+ const focusEnd = focusLine + (view === 'inbox' ? 2 : 1);
501
+ if (focusLine < offset) offset = focusLine;
502
+ else if (focusEnd > offset + pageSize) offset = focusEnd - pageSize;
503
+ offset = Math.max(0, Math.min(offset, maxOffset));
504
+ }
505
+ reveal = false;
506
+ offsets[view] = offset;
507
+ const thumbSize = Math.max(
508
+ 1,
509
+ Math.floor(pageSize * Math.min(1, pageSize / Math.max(1, body.length))),
510
+ );
511
+ const thumbStart = maxOffset
512
+ ? Math.round((offset / maxOffset) * (pageSize - thumbSize))
513
+ : 0;
514
+ const rows = Array.from({ length: pageSize }, (_, index) => {
515
+ const line = sliceByColumn(body[offset + index] ?? '', 0, bodyWidth, true);
516
+ const track = index >= thumbStart && index < thumbStart + thumbSize ? '█' : '│';
517
+ return (
518
+ line +
519
+ ' '.repeat(Math.max(0, bodyWidth - visibleWidth(line))) +
520
+ theme.fg('dim', track)
521
+ );
522
+ });
523
+ const cue = wrap(
524
+ `Rows ${body.length ? offset + 1 : 0}-${Math.min(offset + pageSize, body.length)}/${body.length} · ${offset ? 'above · ' : ''}${offset < maxOffset ? 'more below' : 'end'}`,
525
+ );
526
+ while (cue.length < cueRows) cue.push('');
527
+ const row = (line: string) => {
528
+ const clipped = sliceByColumn(line, 0, inner, true);
529
+ return (
530
+ theme.fg('border', '│') +
531
+ clipped +
532
+ ' '.repeat(Math.max(0, inner - visibleWidth(clipped))) +
533
+ theme.fg('border', '│')
534
+ );
535
+ };
536
+ return [
537
+ theme.fg('border', `╭${'─'.repeat(inner)}╮`),
538
+ ...header.map((line) => row(theme.fg('accent', line))),
539
+ ...fixedFeedback.map((line) => row(theme.fg('muted', line))),
540
+ ...rows.map(row),
541
+ ...cue.map((line) => row(theme.fg('dim', line))),
542
+ ...footer.map((line) => row(theme.fg('dim', line))),
543
+ theme.fg('border', `╰${'─'.repeat(inner)}╯`),
213
544
  ];
214
545
  },
215
- invalidate() {
216
- list.invalidate();
546
+ invalidate() {},
547
+ dispose() {
548
+ active = false;
549
+ request++;
550
+ loading = false;
217
551
  },
218
552
  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);
553
+ if (!active || busy) return;
554
+ const queue = inbox();
555
+ const proposal = queue[selected];
556
+ if (kb.matches(data, 'tui.select.cancel')) {
557
+ if (view === 'inspection') view = inspectionReturn;
558
+ else if (view !== 'inbox') view = 'inbox';
559
+ else if (expanded) {
560
+ collapse();
561
+ reveal = true;
562
+ } else {
563
+ active = false;
564
+ request++;
565
+ done('close');
566
+ return;
567
+ }
568
+ } else {
569
+ // Let Pi resolve the overlay width after a resize, then re-budget for this input.
570
+ if (lastColumns !== tui.terminal.columns) tui.renderNow();
571
+ component.render(lastWidth);
572
+ if (!viable) return;
573
+ if (matchesKey(data, 'pageDown')) offsets[view] += pageSize;
574
+ else if (matchesKey(data, 'pageUp')) offsets[view] -= pageSize;
575
+ else if (view === 'source' && (matchesKey(data, 'left') || matchesKey(data, 'right')))
576
+ moveSource(matchesKey(data, 'left') ? -1 : 1, false);
577
+ else if (kb.matches(data, 'tui.select.up') || kb.matches(data, 'tui.select.down')) {
578
+ const direction = kb.matches(data, 'tui.select.up') ? -1 : 1;
579
+ if (view === 'inbox') {
580
+ const next = Math.max(0, Math.min(queue.length - 1, selected + direction));
581
+ if (queue.length && next !== selected) {
582
+ selected = next;
583
+ collapse();
584
+ reveal = true;
585
+ }
586
+ } else if (view === 'source') moveSource(direction, true);
587
+ else if (view === 'history') {
588
+ historySelected = Math.max(
589
+ 0,
590
+ Math.min(historyEntries.length - 1, historySelected + direction),
591
+ );
592
+ reveal = true;
593
+ }
594
+ } else if (kb.matches(data, 'tui.select.confirm')) {
595
+ if (view === 'history' && historyEntries.length) {
596
+ inspect(historyEntries[historySelected]!, 'history');
597
+ } else if (view === 'inbox' && proposal) {
598
+ if (expanded) {
599
+ collapse();
600
+ reveal = true;
601
+ } else expand();
602
+ }
603
+ } else if (view === 'inbox') {
604
+ if (matchesKey(data, 'ctrl+a') && proposal) {
605
+ if (!expanded) expand();
606
+ else if (preview && !loading) void authorize();
607
+ } else if (data === 's' && proposal) {
608
+ sourceIndex = 0;
609
+ sourcePage = 0;
610
+ showSource();
611
+ } else if (data === 'i' && proposal) inspect(proposal, 'inbox');
612
+ else if (data === 'h') openHistory();
613
+ else if (data === 'e' && proposal?.state === 'pending') {
614
+ active = false;
615
+ request++;
616
+ loading = false;
617
+ done('edit');
618
+ return;
619
+ } else if (data === 'd' && proposal?.state === 'pending') {
620
+ const focusLine = selected * 2;
621
+ if (
622
+ !expanded &&
623
+ (focusLine < offsets.inbox || focusLine + 2 > offsets.inbox + pageSize)
624
+ ) {
625
+ reveal = true;
626
+ tui.requestRender();
627
+ return;
628
+ }
629
+ try {
630
+ requireTui(ctx.mode);
631
+ outcome(store.dismissProposal(proposal.id, proposal.revision));
632
+ } catch (error) {
633
+ message = String(error);
634
+ reload();
635
+ if (expanded) void loadPreview();
636
+ else reveal = true;
637
+ }
638
+ }
639
+ }
640
+ }
236
641
  tui.requestRender();
237
642
  },
238
643
  };
644
+ return component;
239
645
  },
646
+ { overlay: true, overlayOptions: { width: '100%', maxHeight: '100%', margin: 1 } },
240
647
  );
241
- if (action === 'close') return;
242
- message = '';
648
+ if (action !== 'edit') return;
649
+ const proposal = inbox()[selected];
650
+ if (!proposal || proposal.state !== 'pending') continue;
243
651
  try {
244
652
  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),
653
+ const draft = proposal.draft ?? proposal;
654
+ const text = await ctx.ui.editor(
655
+ 'Edit proposal JSON (save draft only; dates use YYYYMMDDTHHMMSSZ)',
656
+ exact({ change: draft.change, expected: draft.expected, question: draft.question }, 2),
657
+ );
658
+ if (text !== undefined) {
659
+ requireTui(ctx.mode);
660
+ const edited = JSON.parse(text) as ProposalDraft;
661
+ validateDraft(edited);
662
+ const saved = store.editProposal(proposal.id, proposal.revision, edited);
663
+ reload();
664
+ selected = Math.max(
665
+ 0,
666
+ inbox().findIndex((item) => item.id === saved.id),
263
667
  );
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
- }
668
+ expanded = true;
669
+ preview = undefined;
670
+ previewError = '';
671
+ offsets.inbox = 0;
672
+ message = 'Draft saved. Review the refreshed values before applying.';
270
673
  }
271
674
  } catch (error) {
272
675
  message = String(error);
676
+ reload();
677
+ preview = undefined;
678
+ previewError = '';
273
679
  }
274
680
  }
275
681
  }