@robhowley/pi-remembrancer 0.5.1 → 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.
- package/README.md +58 -17
- package/extensions/remembrancer/capture-artifacts.ts +211 -0
- package/extensions/remembrancer/capture-handoff.ts +712 -0
- package/extensions/remembrancer/capture-jobs.ts +111 -0
- package/extensions/remembrancer/capture-matches.ts +145 -0
- package/extensions/remembrancer/capture-notices.ts +51 -0
- package/extensions/remembrancer/capture-publication-lock.mjs +37 -0
- package/extensions/remembrancer/capture-review.ts +84 -12
- package/extensions/remembrancer/capture-sizing.ts +63 -0
- package/extensions/remembrancer/capture-submission.ts +289 -0
- package/extensions/remembrancer/capture-worker-bootstrap.mjs +53 -0
- package/extensions/remembrancer/capture-worker.ts +336 -0
- package/extensions/remembrancer/capture.ts +259 -135
- package/extensions/remembrancer/checkpoints.ts +603 -116
- package/extensions/remembrancer/config.ts +31 -1
- package/extensions/remembrancer/evidence.ts +318 -74
- package/extensions/remembrancer/index.ts +260 -14
- package/extensions/remembrancer/private-sqlite.mjs +17 -0
- package/extensions/remembrancer/proposal-read.ts +223 -9
- package/extensions/remembrancer/proposal-ui.ts +597 -191
- package/extensions/remembrancer/proposals.ts +44 -9
- package/extensions/remembrancer/review-findings.ts +178 -0
- package/extensions/remembrancer/review-pages.ts +58 -16
- package/extensions/remembrancer/review-plan.ts +27 -0
- package/extensions/remembrancer/reviewer-budget.ts +53 -0
- package/extensions/remembrancer/reviewer.ts +166 -30
- package/extensions/remembrancer/taskwarrior.ts +95 -14
- package/package.json +5 -4
- package/skills/remembrancer/SKILL.md +35 -19
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
|
-
import { Type } from '@
|
|
2
|
+
import { Type } from '@sinclair/typebox';
|
|
3
3
|
import type { Evidence } from './evidence.js';
|
|
4
|
+
import { splitsSurrogatePair } from './review-pages.js';
|
|
4
5
|
|
|
5
6
|
export type TaskFields = {
|
|
6
7
|
description?: string;
|
|
@@ -63,7 +64,6 @@ export type Proposal = ProposalDraft & {
|
|
|
63
64
|
result: ApplicationResult | null;
|
|
64
65
|
createdAt: string;
|
|
65
66
|
updatedAt: string;
|
|
66
|
-
history?: Omit<Proposal, 'history'>[];
|
|
67
67
|
};
|
|
68
68
|
|
|
69
69
|
export function stringEnumSchema<const Values extends readonly string[]>(values: Values) {
|
|
@@ -210,8 +210,9 @@ export function validateSnapshot(value: TaskSnapshot): void {
|
|
|
210
210
|
text(annotation.description);
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
-
|
|
214
|
-
|
|
213
|
+
/** Intent syntax without a model-supplied snapshot. Bound drafts still require validateDraft. */
|
|
214
|
+
export function validateProposalIntent(value: Pick<ProposalDraft, 'change' | 'question'>): void {
|
|
215
|
+
object(value, ['change', 'question']);
|
|
215
216
|
const change = value.change;
|
|
216
217
|
object(
|
|
217
218
|
change,
|
|
@@ -226,17 +227,22 @@ export function validateDraft(value: ProposalDraft): void {
|
|
|
226
227
|
if (!Array.isArray(change.annotations)) throw new Error('Invalid annotations');
|
|
227
228
|
change.annotations.forEach(text);
|
|
228
229
|
if (change.operation !== 'complete') fields(change.fields);
|
|
230
|
+
if (change.operation === 'add') text(change.fields.description);
|
|
231
|
+
else uuid(change.targetUuid);
|
|
232
|
+
if (value.question !== null) text(value.question);
|
|
233
|
+
}
|
|
234
|
+
export function validateDraft(value: ProposalDraft): void {
|
|
235
|
+
object(value, ['change', 'expected', 'question']);
|
|
236
|
+
validateProposalIntent({ change: value.change, question: value.question });
|
|
237
|
+
const change = value.change;
|
|
229
238
|
if (change.operation === 'add') {
|
|
230
|
-
text(change.fields.description);
|
|
231
239
|
if (value.expected !== null) throw new Error('Add cannot have an expected task');
|
|
232
240
|
} else {
|
|
233
|
-
uuid(change.targetUuid);
|
|
234
241
|
if (!value.expected) throw new Error('Existing task requires expected snapshot');
|
|
235
242
|
validateSnapshot(value.expected);
|
|
236
243
|
if (value.expected.uuid !== change.targetUuid)
|
|
237
244
|
throw new Error('Task snapshot does not match target');
|
|
238
245
|
}
|
|
239
|
-
if (value.question !== null) text(value.question);
|
|
240
246
|
}
|
|
241
247
|
export function validateSubmission(
|
|
242
248
|
value: ProposalSubmission,
|
|
@@ -260,9 +266,16 @@ export function validateSubmission(
|
|
|
260
266
|
if (!Number.isSafeInteger(value.expectedRevision) || value.expectedRevision! < 1)
|
|
261
267
|
throw new Error('Invalid expected revision');
|
|
262
268
|
}
|
|
263
|
-
|
|
269
|
+
return validateReferences(value.references, evidence);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function validateReferences(
|
|
273
|
+
references: readonly EvidenceReference[],
|
|
274
|
+
evidence: readonly Evidence[],
|
|
275
|
+
): ProposalSource[] {
|
|
276
|
+
if (!Array.isArray(references) || !references.length)
|
|
264
277
|
throw new Error('Proposal requires eligible evidence');
|
|
265
|
-
|
|
278
|
+
const sources = references.map((ref: EvidenceReference) => {
|
|
266
279
|
object(ref, ['sessionId', 'branchId', 'entryId', 'editId', 'offset', 'quote']);
|
|
267
280
|
text(ref.quote);
|
|
268
281
|
const item = evidence.find(
|
|
@@ -276,6 +289,8 @@ export function validateSubmission(
|
|
|
276
289
|
!item ||
|
|
277
290
|
!Number.isSafeInteger(ref.offset) ||
|
|
278
291
|
ref.offset < 0 ||
|
|
292
|
+
splitsSurrogatePair(item.text, ref.offset) ||
|
|
293
|
+
splitsSurrogatePair(item.text, ref.offset + ref.quote.length) ||
|
|
279
294
|
item.text.slice(ref.offset, ref.offset + ref.quote.length) !== ref.quote
|
|
280
295
|
)
|
|
281
296
|
throw new Error('Reference does not match frozen eligible evidence');
|
|
@@ -287,4 +302,24 @@ export function validateSubmission(
|
|
|
287
302
|
locator: `${item.sessionId}/${item.branchId}/${item.entryId}`,
|
|
288
303
|
};
|
|
289
304
|
});
|
|
305
|
+
return unionProposalSources(sources);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function unionProposalSources(
|
|
309
|
+
...groups: readonly (readonly ProposalSource[])[]
|
|
310
|
+
): ProposalSource[] {
|
|
311
|
+
const seen = new Set<string>();
|
|
312
|
+
return groups.flat().filter((source) => {
|
|
313
|
+
const key = JSON.stringify([
|
|
314
|
+
source.sessionId,
|
|
315
|
+
source.branchId,
|
|
316
|
+
source.entryId,
|
|
317
|
+
source.editId,
|
|
318
|
+
source.offset,
|
|
319
|
+
source.quote,
|
|
320
|
+
]);
|
|
321
|
+
if (seen.has(key)) return false;
|
|
322
|
+
seen.add(key);
|
|
323
|
+
return true;
|
|
324
|
+
});
|
|
290
325
|
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { fitPrefixLength } from './review-pages.js';
|
|
2
|
+
import type { ProposalDraft, ProposalSubmission, TaskSnapshot } from './proposals.js';
|
|
3
|
+
import { validateDraft, validateProposalIntent } from './proposals.js';
|
|
4
|
+
import { estimateReviewerTokens, ReviewerBudgetError } from './reviewer-budget.js';
|
|
5
|
+
|
|
6
|
+
export const findingKinds = [
|
|
7
|
+
'accepted',
|
|
8
|
+
'correction',
|
|
9
|
+
'refusal',
|
|
10
|
+
'progress',
|
|
11
|
+
'completion',
|
|
12
|
+
'reference',
|
|
13
|
+
] as const;
|
|
14
|
+
export type FindingRecord = { id: string; ambiguous: boolean };
|
|
15
|
+
// Intent does not need a model-reproduced snapshot. Only the host can bind one.
|
|
16
|
+
export type CaptureDraft = Omit<ProposalDraft, 'expected'> & {
|
|
17
|
+
expected?: TaskSnapshot | null;
|
|
18
|
+
};
|
|
19
|
+
export type FoldedFinding = {
|
|
20
|
+
summary: string;
|
|
21
|
+
status: 'active' | 'completed' | 'refused' | 'uncertain';
|
|
22
|
+
draft: CaptureDraft | null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function object(value: unknown): Record<string, unknown> {
|
|
26
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
27
|
+
throw new Error('Invalid capture step object');
|
|
28
|
+
return value as Record<string, unknown>;
|
|
29
|
+
}
|
|
30
|
+
export function text(value: unknown): string {
|
|
31
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error('Invalid capture step text');
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
export function folded(value: unknown): FoldedFinding {
|
|
35
|
+
const data = object(value);
|
|
36
|
+
const summary = text(data['summary']);
|
|
37
|
+
if (
|
|
38
|
+
typeof data['status'] !== 'string' ||
|
|
39
|
+
!['active', 'completed', 'refused', 'uncertain'].includes(data['status'])
|
|
40
|
+
)
|
|
41
|
+
throw new Error('Invalid capture finding status');
|
|
42
|
+
return {
|
|
43
|
+
summary,
|
|
44
|
+
status: data['status'] as FoldedFinding['status'],
|
|
45
|
+
draft: data['draft'] === null ? null : validateIntent(data['draft']),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Validate the proposed operation before looking up or substituting any trusted state. */
|
|
50
|
+
export function validateIntent(value: unknown): CaptureDraft {
|
|
51
|
+
const draft = object(value);
|
|
52
|
+
if (Object.keys(draft).some((key) => !['change', 'expected', 'question'].includes(key)))
|
|
53
|
+
throw new Error('Invalid capture intent fields');
|
|
54
|
+
const change = object(draft['change']) as CaptureDraft['change'];
|
|
55
|
+
validateProposalIntent({ change, question: draft['question'] as string | null });
|
|
56
|
+
// Ignore a legacy model-supplied snapshot, including any identity/status inside it.
|
|
57
|
+
return { change, question: draft['question'] as string | null };
|
|
58
|
+
}
|
|
59
|
+
/** Structured field pages, never JSON fragments the model must concatenate. Originals stay in host memory. */
|
|
60
|
+
export function* detailPages(
|
|
61
|
+
value: unknown,
|
|
62
|
+
limit: number,
|
|
63
|
+
path: (string | number)[] = [],
|
|
64
|
+
envelope: (page: object, index: number) => unknown = (page) => page,
|
|
65
|
+
): Generator<object> {
|
|
66
|
+
let index = 0;
|
|
67
|
+
const fits = (page: object) => estimateReviewerTokens(envelope(page, index)) <= limit;
|
|
68
|
+
function* walk(value: unknown, path: (string | number)[]): Generator<object> {
|
|
69
|
+
if (value !== null && typeof value === 'object' && Object.keys(value).length) {
|
|
70
|
+
for (const [key, child] of Object.entries(value)) yield* walk(child, [...path, key]);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (typeof value !== 'string') {
|
|
74
|
+
const page = { path, value };
|
|
75
|
+
if (!fits(page)) throw new ReviewerBudgetError('Capture detail metadata cannot fit');
|
|
76
|
+
yield page;
|
|
77
|
+
index++;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let offset = 0;
|
|
81
|
+
do {
|
|
82
|
+
const build = (length: number) => ({
|
|
83
|
+
path,
|
|
84
|
+
offset,
|
|
85
|
+
text: value.slice(offset, offset + length),
|
|
86
|
+
end: offset + length === value.length,
|
|
87
|
+
});
|
|
88
|
+
const length = fitPrefixLength(value, offset, (length) => fits(build(length)));
|
|
89
|
+
const page = build(length);
|
|
90
|
+
if ((!length && offset < value.length) || !fits(page))
|
|
91
|
+
throw new ReviewerBudgetError('Capture detail metadata cannot fit with positive progress');
|
|
92
|
+
yield page;
|
|
93
|
+
index++;
|
|
94
|
+
offset += length;
|
|
95
|
+
} while (offset < value.length);
|
|
96
|
+
}
|
|
97
|
+
yield* walk(value, path);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function validateMaterialization(
|
|
101
|
+
value: unknown,
|
|
102
|
+
record: FindingRecord,
|
|
103
|
+
state: FoldedFinding,
|
|
104
|
+
binding: {
|
|
105
|
+
expected?: TaskSnapshot | null;
|
|
106
|
+
conflictingChanges?: boolean;
|
|
107
|
+
allowNoop?: boolean;
|
|
108
|
+
tracked?: boolean;
|
|
109
|
+
questions?: (string | null | undefined)[];
|
|
110
|
+
} = {},
|
|
111
|
+
): Omit<ProposalSubmission, 'references'> | null {
|
|
112
|
+
const result = object(value);
|
|
113
|
+
text(result['reason']);
|
|
114
|
+
if (result['submission'] === null) {
|
|
115
|
+
if (record.ambiguous || binding.conflictingChanges || state.status === 'uncertain')
|
|
116
|
+
throw new Error('Ambiguous capture requires a question');
|
|
117
|
+
if (state.draft?.question || binding.questions?.some(Boolean))
|
|
118
|
+
throw new Error('Capture must preserve unresolved questions');
|
|
119
|
+
if (binding.tracked && !binding.allowNoop)
|
|
120
|
+
throw new Error('Tracked capture requires a proposal or verified no-op');
|
|
121
|
+
if (state.status !== 'completed' && state.status !== 'refused' && !binding.allowNoop)
|
|
122
|
+
throw new Error('Active capture requires a proposal or verified no-op');
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
const submission = object(result['submission']) as Omit<ProposalSubmission, 'references'>;
|
|
126
|
+
if (
|
|
127
|
+
Object.keys(submission).some(
|
|
128
|
+
(key) => !['change', 'expected', 'question', 'explanation'].includes(key),
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
throw new Error('Materialization cannot select references or proposal identity');
|
|
132
|
+
validateIntent({
|
|
133
|
+
change: submission.change,
|
|
134
|
+
expected: submission.expected,
|
|
135
|
+
question: submission.question,
|
|
136
|
+
});
|
|
137
|
+
text(submission.explanation);
|
|
138
|
+
const question = submission.question;
|
|
139
|
+
const requiredQuestions = [state.draft?.question, ...(binding.questions ?? [])];
|
|
140
|
+
if (requiredQuestions.some((required) => required && !question?.includes(required)))
|
|
141
|
+
throw new Error('Finalized capture must preserve unresolved questions');
|
|
142
|
+
if (
|
|
143
|
+
(record.ambiguous ||
|
|
144
|
+
binding.conflictingChanges ||
|
|
145
|
+
state.status === 'uncertain' ||
|
|
146
|
+
state.status === 'refused' ||
|
|
147
|
+
(state.status === 'completed' && submission.change.operation !== 'complete')) &&
|
|
148
|
+
!question
|
|
149
|
+
)
|
|
150
|
+
throw new Error('Unsupported or ambiguous capture outcome requires a question');
|
|
151
|
+
if (
|
|
152
|
+
state.status === 'active' &&
|
|
153
|
+
submission.change.operation === 'complete' &&
|
|
154
|
+
state.draft?.change.operation !== 'complete' &&
|
|
155
|
+
!question
|
|
156
|
+
)
|
|
157
|
+
throw new Error('Active evidence does not authorize completion');
|
|
158
|
+
if (submission.change.operation !== 'add') {
|
|
159
|
+
const intent = state.draft?.change;
|
|
160
|
+
if (
|
|
161
|
+
record.ambiguous ||
|
|
162
|
+
submission.change.targetUuid !== binding.expected?.uuid ||
|
|
163
|
+
(intent && intent.operation !== 'add' && intent.targetUuid !== submission.change.targetUuid)
|
|
164
|
+
)
|
|
165
|
+
throw new Error('Capture target was not uniquely matched to exact saved state');
|
|
166
|
+
} else if (binding.expected && (binding.conflictingChanges || !question)) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
'Matched existing task cannot become an addition for conflicting changes or an unqualified add',
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
const bound = {
|
|
172
|
+
...submission,
|
|
173
|
+
question,
|
|
174
|
+
expected: submission.change.operation === 'add' ? null : (binding.expected ?? null),
|
|
175
|
+
};
|
|
176
|
+
validateDraft({ change: bound.change, expected: bound.expected, question: bound.question });
|
|
177
|
+
return bound;
|
|
178
|
+
}
|
|
@@ -83,19 +83,39 @@ export function groupEvidencePage(entries: readonly EvidencePageEntry[]): Eviden
|
|
|
83
83
|
return groups;
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
-
function splitsSurrogatePair(text: string, boundary: number): boolean {
|
|
86
|
+
export function splitsSurrogatePair(text: string, boundary: number): boolean {
|
|
87
87
|
if (boundary <= 0 || boundary >= text.length) return false;
|
|
88
88
|
const before = text.charCodeAt(boundary - 1);
|
|
89
89
|
const after = text.charCodeAt(boundary);
|
|
90
90
|
return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff;
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
-
function safePrefixLength(text: string, start: number, maxUnits: number): number {
|
|
93
|
+
export function safePrefixLength(text: string, start: number, maxUnits: number): number {
|
|
94
94
|
let length = Math.min(maxUnits, text.length - start);
|
|
95
95
|
if (length > 0 && splitsSurrogatePair(text, start + length)) length--;
|
|
96
96
|
return length;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
/** Find a Unicode-safe prefix using the complete encoded response as the fit predicate. */
|
|
100
|
+
export function fitPrefixLength(
|
|
101
|
+
text: string,
|
|
102
|
+
start: number,
|
|
103
|
+
fits: (length: number) => boolean,
|
|
104
|
+
maxUnits = text.length - start,
|
|
105
|
+
): number {
|
|
106
|
+
let low = 0;
|
|
107
|
+
let high = Math.min(text.length - start, maxUnits);
|
|
108
|
+
const full = safePrefixLength(text, start, high);
|
|
109
|
+
// Finishing can remove a continuation cursor, so test that envelope first.
|
|
110
|
+
if (fits(full)) return full;
|
|
111
|
+
while (low < high) {
|
|
112
|
+
const middle = Math.ceil((low + high) / 2);
|
|
113
|
+
if (fits(safePrefixLength(text, start, middle))) low = middle;
|
|
114
|
+
else high = middle - 1;
|
|
115
|
+
}
|
|
116
|
+
return safePrefixLength(text, start, low);
|
|
117
|
+
}
|
|
118
|
+
|
|
99
119
|
export function boundedEvidencePage(
|
|
100
120
|
evidence: readonly Evidence[],
|
|
101
121
|
initial: PageCursor,
|
|
@@ -186,10 +206,36 @@ export function boundedEvidencePage(
|
|
|
186
206
|
export function frozenContext(
|
|
187
207
|
review: Pick<PreparedReview, 'evidence' | 'snapshots'>,
|
|
188
208
|
batch: string,
|
|
189
|
-
args: { selected?: Selected; before?: number; offset?: number },
|
|
209
|
+
args: { selected?: Selected; before?: number; skip?: number; offset?: number },
|
|
190
210
|
) {
|
|
191
211
|
const selected = args.selected;
|
|
192
212
|
if (!selected) throw new Error('Context requires a selected evidence item.');
|
|
213
|
+
const { branch, selectedIndex } = frozenBranch(review, selected);
|
|
214
|
+
const before = args.before ?? 1;
|
|
215
|
+
const skip = args.skip ?? 0;
|
|
216
|
+
const offset = args.offset ?? 0;
|
|
217
|
+
if (!Number.isInteger(before) || before < 1 || before > 40)
|
|
218
|
+
throw new Error('Context before must be an integer from 1 to 40.');
|
|
219
|
+
if (!Number.isSafeInteger(skip) || skip < 0 || skip > selectedIndex)
|
|
220
|
+
throw new Error('Context skip is outside the frozen preceding entries.');
|
|
221
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
222
|
+
throw new Error('Context offset must be a nonnegative integer.');
|
|
223
|
+
const end = selectedIndex - skip;
|
|
224
|
+
const start = Math.max(0, end - before);
|
|
225
|
+
return contextPage(
|
|
226
|
+
batch,
|
|
227
|
+
selected,
|
|
228
|
+
branch.slice(start, end),
|
|
229
|
+
offset,
|
|
230
|
+
// Manual readers retain their existing response shape. Capture explicitly opts into paging.
|
|
231
|
+
args.skip === undefined ? {} : { skip, nextSkip: start > 0 ? selectedIndex - start : null },
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function frozenBranch(
|
|
236
|
+
review: Pick<PreparedReview, 'evidence' | 'snapshots'>,
|
|
237
|
+
selected: Selected,
|
|
238
|
+
) {
|
|
193
239
|
const selectedEvidence = review.evidence.find(
|
|
194
240
|
(item) =>
|
|
195
241
|
item.sessionId === selected.sessionId &&
|
|
@@ -213,21 +259,16 @@ export function frozenContext(
|
|
|
213
259
|
(item) => item.entryId === selected.entryId && item.editId === selected.editId,
|
|
214
260
|
);
|
|
215
261
|
if (selectedIndex < 0) throw new Error('Selected evidence is not in the frozen branch.');
|
|
216
|
-
|
|
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
|
-
);
|
|
262
|
+
return { branch, selectedIndex };
|
|
228
263
|
}
|
|
229
264
|
|
|
230
|
-
export function contextPage(
|
|
265
|
+
export function contextPage(
|
|
266
|
+
batch: string,
|
|
267
|
+
selected: Selected,
|
|
268
|
+
items: Evidence[],
|
|
269
|
+
offset: number,
|
|
270
|
+
envelope: Record<string, unknown> = {},
|
|
271
|
+
) {
|
|
231
272
|
const total = items.reduce((length, item) => length + item.text.length, 0);
|
|
232
273
|
if (offset > total) throw new Error('Context offset is beyond the requested range');
|
|
233
274
|
|
|
@@ -257,6 +298,7 @@ export function contextPage(batch: string, selected: Selected, items: Evidence[]
|
|
|
257
298
|
items.slice(0, cursor.index).reduce((length, item) => length + item.text.length, 0) +
|
|
258
299
|
cursor.offset;
|
|
259
300
|
return {
|
|
301
|
+
...envelope,
|
|
260
302
|
batch,
|
|
261
303
|
selected,
|
|
262
304
|
contextOnly: true,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import type { PreparedReview } from './evidence.js';
|
|
3
|
+
|
|
4
|
+
const ownedReviews = new WeakSet<PreparedReview>();
|
|
5
|
+
/** Share one private frozen input between delivery and publication, never caller-owned state. */
|
|
6
|
+
export function ownReview(review: PreparedReview): PreparedReview {
|
|
7
|
+
if (ownedReviews.has(review)) return review;
|
|
8
|
+
const sources = [
|
|
9
|
+
...review.successfulSources,
|
|
10
|
+
...review.snapshots.map((snapshot) => snapshot.source),
|
|
11
|
+
...review.evidence,
|
|
12
|
+
...review.tips,
|
|
13
|
+
...review.checkpoints,
|
|
14
|
+
];
|
|
15
|
+
const first = sources[0];
|
|
16
|
+
if (
|
|
17
|
+
sources.some(
|
|
18
|
+
(source) =>
|
|
19
|
+
source.sessionId !== first?.sessionId || resolve(source.file) !== resolve(first.file),
|
|
20
|
+
) ||
|
|
21
|
+
review.sourceDefaults.some((source) => source.sessionId !== first?.sessionId)
|
|
22
|
+
)
|
|
23
|
+
throw new Error('A capture review plan requires one frozen session source.');
|
|
24
|
+
const copy = structuredClone(review);
|
|
25
|
+
ownedReviews.add(copy);
|
|
26
|
+
return copy;
|
|
27
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { CreateAgentSessionOptions } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
|
|
3
|
+
export interface ReviewerBudget {
|
|
4
|
+
contextWindow: number;
|
|
5
|
+
responseReserve: number;
|
|
6
|
+
framingReserve: number;
|
|
7
|
+
maxInputTokens: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class ReviewerBudgetError extends Error {
|
|
11
|
+
override name = 'ReviewerBudgetError';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Conservative estimate, not provider token accounting. Includes JSON escaping and Unicode. */
|
|
15
|
+
export function estimateReviewerTokens(value: unknown): number {
|
|
16
|
+
const json = JSON.stringify(value);
|
|
17
|
+
if (json === undefined) throw new ReviewerBudgetError('Reviewer input is not serializable');
|
|
18
|
+
// One token per UTF-8 byte deliberately overestimates ordinary text and schemas.
|
|
19
|
+
return Buffer.byteLength(json, 'utf8');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function getReviewerBudget(
|
|
23
|
+
model: NonNullable<CreateAgentSessionOptions['model']>,
|
|
24
|
+
): ReviewerBudget {
|
|
25
|
+
const { contextWindow, maxTokens } = model;
|
|
26
|
+
if (
|
|
27
|
+
!Number.isSafeInteger(contextWindow) ||
|
|
28
|
+
contextWindow <= 0 ||
|
|
29
|
+
!Number.isSafeInteger(maxTokens) ||
|
|
30
|
+
maxTokens <= 0
|
|
31
|
+
) {
|
|
32
|
+
throw new ReviewerBudgetError('Reviewer requires positive model contextWindow and maxTokens');
|
|
33
|
+
}
|
|
34
|
+
// Reserve the entire declared response ceiling, including thinking. Do not rely
|
|
35
|
+
// on provider defaults, observed usage, or Pi's less conservative context estimate.
|
|
36
|
+
const responseReserve = maxTokens;
|
|
37
|
+
// Leave additional room for provider framing and a small host handoff envelope.
|
|
38
|
+
const framingReserve = Math.max(1024, Math.ceil(contextWindow * 0.05));
|
|
39
|
+
const maxInputTokens = contextWindow - responseReserve - framingReserve;
|
|
40
|
+
const budget = { contextWindow, responseReserve, framingReserve, maxInputTokens };
|
|
41
|
+
assertReviewerFits(budget, 1, 'minimum framing and response reserve');
|
|
42
|
+
return budget;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function assertReviewerFits(budget: ReviewerBudget, tokens: number, label: string): void {
|
|
46
|
+
if (tokens > budget.maxInputTokens) {
|
|
47
|
+
throw new ReviewerBudgetError(
|
|
48
|
+
`Reviewer ${label} exceeds context budget (${tokens} estimated input tokens, ` +
|
|
49
|
+
`${budget.maxInputTokens} available after response/thinking and framing reserves). ` +
|
|
50
|
+
'Split the input or hand off host-owned state to a fresh reviewer step.',
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|