@robhowley/pi-remembrancer 0.4.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.
- package/README.md +44 -15
- package/extensions/remembrancer/capture-review.ts +76 -0
- package/extensions/remembrancer/capture.ts +158 -0
- package/extensions/remembrancer/checkpoints.ts +291 -25
- package/extensions/remembrancer/config.ts +14 -3
- package/extensions/remembrancer/index.ts +42 -270
- package/extensions/remembrancer/proposal-ui.ts +275 -0
- package/extensions/remembrancer/proposals.ts +290 -0
- package/extensions/remembrancer/review-pages.ts +268 -0
- package/extensions/remembrancer/reviewer.ts +212 -0
- package/extensions/remembrancer/taskwarrior.ts +288 -0
- package/package.json +1 -1
- package/skills/remembrancer/SKILL.md +29 -0
|
@@ -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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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,181 +164,6 @@ const selectedParameters = Type.Object({
|
|
|
152
164
|
editId: Type.Union([Type.String(), Type.Null()]),
|
|
153
165
|
});
|
|
154
166
|
|
|
155
|
-
export const REVIEW_RESPONSE_MAX_BYTES = 50 * 1024;
|
|
156
|
-
const PAGE_MAX_TEXT_UNITS = 48_000;
|
|
157
|
-
const PAGE_MAX_ENTRIES = 200;
|
|
158
|
-
|
|
159
|
-
export type EvidencePageEntry = Evidence & { offset: number; continues: boolean };
|
|
160
|
-
type EvidencePageItem = Pick<Evidence, 'entryId' | 'role' | 'text' | 'timestamp' | 'editId'> & {
|
|
161
|
-
offset: number;
|
|
162
|
-
continues: boolean;
|
|
163
|
-
};
|
|
164
|
-
type EvidenceGroup = Pick<
|
|
165
|
-
Evidence,
|
|
166
|
-
'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'
|
|
167
|
-
> & {
|
|
168
|
-
entries: EvidencePageItem[];
|
|
169
|
-
};
|
|
170
|
-
export type PageCursor = { index: number; offset: number };
|
|
171
|
-
|
|
172
|
-
function serializedResponse(data: object): string {
|
|
173
|
-
const text = JSON.stringify(data);
|
|
174
|
-
if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
|
|
175
|
-
const bytes = Buffer.byteLength(text, 'utf8');
|
|
176
|
-
if (bytes > REVIEW_RESPONSE_MAX_BYTES)
|
|
177
|
-
throw new Error(
|
|
178
|
-
`Remembrancer response is ${bytes} UTF-8 bytes, over the ${REVIEW_RESPONSE_MAX_BYTES}-byte limit; metadata or envelope cannot fit.`,
|
|
179
|
-
);
|
|
180
|
-
return text;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function fitsResponse(data: object): boolean {
|
|
184
|
-
const text = JSON.stringify(data);
|
|
185
|
-
if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
|
|
186
|
-
return Buffer.byteLength(text, 'utf8') <= REVIEW_RESPONSE_MAX_BYTES;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
function sameGroup(
|
|
190
|
-
a: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
|
|
191
|
-
b: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
|
|
192
|
-
): boolean {
|
|
193
|
-
return (
|
|
194
|
-
a.file === b.file &&
|
|
195
|
-
a.sessionId === b.sessionId &&
|
|
196
|
-
a.cwd === b.cwd &&
|
|
197
|
-
a.branchId === b.branchId &&
|
|
198
|
-
a.reviewedThrough === b.reviewedThrough
|
|
199
|
-
);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export function groupEvidencePage(entries: readonly EvidencePageEntry[]): EvidenceGroup[] {
|
|
203
|
-
const groups: EvidenceGroup[] = [];
|
|
204
|
-
for (const entry of entries) {
|
|
205
|
-
let group = groups.at(-1);
|
|
206
|
-
if (!group || !sameGroup(group, entry)) {
|
|
207
|
-
group = {
|
|
208
|
-
file: entry.file,
|
|
209
|
-
sessionId: entry.sessionId,
|
|
210
|
-
cwd: entry.cwd,
|
|
211
|
-
branchId: entry.branchId,
|
|
212
|
-
reviewedThrough: entry.reviewedThrough,
|
|
213
|
-
entries: [],
|
|
214
|
-
};
|
|
215
|
-
groups.push(group);
|
|
216
|
-
}
|
|
217
|
-
group.entries.push({
|
|
218
|
-
entryId: entry.entryId,
|
|
219
|
-
role: entry.role,
|
|
220
|
-
text: entry.text,
|
|
221
|
-
timestamp: entry.timestamp,
|
|
222
|
-
editId: entry.editId,
|
|
223
|
-
offset: entry.offset,
|
|
224
|
-
continues: entry.continues,
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
return groups;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
function splitsSurrogatePair(text: string, boundary: number): boolean {
|
|
231
|
-
if (boundary <= 0 || boundary >= text.length) return false;
|
|
232
|
-
const before = text.charCodeAt(boundary - 1);
|
|
233
|
-
const after = text.charCodeAt(boundary);
|
|
234
|
-
return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
function safePrefixLength(text: string, start: number, maxUnits: number): number {
|
|
238
|
-
let length = Math.min(maxUnits, text.length - start);
|
|
239
|
-
if (length > 0 && splitsSurrogatePair(text, start + length)) length--;
|
|
240
|
-
return length;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
export function boundedEvidencePage(
|
|
244
|
-
evidence: readonly Evidence[],
|
|
245
|
-
initial: PageCursor,
|
|
246
|
-
buildResponse: (entries: EvidencePageEntry[], cursor: PageCursor) => Record<string, unknown>,
|
|
247
|
-
): { data: Record<string, unknown>; cursor: PageCursor } {
|
|
248
|
-
let { index, offset } = initial;
|
|
249
|
-
const entries: EvidencePageEntry[] = [];
|
|
250
|
-
let remainingText = PAGE_MAX_TEXT_UNITS;
|
|
251
|
-
|
|
252
|
-
const candidateFits = (entry: EvidencePageEntry, cursor: PageCursor) =>
|
|
253
|
-
fitsResponse(buildResponse([...entries, entry], cursor));
|
|
254
|
-
const append = (item: Evidence, length: number) => {
|
|
255
|
-
const start = offset;
|
|
256
|
-
const continues = start + length < item.text.length;
|
|
257
|
-
const entry: EvidencePageEntry = {
|
|
258
|
-
...item,
|
|
259
|
-
text: item.text.slice(start, start + length),
|
|
260
|
-
offset: start,
|
|
261
|
-
continues,
|
|
262
|
-
};
|
|
263
|
-
const cursor = continues ? { index, offset: start + length } : { index: index + 1, offset: 0 };
|
|
264
|
-
if (!candidateFits(entry, cursor)) return false;
|
|
265
|
-
entries.push(entry);
|
|
266
|
-
remainingText -= length;
|
|
267
|
-
({ index, offset } = cursor);
|
|
268
|
-
return true;
|
|
269
|
-
};
|
|
270
|
-
|
|
271
|
-
while (entries.length < PAGE_MAX_ENTRIES && remainingText > 0 && index < evidence.length) {
|
|
272
|
-
const item = evidence[index];
|
|
273
|
-
if (!item) break;
|
|
274
|
-
const wanted = safePrefixLength(item.text, offset, remainingText);
|
|
275
|
-
|
|
276
|
-
if (item.text.length === offset) {
|
|
277
|
-
if (!append(item, 0)) {
|
|
278
|
-
if (entries.length === 0)
|
|
279
|
-
throw new Error(
|
|
280
|
-
`Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
|
|
281
|
-
);
|
|
282
|
-
break;
|
|
283
|
-
}
|
|
284
|
-
continue;
|
|
285
|
-
}
|
|
286
|
-
if (wanted === 0) break;
|
|
287
|
-
|
|
288
|
-
if (append(item, wanted)) {
|
|
289
|
-
if (entries.at(-1)?.continues || remainingText === 0) break;
|
|
290
|
-
continue;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
let low = 0;
|
|
294
|
-
let high = wanted - 1;
|
|
295
|
-
while (low < high) {
|
|
296
|
-
const middle = Math.ceil((low + high) / 2);
|
|
297
|
-
const length = safePrefixLength(item.text, offset, middle);
|
|
298
|
-
if (length === 0) {
|
|
299
|
-
low = middle + 1;
|
|
300
|
-
continue;
|
|
301
|
-
}
|
|
302
|
-
const start = offset;
|
|
303
|
-
const entry: EvidencePageEntry = {
|
|
304
|
-
...item,
|
|
305
|
-
text: item.text.slice(start, start + length),
|
|
306
|
-
offset: start,
|
|
307
|
-
continues: true,
|
|
308
|
-
};
|
|
309
|
-
if (candidateFits(entry, { index, offset: start + length })) {
|
|
310
|
-
low = middle;
|
|
311
|
-
continue;
|
|
312
|
-
}
|
|
313
|
-
high = middle - 1;
|
|
314
|
-
}
|
|
315
|
-
const length = safePrefixLength(item.text, offset, low);
|
|
316
|
-
if (length > 0 && append(item, length)) break;
|
|
317
|
-
if (entries.length === 0)
|
|
318
|
-
throw new Error(
|
|
319
|
-
`Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
|
|
320
|
-
);
|
|
321
|
-
break;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
const cursor = { index, offset };
|
|
325
|
-
const data = buildResponse(entries, cursor);
|
|
326
|
-
serializedResponse(data);
|
|
327
|
-
return { data, cursor };
|
|
328
|
-
}
|
|
329
|
-
|
|
330
167
|
function page(batch: Batch, envelope: Record<string, unknown> = {}) {
|
|
331
168
|
const result = boundedEvidencePage(batch.evidence, batch, (entries, cursor) => ({
|
|
332
169
|
batch: batch.token,
|
|
@@ -354,46 +191,6 @@ function usesDefaultSessionDir(ctx: ExtensionContext): boolean {
|
|
|
354
191
|
return manager.usesDefaultSessionDir();
|
|
355
192
|
}
|
|
356
193
|
|
|
357
|
-
function contextPage(batch: string, selected: Selected, items: Evidence[], offset: number) {
|
|
358
|
-
const total = items.reduce((length, item) => length + item.text.length, 0);
|
|
359
|
-
if (offset > total) throw new Error('Context offset is beyond the requested range');
|
|
360
|
-
|
|
361
|
-
let index = 0;
|
|
362
|
-
let localOffset = 0;
|
|
363
|
-
let position = 0;
|
|
364
|
-
while (index < items.length) {
|
|
365
|
-
const item = items[index]!;
|
|
366
|
-
if (item.text.length === 0) {
|
|
367
|
-
if (offset === position) break;
|
|
368
|
-
index++;
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
const end = position + item.text.length;
|
|
372
|
-
if (offset < end) {
|
|
373
|
-
localOffset = offset - position;
|
|
374
|
-
if (splitsSurrogatePair(item.text, localOffset))
|
|
375
|
-
throw new Error('Context offset splits a surrogate pair; use a returned nextOffset.');
|
|
376
|
-
break;
|
|
377
|
-
}
|
|
378
|
-
position = end;
|
|
379
|
-
index++;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
const result = boundedEvidencePage(items, { index, offset: localOffset }, (entries, cursor) => {
|
|
383
|
-
const nextOffset =
|
|
384
|
-
items.slice(0, cursor.index).reduce((length, item) => length + item.text.length, 0) +
|
|
385
|
-
cursor.offset;
|
|
386
|
-
return {
|
|
387
|
-
batch,
|
|
388
|
-
selected,
|
|
389
|
-
contextOnly: true,
|
|
390
|
-
groups: groupEvidencePage(entries),
|
|
391
|
-
nextOffset: nextOffset < total ? nextOffset : null,
|
|
392
|
-
};
|
|
393
|
-
});
|
|
394
|
-
return result.data;
|
|
395
|
-
}
|
|
396
|
-
|
|
397
194
|
export default function remembrancer(pi: ExtensionAPI) {
|
|
398
195
|
let db: CheckpointStore | undefined;
|
|
399
196
|
let batch: Batch | undefined;
|
|
@@ -435,7 +232,7 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
435
232
|
}
|
|
436
233
|
|
|
437
234
|
pi.registerCommand(REMEMBRANCER_COMMAND_NAME, {
|
|
438
|
-
description: '
|
|
235
|
+
description: 'Review stored task proposals or start a bounded historical review',
|
|
439
236
|
getArgumentCompletions: getRemembrancerArgumentCompletions,
|
|
440
237
|
handler: async (args, ctx) => {
|
|
441
238
|
const parsed = parseRemembrancerCommandArgs(args);
|
|
@@ -454,6 +251,11 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
454
251
|
);
|
|
455
252
|
return;
|
|
456
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
|
+
}
|
|
457
259
|
if (!ctx.isIdle()) {
|
|
458
260
|
ctx.ui.notify(
|
|
459
261
|
'Pi is busy. Wait for the current run to finish, then retry the seed command.',
|
|
@@ -552,58 +354,28 @@ export default function remembrancer(pi: ExtensionAPI) {
|
|
|
552
354
|
function contextReview(args: ReviewArgs): object {
|
|
553
355
|
if (!batch || args.batch !== batch.token)
|
|
554
356
|
throw new Error('No matching open review in this Pi session.');
|
|
555
|
-
|
|
556
|
-
if (!selected) throw new Error('Context requires a selected evidence item.');
|
|
557
|
-
const selectedEvidence = batch.evidence.find(
|
|
558
|
-
(item) =>
|
|
559
|
-
item.sessionId === selected.sessionId &&
|
|
560
|
-
item.branchId === selected.branchId &&
|
|
561
|
-
item.entryId === selected.entryId &&
|
|
562
|
-
item.editId === selected.editId,
|
|
563
|
-
);
|
|
564
|
-
if (!selectedEvidence) throw new Error('Selected evidence is not in this review batch.');
|
|
565
|
-
|
|
566
|
-
const snapshot = batch.snapshots.find(
|
|
567
|
-
(candidate) =>
|
|
568
|
-
candidate.source.sessionId === selected.sessionId &&
|
|
569
|
-
resolve(candidate.source.file) === resolve(selectedEvidence.file),
|
|
570
|
-
);
|
|
571
|
-
if (!snapshot) throw new Error('Selected evidence snapshot is unavailable.');
|
|
572
|
-
|
|
573
|
-
const branch = branchEvidence(
|
|
574
|
-
snapshot.tree,
|
|
575
|
-
{
|
|
576
|
-
file: snapshot.source.file,
|
|
577
|
-
sessionId: selected.sessionId,
|
|
578
|
-
entryId: selected.branchId,
|
|
579
|
-
},
|
|
580
|
-
selectedEvidence.reviewedThrough,
|
|
581
|
-
);
|
|
582
|
-
const selectedIndex = branch.findIndex(
|
|
583
|
-
(item) => item.entryId === selected.entryId && item.editId === selected.editId,
|
|
584
|
-
);
|
|
585
|
-
if (selectedIndex < 0) throw new Error('Selected evidence is not in the frozen branch.');
|
|
586
|
-
|
|
587
|
-
const before = args.before ?? 1;
|
|
588
|
-
const offset = args.offset ?? 0;
|
|
589
|
-
if (!Number.isInteger(before) || before < 1 || before > 40)
|
|
590
|
-
throw new Error('Context before must be an integer from 1 to 40.');
|
|
591
|
-
if (!Number.isInteger(offset) || offset < 0)
|
|
592
|
-
throw new Error('Context offset must be a nonnegative integer.');
|
|
593
|
-
|
|
594
|
-
const items = branch.slice(Math.max(0, selectedIndex - before), selectedIndex);
|
|
595
|
-
return contextPage(batch.token, selected, items, offset);
|
|
357
|
+
return frozenContext(batch, batch.token, args);
|
|
596
358
|
}
|
|
597
359
|
|
|
598
360
|
pi.on('session_start', (_event, ctx) => {
|
|
599
361
|
if (loadRemembrancerConfig(ctx.cwd, ctx.isProjectTrusted()).disabled) return;
|
|
600
362
|
registerReviewTool();
|
|
601
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
|
+
}
|
|
602
368
|
});
|
|
603
|
-
pi.on('session_shutdown', () => {
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
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
|
+
}
|
|
607
379
|
});
|
|
608
380
|
|
|
609
381
|
function registerReviewTool() {
|
|
@@ -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
|
+
}
|