@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
@@ -0,0 +1,111 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, mkdirSync, openSync, realpathSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import type { DatabaseSync } from 'node:sqlite';
5
+ import { openPrivateSqlite } from './private-sqlite.mjs';
6
+ import type { ReadyManifest } from './capture-handoff.js';
7
+
8
+ export const CAPTURE_MAX_ATTEMPTS = 2;
9
+ export const CAPTURE_RETRY_DELAY_MS = 60_000;
10
+
11
+ export type CaptureJob = {
12
+ manifest: ReadyManifest;
13
+ state: 'queued' | 'completed' | 'failed';
14
+ retryEligible: boolean;
15
+ diagnostic: string | null;
16
+ attemptCount: number;
17
+ activeAttemptId: string | null;
18
+ nextAttemptAt: number | null;
19
+ revision: number;
20
+ };
21
+
22
+ export type CaptureStatus = {
23
+ paused: boolean;
24
+ jobs: Array<CaptureJob & { blockedBy: string | null }>;
25
+ };
26
+
27
+ export class CaptureRetryableError extends Error {}
28
+
29
+ // Preparation has already persisted this classified failure and abandoned its
30
+ // attempt. The worker must not replace it with a generic execution failure.
31
+ export class CapturePreparationError extends Error {
32
+ constructor(
33
+ message: string,
34
+ readonly category: string,
35
+ readonly retryEligible: boolean,
36
+ ) {
37
+ super(message);
38
+ this.name = 'CapturePreparationError';
39
+ }
40
+ }
41
+
42
+ // One object per acquired OS lock, never recycled after release. An attempt is
43
+ // valid only while it is that object's current identity, not merely its job ID.
44
+ export type CaptureAttempt = { readonly jobId: string; readonly id: string };
45
+ const owners = new Map<string, CaptureWorkerOwnership>();
46
+
47
+ export class CaptureWorkerOwnership {
48
+ private active: CaptureAttempt | undefined;
49
+ private constructor(
50
+ private readonly file: string,
51
+ private readonly lock: DatabaseSync,
52
+ ) {}
53
+
54
+ static claim(filename: string): CaptureWorkerOwnership {
55
+ if (filename === ':memory:') throw Error('Worker ownership requires a durable database');
56
+ // Admission after disabled startup may have no foreground database yet.
57
+ // Exclusive synchronous creation cannot drop an existing store's POSIX locks.
58
+ mkdirSync(dirname(resolve(filename)), { recursive: true, mode: 0o700 });
59
+ try {
60
+ closeSync(openSync(filename, 'ax', 0o600));
61
+ } catch (error) {
62
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
63
+ }
64
+ const file = realpathSync(resolve(filename));
65
+ // Never open/close a second descriptor for a lock file owned by this process:
66
+ // POSIX would release all of this process's locks on that inode.
67
+ if (owners.has(file)) throw Error('A capture worker already owns this database');
68
+ const lockFile = file + '.worker-lock';
69
+ mkdirSync(dirname(lockFile), { recursive: true, mode: 0o700 });
70
+ const lock = openPrivateSqlite(lockFile);
71
+ try {
72
+ lock.exec('BEGIN IMMEDIATE');
73
+ } catch (error) {
74
+ lock.close();
75
+ throw error;
76
+ }
77
+ const owner = new CaptureWorkerOwnership(file, lock);
78
+ owners.set(file, owner);
79
+ return owner;
80
+ }
81
+
82
+ assertStore(filename: string): void {
83
+ if (owners.get(this.file) !== this || realpathSync(resolve(filename)) !== this.file)
84
+ throw Error('No matching capture worker ownership');
85
+ }
86
+
87
+ startAttempt(jobId: string): CaptureAttempt {
88
+ if (owners.get(this.file) !== this) throw Error('Capture worker ownership was released');
89
+ if (this.active) throw Error('A capture attempt is already active');
90
+ this.active = Object.freeze({ jobId, id: randomUUID() });
91
+ return this.active;
92
+ }
93
+
94
+ assertAttempt(attempt: CaptureAttempt): void {
95
+ if (owners.get(this.file) !== this || this.active !== attempt)
96
+ throw Error('No matching active capture attempt');
97
+ }
98
+
99
+ abandon(attempt: CaptureAttempt): void {
100
+ this.assertAttempt(attempt);
101
+ this.active = undefined;
102
+ }
103
+
104
+ release(): void {
105
+ // Invalidate callbacks BEFORE closing the descriptor, even if close fails.
106
+ this.active = undefined;
107
+ if (owners.get(this.file) !== this) return;
108
+ owners.delete(this.file);
109
+ this.lock.close();
110
+ }
111
+ }
@@ -0,0 +1,145 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import type { Proposal, TaskChange, TaskSnapshot } from './proposals.js';
3
+ import type { FindingRecord, FoldedFinding } from './review-findings.js';
4
+ import { satisfies, snapshot, type TaskRecord } from './taskwarrior.js';
5
+
6
+ export type CaptureMatches = ReturnType<typeof resolveCaptureMatches>;
7
+ export type ResolvedCapture = {
8
+ record: FindingRecord;
9
+ state: FoldedFinding;
10
+ matches: CaptureMatches;
11
+ };
12
+
13
+ /** Candidate membership is not identity. Never choose the first of several matches. */
14
+ export function resolveCaptureMatches(
15
+ tasks: readonly TaskRecord[],
16
+ proposals: readonly Proposal[],
17
+ ambiguous = false,
18
+ intentTarget?: string,
19
+ ) {
20
+ const exactTasks = [...new Map(tasks.map((task) => [task['uuid'], task])).values()];
21
+ const exactProposals = [
22
+ ...new Map(proposals.map((proposal) => [proposal.id, proposal])).values(),
23
+ ];
24
+ const pending = exactProposals.filter((proposal) => proposal.state === 'pending');
25
+ const identities = new Set(exactTasks.map((task) => `task:${task['uuid']}`));
26
+ for (const proposal of exactProposals) {
27
+ const change = (proposal.draft ?? proposal).change;
28
+ const uuid =
29
+ change.operation !== 'add'
30
+ ? change.targetUuid
31
+ : (proposal.result?.verified?.uuid ?? proposal.claim);
32
+ identities.add(uuid ? `task:${uuid}` : `proposal:${proposal.id}`);
33
+ }
34
+ ambiguous ||=
35
+ identities.size > 1 ||
36
+ pending.length > 1 ||
37
+ (!!intentTarget && identities.size > 0 && !identities.has(`task:${intentTarget}`));
38
+ const key = !ambiguous && identities.size === 1 ? [...identities][0]! : null;
39
+ const proposal = key ? pending[0] : undefined;
40
+ const task = key ? exactTasks[0] : undefined;
41
+ const expected: TaskSnapshot | null = key
42
+ ? task
43
+ ? snapshot(task)
44
+ : ((proposal?.draft ?? proposal)?.expected ??
45
+ exactProposals.find((item) => item.result?.verified)?.result?.verified ??
46
+ (exactProposals[0]?.draft ?? exactProposals[0])?.expected ??
47
+ null)
48
+ : null;
49
+ return {
50
+ key,
51
+ ambiguous,
52
+ tasks: exactTasks,
53
+ proposals: exactProposals,
54
+ proposal,
55
+ expected,
56
+ verifyOnly: exactProposals.some((item) => ['applying', 'uncertain'].includes(item.state)),
57
+ questions: exactProposals.map((item) => (item.draft ?? item).question),
58
+ };
59
+ }
60
+
61
+ /** Only observable satisfaction can dispose active intent without a proposal. */
62
+ export function captureIsSatisfied(state: FoldedFinding, matches: CaptureMatches): boolean {
63
+ if (matches.ambiguous || matches.proposal) return false;
64
+ const task = matches.tasks[0];
65
+ // An interrupted application is not permission for another write. A live task
66
+ // must prove both the saved operation and the current intent already satisfied.
67
+ if (
68
+ matches.verifyOnly &&
69
+ (!task ||
70
+ matches.proposals.some(
71
+ (proposal) =>
72
+ ['applying', 'uncertain'].includes(proposal.state) &&
73
+ !satisfies(
74
+ (proposal.draft ?? proposal).change,
75
+ task,
76
+ proposal.applicationBefore?.status ??
77
+ (proposal.draft ?? proposal).expected?.status ??
78
+ 'pending',
79
+ ),
80
+ ))
81
+ )
82
+ return false;
83
+ const satisfied = (actual: TaskRecord): boolean =>
84
+ state.status === 'completed'
85
+ ? satisfies(
86
+ {
87
+ operation: 'complete',
88
+ targetUuid: String(actual['uuid']),
89
+ annotations: state.draft?.change.annotations ?? [],
90
+ },
91
+ actual,
92
+ )
93
+ : state.status === 'active' &&
94
+ actual['status'] !== 'deleted' &&
95
+ !!state.draft &&
96
+ satisfies(state.draft.change, actual, actual['status']);
97
+ return !!task && satisfied(task);
98
+ }
99
+
100
+ /** Independent records are not an ancestry-ordered correction chain. */
101
+ export function captureChangesConflict(states: readonly FoldedFinding[]): boolean {
102
+ if (new Set(states.map((state) => state.status)).size > 1) return true;
103
+ const fields = new Map<string, unknown>();
104
+ for (const state of states) {
105
+ const change = state.draft?.change;
106
+ if (!change || change.operation === 'complete') continue;
107
+ for (const [key, value] of Object.entries(change.fields)) {
108
+ if (fields.has(key) && !isDeepStrictEqual(fields.get(key), value)) return true;
109
+ fields.set(key, value);
110
+ }
111
+ }
112
+ return false;
113
+ }
114
+
115
+ /** A consolidated question-free edit must retain each compatible requested change. */
116
+ export function validateConsolidatedChange(change: TaskChange, states: readonly FoldedFinding[]) {
117
+ for (const state of states) {
118
+ const intent = state.draft?.change;
119
+ if (!intent) continue;
120
+ if (intent.annotations.some((annotation) => !change.annotations.includes(annotation)))
121
+ throw new Error('Consolidation dropped requested annotations');
122
+ if (intent.operation !== 'complete') {
123
+ if (
124
+ change.operation === 'complete' ||
125
+ Object.entries(intent.fields).some(
126
+ ([key, value]) =>
127
+ !isDeepStrictEqual(change.fields[key as keyof typeof change.fields], value),
128
+ )
129
+ )
130
+ throw new Error('Consolidation dropped requested fields');
131
+ }
132
+ }
133
+ }
134
+
135
+ /** Group only definite identity, leaving unrelated and uncertain records separate. */
136
+ export function groupCaptureMatches(resolved: readonly ResolvedCapture[]): ResolvedCapture[][] {
137
+ const groups = new Map<string, ResolvedCapture[]>();
138
+ for (const item of resolved) {
139
+ const key = item.matches.key ?? `record:${item.record.id}`;
140
+ const group = groups.get(key) ?? [];
141
+ group.push(item);
142
+ groups.set(key, group);
143
+ }
144
+ return [...groups.values()];
145
+ }
@@ -0,0 +1,51 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { open, readFile, rename, unlink } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import type { CheckpointStore } from './checkpoints.js';
5
+
6
+ export type ProposalNotice = { generation: number; pending: number };
7
+
8
+ /** Derived only from committed SQLite state. The singleton worker serializes replacement. */
9
+ export async function publishProposalNotice(store: CheckpointStore): Promise<void> {
10
+ const notice = store.proposalNotice();
11
+ const target = store.file + '.notice.json';
12
+ const temporary = target + '.' + randomUUID() + '.tmp';
13
+ try {
14
+ const file = await open(temporary, 'wx', 0o600);
15
+ try {
16
+ await file.writeFile(JSON.stringify(notice) + '\n');
17
+ await file.sync();
18
+ } finally {
19
+ await file.close();
20
+ }
21
+ await rename(temporary, target);
22
+ const directory = await open(dirname(target), 'r');
23
+ try {
24
+ await directory.sync();
25
+ } finally {
26
+ await directory.close();
27
+ }
28
+ } finally {
29
+ await unlink(temporary).catch((error: NodeJS.ErrnoException) => {
30
+ if (error.code !== 'ENOENT') throw error;
31
+ });
32
+ }
33
+ }
34
+
35
+ /** No SQLite descriptors or synchronous filesystem work on the TUI tick. */
36
+ export async function readProposalNotice(database: string): Promise<ProposalNotice | undefined> {
37
+ try {
38
+ const value = JSON.parse(await readFile(database + '.notice.json', 'utf8')) as ProposalNotice;
39
+ if (
40
+ !Number.isSafeInteger(value.generation) ||
41
+ value.generation < 0 ||
42
+ !Number.isSafeInteger(value.pending) ||
43
+ value.pending < 0
44
+ )
45
+ throw Error('Invalid proposal notice');
46
+ return value;
47
+ } catch (error) {
48
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
49
+ throw error;
50
+ }
51
+ }
@@ -0,0 +1,37 @@
1
+ // SQLite waits off the TUI thread. The transaction is released by close or
2
+ // process death, never by deleting the lock file or guessing whether a PID lives.
3
+ import { setTimeout } from 'node:timers/promises';
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+ import { openPrivateSqlite } from './private-sqlite.mjs';
6
+
7
+ let database;
8
+ try {
9
+ database = openPrivateSqlite(workerData);
10
+ database.exec('PRAGMA busy_timeout = 1000');
11
+ for (;;) {
12
+ try {
13
+ database.exec('BEGIN IMMEDIATE');
14
+ break;
15
+ } catch (error) {
16
+ if (error.errcode !== 5 && error.errcode !== 6) throw error;
17
+ await setTimeout(10);
18
+ }
19
+ }
20
+ parentPort.once('message', () => {
21
+ try {
22
+ database.close();
23
+ } catch (error) {
24
+ parentPort.postMessage({ failed: true, code: error.code, errcode: error.errcode });
25
+ } finally {
26
+ parentPort.close();
27
+ }
28
+ });
29
+ parentPort.postMessage({ acquired: true });
30
+ } catch (error) {
31
+ try {
32
+ database?.close();
33
+ } finally {
34
+ parentPort.postMessage({ failed: true, code: error.code, errcode: error.errcode });
35
+ parentPort.close();
36
+ }
37
+ }
@@ -1,28 +1,41 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import type { FinishPlan } from './checkpoints.js';
3
- import { prepareReview, type Checkpoint, type Source } from './evidence.js';
4
- import { validateSubmission, type ProposalSubmission } from './proposals.js';
3
+ import type { PreparedReview } from './evidence.js';
4
+ import {
5
+ validateReferences,
6
+ validateSubmission,
7
+ type EvidenceReference,
8
+ type ProposalSubmission,
9
+ } from './proposals.js';
10
+ import { ownReview } from './review-plan.js';
5
11
  import {
6
12
  boundedEvidencePage,
7
13
  frozenContext,
8
14
  groupEvidencePage,
15
+ serializedResponse,
9
16
  type PageCursor,
10
17
  type Selected,
11
18
  } from './review-pages.js';
