@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.
@@ -0,0 +1,290 @@
1
+ import { resolve } from 'node:path';
2
+ import { Type } from '@earendil-works/pi-ai';
3
+ import type { Evidence } from './evidence.js';
4
+
5
+ export type TaskFields = {
6
+ description?: string;
7
+ project?: string | null;
8
+ due?: string | null;
9
+ wait?: string | null;
10
+ scheduled?: string | null;
11
+ priority?: 'H' | 'M' | 'L' | null;
12
+ waitingon?: string | null;
13
+ tags?: string[];
14
+ depends?: string[];
15
+ };
16
+ export type TaskSnapshot = {
17
+ uuid: string;
18
+ status: 'pending' | 'completed' | 'deleted' | 'waiting' | 'recurring';
19
+ fields: TaskFields & { description: string };
20
+ annotations: { entry: string; description: string }[];
21
+ };
22
+ export type TaskChange =
23
+ | { operation: 'add'; fields: TaskFields & { description: string }; annotations: string[] }
24
+ | { operation: 'update'; targetUuid: string; fields: TaskFields; annotations: string[] }
25
+ | { operation: 'complete'; targetUuid: string; annotations: string[] };
26
+ export type ProposalDraft = {
27
+ change: TaskChange;
28
+ expected: TaskSnapshot | null;
29
+ question: string | null;
30
+ };
31
+ export type EvidenceReference = Pick<Evidence, 'sessionId' | 'branchId' | 'entryId' | 'editId'> & {
32
+ offset: number;
33
+ quote: string;
34
+ };
35
+ export type ProposalSource = EvidenceReference &
36
+ Pick<Evidence, 'file' | 'role' | 'timestamp'> & { locator: string };
37
+ export type ProposalSubmission = ProposalDraft & {
38
+ id?: string;
39
+ expectedRevision?: number;
40
+ explanation: string;
41
+ references: EvidenceReference[];
42
+ };
43
+ export type ProposalState =
44
+ | 'pending'
45
+ | 'dismissed'
46
+ | 'applying'
47
+ | 'applied'
48
+ | 'already_satisfied'
49
+ | 'uncertain';
50
+ export type ApplicationResult = { actual?: Record<string, unknown> | null } & (
51
+ | { state: 'applied' | 'already_satisfied'; verified: TaskSnapshot; error: null }
52
+ | { state: 'uncertain'; verified: TaskSnapshot | null; error: string }
53
+ );
54
+ export type Proposal = ProposalDraft & {
55
+ id: string;
56
+ revision: number;
57
+ draft: ProposalDraft | null;
58
+ explanation: string;
59
+ sources: ProposalSource[];
60
+ state: ProposalState;
61
+ claim: string | null;
62
+ applicationBefore?: TaskSnapshot | null;
63
+ result: ApplicationResult | null;
64
+ createdAt: string;
65
+ updatedAt: string;
66
+ history?: Omit<Proposal, 'history'>[];
67
+ };
68
+
69
+ export function stringEnumSchema<const Values extends readonly string[]>(values: Values) {
70
+ return Type.Unsafe<Values[number]>({
71
+ type: 'string',
72
+ enum: values as unknown as Values[number][],
73
+ });
74
+ }
75
+
76
+ const nullableText = Type.Union([Type.String(), Type.Null()]);
77
+ const taskFieldProperties = {
78
+ description: Type.Optional(Type.String()),
79
+ project: Type.Optional(nullableText),
80
+ due: Type.Optional(nullableText),
81
+ wait: Type.Optional(nullableText),
82
+ scheduled: Type.Optional(nullableText),
83
+ priority: Type.Optional(Type.Union([stringEnumSchema(['H', 'M', 'L']), Type.Null()])),
84
+ waitingon: Type.Optional(nullableText),
85
+ tags: Type.Optional(Type.Array(Type.String())),
86
+ depends: Type.Optional(Type.Array(Type.String())),
87
+ };
88
+ const fieldsSchema = Type.Object(taskFieldProperties, { additionalProperties: false });
89
+ const addFieldsSchema = Type.Object(
90
+ { ...taskFieldProperties, description: Type.String() },
91
+ { additionalProperties: false },
92
+ );
93
+ const annotationsSchema = Type.Array(Type.String());
94
+ export const proposalParameters = Type.Object(
95
+ {
96
+ id: Type.Optional(Type.String()),
97
+ expectedRevision: Type.Optional(Type.Integer({ minimum: 1 })),
98
+ change: Type.Union([
99
+ Type.Object(
100
+ { operation: Type.Literal('add'), fields: addFieldsSchema, annotations: annotationsSchema },
101
+ { additionalProperties: false },
102
+ ),
103
+ Type.Object(
104
+ {
105
+ operation: Type.Literal('update'),
106
+ targetUuid: Type.String(),
107
+ fields: fieldsSchema,
108
+ annotations: annotationsSchema,
109
+ },
110
+ { additionalProperties: false },
111
+ ),
112
+ Type.Object(
113
+ {
114
+ operation: Type.Literal('complete'),
115
+ targetUuid: Type.String(),
116
+ annotations: annotationsSchema,
117
+ },
118
+ { additionalProperties: false },
119
+ ),
120
+ ]),
121
+ expected: Type.Union([
122
+ Type.Null(),
123
+ Type.Object(
124
+ {
125
+ uuid: Type.String(),
126
+ status: stringEnumSchema(['pending', 'completed', 'deleted', 'waiting', 'recurring']),
127
+ fields: addFieldsSchema,
128
+ annotations: Type.Array(
129
+ Type.Object(
130
+ { entry: Type.String(), description: Type.String() },
131
+ { additionalProperties: false },
132
+ ),
133
+ ),
134
+ },
135
+ { additionalProperties: false },
136
+ ),
137
+ ]),
138
+ question: nullableText,
139
+ explanation: Type.String(),
140
+ references: Type.Array(
141
+ Type.Object(
142
+ {
143
+ sessionId: Type.String(),
144
+ branchId: Type.String(),
145
+ entryId: Type.String(),
146
+ editId: nullableText,
147
+ offset: Type.Integer({ minimum: 0 }),
148
+ quote: Type.String(),
149
+ },
150
+ { additionalProperties: false },
151
+ ),
152
+ { minItems: 1 },
153
+ ),
154
+ },
155
+ { additionalProperties: false },
156
+ );
157
+
158
+ function object(value: unknown, keys: readonly string[]): asserts value is Record<string, unknown> {
159
+ if (
160
+ !value ||
161
+ typeof value !== 'object' ||
162
+ Array.isArray(value) ||
163
+ Object.keys(value).some((key) => !keys.includes(key))
164
+ )
165
+ throw new Error('Invalid proposal fields');
166
+ }
167
+ function text(value: unknown): asserts value is string {
168
+ if (typeof value !== 'string' || !value.trim()) throw new Error('Expected nonempty text');
169
+ }
170
+ function uuid(value: unknown): asserts value is string {
171
+ if (typeof value !== 'string' || !/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/iu.test(value))
172
+ throw new Error('Expected full task UUID');
173
+ }
174
+ function fields(value: unknown) {
175
+ object(value, [
176
+ 'description',
177
+ 'project',
178
+ 'due',
179
+ 'wait',
180
+ 'scheduled',
181
+ 'priority',
182
+ 'waitingon',
183
+ 'tags',
184
+ 'depends',
185
+ ]);
186
+ for (const [key, item] of Object.entries(value)) {
187
+ if (key === 'tags' || key === 'depends') {
188
+ if (!Array.isArray(item)) throw new Error('Expected task field array');
189
+ for (const element of item) {
190
+ if (key === 'depends') uuid(element);
191
+ else text(element);
192
+ }
193
+ } else if (key === 'priority') {
194
+ if (item !== null && !['H', 'M', 'L'].includes(item as string))
195
+ throw new Error('Invalid priority');
196
+ } else if (item !== null || key === 'description') text(item);
197
+ }
198
+ }
199
+ export function validateSnapshot(value: TaskSnapshot): void {
200
+ object(value, ['uuid', 'status', 'fields', 'annotations']);
201
+ uuid(value.uuid);
202
+ if (!['pending', 'completed', 'deleted', 'waiting', 'recurring'].includes(value.status))
203
+ throw new Error('Invalid task status');
204
+ fields(value.fields);
205
+ text(value.fields.description);
206
+ if (!Array.isArray(value.annotations)) throw new Error('Invalid annotations');
207
+ for (const annotation of value.annotations) {
208
+ object(annotation, ['entry', 'description']);
209
+ text(annotation.entry);
210
+ text(annotation.description);
211
+ }
212
+ }
213
+ export function validateDraft(value: ProposalDraft): void {
214
+ object(value, ['change', 'expected', 'question']);
215
+ const change = value.change;
216
+ object(
217
+ change,
218
+ change?.operation === 'add'
219
+ ? ['operation', 'fields', 'annotations']
220
+ : change?.operation === 'complete'
221
+ ? ['operation', 'targetUuid', 'annotations']
222
+ : ['operation', 'targetUuid', 'fields', 'annotations'],
223
+ );
224
+ if (!['add', 'update', 'complete'].includes(change.operation))
225
+ throw new Error('Invalid operation');
226
+ if (!Array.isArray(change.annotations)) throw new Error('Invalid annotations');
227
+ change.annotations.forEach(text);
228
+ if (change.operation !== 'complete') fields(change.fields);
229
+ if (change.operation === 'add') {
230
+ text(change.fields.description);
231
+ if (value.expected !== null) throw new Error('Add cannot have an expected task');
232
+ } else {
233
+ uuid(change.targetUuid);
234
+ if (!value.expected) throw new Error('Existing task requires expected snapshot');
235
+ validateSnapshot(value.expected);
236
+ if (value.expected.uuid !== change.targetUuid)
237
+ throw new Error('Task snapshot does not match target');
238
+ }
239
+ if (value.question !== null) text(value.question);
240
+ }
241
+ export function validateSubmission(
242
+ value: ProposalSubmission,
243
+ evidence: readonly Evidence[],
244
+ ): ProposalSource[] {
245
+ object(value, [
246
+ 'id',
247
+ 'expectedRevision',
248
+ 'change',
249
+ 'expected',
250
+ 'question',
251
+ 'explanation',
252
+ 'references',
253
+ ]);
254
+ validateDraft({ change: value.change, expected: value.expected, question: value.question });
255
+ text(value.explanation);
256
+ if ((value.id === undefined) !== (value.expectedRevision === undefined))
257
+ throw new Error('Revision requires proposal ID');
258
+ if (value.id !== undefined) {
259
+ text(value.id);
260
+ if (!Number.isSafeInteger(value.expectedRevision) || value.expectedRevision! < 1)
261
+ throw new Error('Invalid expected revision');
262
+ }
263
+ if (!Array.isArray(value.references) || !value.references.length)
264
+ throw new Error('Proposal requires eligible evidence');
265
+ return value.references.map((ref) => {
266
+ object(ref, ['sessionId', 'branchId', 'entryId', 'editId', 'offset', 'quote']);
267
+ text(ref.quote);
268
+ const item = evidence.find(
269
+ (item) =>
270
+ item.sessionId === ref.sessionId &&
271
+ item.branchId === ref.branchId &&
272
+ item.entryId === ref.entryId &&
273
+ item.editId === ref.editId,
274
+ );
275
+ if (
276
+ !item ||
277
+ !Number.isSafeInteger(ref.offset) ||
278
+ ref.offset < 0 ||
279
+ item.text.slice(ref.offset, ref.offset + ref.quote.length) !== ref.quote
280
+ )
281
+ throw new Error('Reference does not match frozen eligible evidence');
282
+ return {
283
+ ...ref,
284
+ file: resolve(item.file),
285
+ role: item.role,
286
+ timestamp: item.timestamp,
287
+ locator: `${item.sessionId}/${item.branchId}/${item.entryId}`,
288
+ };
289
+ });
290
+ }
@@ -0,0 +1,268 @@
1
+ import { resolve } from 'node:path';
2
+ import { branchEvidence, type Evidence, type PreparedReview } from './evidence.js';
3
+
4
+ export type Selected = {
5
+ sessionId: string;
6
+ branchId: string;
7
+ entryId: string;
8
+ editId: string | null;
9
+ };
10
+
11
+ export const REVIEW_RESPONSE_MAX_BYTES = 50 * 1024;
12
+ const PAGE_MAX_TEXT_UNITS = 48_000;
13
+ const PAGE_MAX_ENTRIES = 200;
14
+
15
+ export type EvidencePageEntry = Evidence & { offset: number; continues: boolean };
16
+ type EvidencePageItem = Pick<Evidence, 'entryId' | 'role' | 'text' | 'timestamp' | 'editId'> & {
17
+ offset: number;
18
+ continues: boolean;
19
+ };
20
+ type EvidenceGroup = Pick<
21
+ Evidence,
22
+ 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'
23
+ > & {
24
+ entries: EvidencePageItem[];
25
+ };
26
+ export type PageCursor = { index: number; offset: number };
27
+
28
+ export function serializedResponse(data: object): string {
29
+ const text = JSON.stringify(data);
30
+ if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
31
+ const bytes = Buffer.byteLength(text, 'utf8');
32
+ if (bytes > REVIEW_RESPONSE_MAX_BYTES)
33
+ throw new Error(
34
+ `Remembrancer response is ${bytes} UTF-8 bytes, over the ${REVIEW_RESPONSE_MAX_BYTES}-byte limit; metadata or envelope cannot fit.`,
35
+ );
36
+ return text;
37
+ }
38
+
39
+ function fitsResponse(data: object): boolean {
40
+ const text = JSON.stringify(data);
41
+ if (text === undefined) throw new Error('Remembrancer response is not JSON serializable.');
42
+ return Buffer.byteLength(text, 'utf8') <= REVIEW_RESPONSE_MAX_BYTES;
43
+ }
44
+
45
+ function sameGroup(
46
+ a: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
47
+ b: Pick<Evidence, 'file' | 'sessionId' | 'cwd' | 'branchId' | 'reviewedThrough'>,
48
+ ): boolean {
49
+ return (
50
+ a.file === b.file &&
51
+ a.sessionId === b.sessionId &&
52
+ a.cwd === b.cwd &&
53
+ a.branchId === b.branchId &&
54
+ a.reviewedThrough === b.reviewedThrough
55
+ );
56
+ }
57
+
58
+ export function groupEvidencePage(entries: readonly EvidencePageEntry[]): EvidenceGroup[] {
59
+ const groups: EvidenceGroup[] = [];
60
+ for (const entry of entries) {
61
+ let group = groups.at(-1);
62
+ if (!group || !sameGroup(group, entry)) {
63
+ group = {
64
+ file: entry.file,
65
+ sessionId: entry.sessionId,
66
+ cwd: entry.cwd,
67
+ branchId: entry.branchId,
68
+ reviewedThrough: entry.reviewedThrough,
69
+ entries: [],
70
+ };
71
+ groups.push(group);
72
+ }
73
+ group.entries.push({
74
+ entryId: entry.entryId,
75
+ role: entry.role,
76
+ text: entry.text,
77
+ timestamp: entry.timestamp,
78
+ editId: entry.editId,
79
+ offset: entry.offset,
80
+ continues: entry.continues,
81
+ });
82
+ }
83
+ return groups;
84
+ }
85
+
86
+ function splitsSurrogatePair(text: string, boundary: number): boolean {
87
+ if (boundary <= 0 || boundary >= text.length) return false;
88
+ const before = text.charCodeAt(boundary - 1);
89
+ const after = text.charCodeAt(boundary);
90
+ return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff;
91
+ }
92
+
93
+ function safePrefixLength(text: string, start: number, maxUnits: number): number {
94
+ let length = Math.min(maxUnits, text.length - start);
95
+ if (length > 0 && splitsSurrogatePair(text, start + length)) length--;
96
+ return length;
97
+ }
98
+
99
+ export function boundedEvidencePage(
100
+ evidence: readonly Evidence[],
101
+ initial: PageCursor,
102
+ buildResponse: (entries: EvidencePageEntry[], cursor: PageCursor) => Record<string, unknown>,
103
+ ): { data: Record<string, unknown>; cursor: PageCursor } {
104
+ let { index, offset } = initial;
105
+ const entries: EvidencePageEntry[] = [];
106
+ let remainingText = PAGE_MAX_TEXT_UNITS;
107
+
108
+ const candidateFits = (entry: EvidencePageEntry, cursor: PageCursor) =>
109
+ fitsResponse(buildResponse([...entries, entry], cursor));
110
+ const append = (item: Evidence, length: number) => {
111
+ const start = offset;
112
+ const continues = start + length < item.text.length;
113
+ const entry: EvidencePageEntry = {
114
+ ...item,
115
+ text: item.text.slice(start, start + length),
116
+ offset: start,
117
+ continues,
118
+ };
119
+ const cursor = continues ? { index, offset: start + length } : { index: index + 1, offset: 0 };
120
+ if (!candidateFits(entry, cursor)) return false;
121
+ entries.push(entry);
122
+ remainingText -= length;
123
+ ({ index, offset } = cursor);
124
+ return true;
125
+ };
126
+
127
+ while (entries.length < PAGE_MAX_ENTRIES && remainingText > 0 && index < evidence.length) {
128
+ const item = evidence[index];
129
+ if (!item) break;
130
+ const wanted = safePrefixLength(item.text, offset, remainingText);
131
+
132
+ if (item.text.length === offset) {
133
+ if (!append(item, 0)) {
134
+ if (entries.length === 0)
135
+ throw new Error(
136
+ `Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
137
+ );
138
+ break;
139
+ }
140
+ continue;
141
+ }
142
+ if (wanted === 0) break;
143
+
144
+ if (append(item, wanted)) {
145
+ if (entries.at(-1)?.continues || remainingText === 0) break;
146
+ continue;
147
+ }
148
+
149
+ let low = 0;
150
+ let high = wanted - 1;
151
+ while (low < high) {
152
+ const middle = Math.ceil((low + high) / 2);
153
+ const length = safePrefixLength(item.text, offset, middle);
154
+ if (length === 0) {
155
+ low = middle + 1;
156
+ continue;
157
+ }
158
+ const start = offset;
159
+ const entry: EvidencePageEntry = {
160
+ ...item,
161
+ text: item.text.slice(start, start + length),
162
+ offset: start,
163
+ continues: true,
164
+ };
165
+ if (candidateFits(entry, { index, offset: start + length })) {
166
+ low = middle;
167
+ continue;
168
+ }
169
+ high = middle - 1;
170
+ }
171
+ const length = safePrefixLength(item.text, offset, low);
172
+ if (length > 0 && append(item, length)) break;
173
+ if (entries.length === 0)
174
+ throw new Error(
175
+ `Remembrancer response cannot fit a complete evidence entry within the ${REVIEW_RESPONSE_MAX_BYTES}-byte UTF-8 limit; metadata or envelope cannot fit.`,
176
+ );
177
+ break;
178
+ }
179
+
180
+ const cursor = { index, offset };
181
+ const data = buildResponse(entries, cursor);
182
+ serializedResponse(data);
183
+ return { data, cursor };
184
+ }
185
+
186
+ export function frozenContext(
187
+ review: Pick<PreparedReview, 'evidence' | 'snapshots'>,
188
+ batch: string,
189
+ args: { selected?: Selected; before?: number; offset?: number },
190
+ ) {
191
+ const selected = args.selected;
192
+ if (!selected) throw new Error('Context requires a selected evidence item.');
193
+ const selectedEvidence = review.evidence.find(
194
+ (item) =>
195
+ item.sessionId === selected.sessionId &&
196
+ item.branchId === selected.branchId &&
197
+ item.entryId === selected.entryId &&
198
+ item.editId === selected.editId,
199
+ );
200
+ if (!selectedEvidence) throw new Error('Selected evidence is not in this review batch.');
201
+ const snapshot = review.snapshots.find(
202
+ (candidate) =>
203
+ candidate.source.sessionId === selected.sessionId &&
204
+ resolve(candidate.source.file) === resolve(selectedEvidence.file),
205
+ );
206
+ if (!snapshot) throw new Error('Selected evidence snapshot is unavailable.');
207
+ const branch = branchEvidence(
208
+ snapshot.tree,
209
+ { file: snapshot.source.file, sessionId: selected.sessionId, entryId: selected.branchId },
210
+ selectedEvidence.reviewedThrough,
211
+ );
212
+ const selectedIndex = branch.findIndex(
213
+ (item) => item.entryId === selected.entryId && item.editId === selected.editId,
214
+ );
215
+ if (selectedIndex < 0) throw new Error('Selected evidence is not in the frozen branch.');
216
+ const before = args.before ?? 1;
217
+ const offset = args.offset ?? 0;
218
+ if (!Number.isInteger(before) || before < 1 || before > 40)
219
+ throw new Error('Context before must be an integer from 1 to 40.');
220
+ if (!Number.isInteger(offset) || offset < 0)
221
+ throw new Error('Context offset must be a nonnegative integer.');
222
+ return contextPage(
223
+ batch,
224
+ selected,
225
+ branch.slice(Math.max(0, selectedIndex - before), selectedIndex),
226
+ offset,
227
+ );
228
+ }
229
+
230
+ export function contextPage(batch: string, selected: Selected, items: Evidence[], offset: number) {
231
+ const total = items.reduce((length, item) => length + item.text.length, 0);
232
+ if (offset > total) throw new Error('Context offset is beyond the requested range');
233
+
234
+ let index = 0;
235
+ let localOffset = 0;
236
+ let position = 0;
237
+ while (index < items.length) {
238
+ const item = items[index]!;
239
+ if (item.text.length === 0) {
240
+ if (offset === position) break;
241
+ index++;
242
+ continue;
243
+ }
244
+ const end = position + item.text.length;
245
+ if (offset < end) {
246
+ localOffset = offset - position;
247
+ if (splitsSurrogatePair(item.text, localOffset))
248
+ throw new Error('Context offset splits a surrogate pair; use a returned nextOffset.');
249
+ break;
250
+ }
251
+ position = end;
252
+ index++;
253
+ }
254
+
255
+ const result = boundedEvidencePage(items, { index, offset: localOffset }, (entries, cursor) => {
256
+ const nextOffset =
257
+ items.slice(0, cursor.index).reduce((length, item) => length + item.text.length, 0) +
258
+ cursor.offset;
259
+ return {
260
+ batch,
261
+ selected,
262
+ contextOnly: true,
263
+ groups: groupEvidencePage(entries),
264
+ nextOffset: nextOffset < total ? nextOffset : null,
265
+ };
266
+ });
267
+ return result.data;
268
+ }