12
19
 
13
- // Only host-selected source preparation creates coverage. Model reads cannot supply
14
- // a plan, move the evidence cursor, or promote supporting context into evidence.
20
+ export type PreparedCapturePage = Readonly<{
21
+ text: string;
22
+ assertReadable(): void;
23
+ accept(): void;
24
+ }>;
25
+
26
+ // Only accepted host-issued pages create coverage. Supporting context never does.
15
27
  export class CaptureReview {
16
28
  readonly id = randomUUID();
17
- private readonly review;
18
29
  private cursor: PageCursor = { index: 0, offset: 0 };
30
+ private pageRead = false;
31
+ private readonly review: PreparedReview;
19
32
 
20
33
  constructor(
21
- source: Source,
22
- reviewed: readonly Checkpoint[],
34
+ review: PreparedReview,
23
35
  private readonly assertActive: () => void,
24
36
  ) {
25
- this.review = prepareReview([source], [...reviewed]);
37
+ // Publication and delivery must observe the same original claims, not caller mutations.
38
+ this.review = ownReview(review);
26
39
  }
27
40
 
28
41
  get hasEvidence(): boolean {
@@ -37,6 +50,51 @@ export class CaptureReview {
37
50
  return structuredClone(this.review.warnings);
38
51
  }
39
52
 
53
+ /** Prepare the complete frozen evidence without acknowledging any delivery. */
54
+ *preparePages(): Generator<PreparedCapturePage> {
55
+ let cursor: PageCursor = { index: 0, offset: 0 };
56
+ do {
57
+ this.assertActive();
58
+ const start = cursor;
59
+ const result = boundedEvidencePage(this.review.evidence, start, (entries, next) => ({
60
+ batch: this.id,
61
+ groups: groupEvidencePage(entries),
62
+ hasMore: next.index < this.review.evidence.length,
63
+ }));
64
+ const end = result.cursor;
65
+ const isNext = () => start.index === this.cursor.index && start.offset === this.cursor.offset;
66
+ const assertReadable = () => {
67
+ this.assertActive();
68
+ const prior =
69
+ end.index < this.cursor.index ||
70
+ (end.index === this.cursor.index && end.offset <= this.cursor.offset);
71
+ if (!isNext() && !prior) throw new Error('Read the next evidence page in order.');
72
+ };
73
+ yield Object.freeze({
74
+ text: serializedResponse(result.data),
75
+ assertReadable,
76
+ // The runner calls this only after accepting the entire text and its budget.
77
+ accept: () => {
78
+ assertReadable();
79
+ if (isNext()) this.cursor = end;
80
+ this.pageRead = true;
81
+ },
82
+ });
83
+ cursor = end;
84
+ } while (cursor.index < this.review.evidence.length);
85
+ }
86
+
87
+ assertEvidenceDelivered(): void {
88
+ this.assertActive();
89
+ if (
90
+ !this.pageRead ||
91
+ this.cursor.index !== this.review.evidence.length ||
92
+ this.cursor.offset !== 0
93
+ )
94
+ throw new Error('Read all evidence pages before finishing');
95
+ }
96
+
97
+ // Direct host readers accept a complete page synchronously.
40
98
  page(envelope: Record<string, unknown> = {}) {
41
99
  this.assertActive();
42
100
  const result = boundedEvidencePage(this.review.evidence, this.cursor, (entries, cursor) => ({
@@ -46,23 +104,37 @@ export class CaptureReview {
46
104
  hasMore: cursor.index < this.review.evidence.length,
47
105
  }));
48
106
  this.cursor = result.cursor;
107
+ this.pageRead = true;
49
108
  return result.data;
50
109
  }
51
110
 
52
- context(args: { batch: string; selected?: Selected; before?: number; offset?: number }): object {
111
+ context(args: {
112
+ batch: string;
113
+ selected?: Selected;
114
+ before?: number;
115
+ skip?: number;
116
+ offset?: number;
117
+ }): object {
53
118
  this.assertActive();
54
119
  if (args.batch !== this.id) throw new Error('No matching open capture in this Pi session.');
55
120
  return frozenContext(this.review, this.id, args);
56
121
  }
57
122
 
123
+ validateReferences(references: readonly EvidenceReference[]) {
124
+ this.assertActive();
125
+ return validateReferences(references, this.review.evidence);
126
+ }
127
+
58
128
  completion(submissions: readonly ProposalSubmission[]) {
59
129
  this.assertActive();
60
130
  if (this.incomplete) throw new Error('Cannot finish incomplete capture scope');
61
- if (!this.hasEvidence) throw new Error('Cannot finish capture without eligible evidence');
62
- if (this.cursor.index !== this.review.evidence.length || this.cursor.offset !== 0)
63
- throw new Error('Read all evidence pages before finishing');
64
131
  if (!Array.isArray(submissions))
65
132
  throw new Error('Capture requires proposals array (empty is valid)');
133
+ if (!this.hasEvidence && submissions.length)
134
+ throw new Error('No evidence for capture proposals');
135
+ // Empty bootstrap jobs never start a reviewer. Actual reviews enforce even empty
136
+ // artifact delivery through CaptureArtifacts.assertDelivered() before staging.
137
+ if (this.hasEvidence) this.assertEvidenceDelivered();
66
138
  const sources = submissions.map((submission) =>
67
139
  validateSubmission(submission, this.review.evidence),
68
140
  );
@@ -0,0 +1,63 @@
1
+ import { fitPrefixLength } from './review-pages.js';
2
+ import { ReviewerBudgetError } from './reviewer-budget.js';
3
+
4
+ export type CaptureField =
5
+ | { path: (string | number)[]; value: unknown }
6
+ | { path: (string | number)[]; offset: number; text: string; end: boolean };
7
+
8
+ /** Greedy exact field/chunk batches, measured with the caller's complete current envelope. */
9
+ export function* captureDetailPages(
10
+ value: unknown,
11
+ fits: (page: { fields: CaptureField[] }) => boolean,
12
+ ): Generator<{ fields: CaptureField[] }> {
13
+ let fields: CaptureField[] = [];
14
+ function* leaves(value: unknown, path: (string | number)[]): Generator<[unknown, typeof path]> {
15
+ if (value !== null && typeof value === 'object' && Object.keys(value).length) {
16
+ for (const [key, child] of Object.entries(value)) yield* leaves(child, [...path, key]);
17
+ } else yield [value, path];
18
+ }
19
+ for (const [valueAtPath, path] of leaves(value, [])) {
20
+ if (typeof valueAtPath !== 'string') {
21
+ const field = { path, value: valueAtPath };
22
+ if (fields.length && !fits({ fields: [...fields, field] })) {
23
+ yield { fields };
24
+ fields = [];
25
+ }
26
+ if (!fits({ fields: [...fields, field] }))
27
+ throw new ReviewerBudgetError('Capture detail metadata cannot fit');
28
+ fields.push(field);
29
+ continue;
30
+ }
31
+ let offset = 0;
32
+ do {
33
+ const field = (length: number): CaptureField => ({
34
+ path,
35
+ offset,
36
+ text: valueAtPath.slice(offset, offset + length),
37
+ end: offset + length === valueAtPath.length,
38
+ });
39
+ let length = fitPrefixLength(valueAtPath, offset, (length) =>
40
+ fits({ fields: [...fields, field(length)] }),
41
+ );
42
+ if (
43
+ fields.length &&
44
+ ((!length && offset < valueAtPath.length) || !fits({ fields: [...fields, field(length)] }))
45
+ ) {
46
+ yield { fields };
47
+ fields = [];
48
+ length = fitPrefixLength(valueAtPath, offset, (length) =>
49
+ fits({ fields: [field(length)] }),
50
+ );
51
+ }
52
+ if ((!length && offset < valueAtPath.length) || !fits({ fields: [...fields, field(length)] }))
53
+ throw new ReviewerBudgetError('Capture detail metadata cannot fit with positive progress');
54
+ fields.push(field(length));
55
+ offset += length;
56
+ if (offset < valueAtPath.length) {
57
+ yield { fields };
58
+ fields = [];
59
+ }
60
+ } while (offset < valueAtPath.length);
61
+ }
62
+ if (fields.length) yield { fields };
63
+ }