@loro-dev/roost 0.1.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
@@ -0,0 +1,1344 @@
1
+ import { decodeUtf8, encodeUtf8 } from '../json.js';
2
+ import { generationIn, generationKeyFragment } from './registry.js';
3
+ import { CoverageError, CoverageStore } from './coverage.js';
4
+ /**
5
+ * Durable send tasks and discovery progress for remote sync (RS2-02), the
6
+ * IndexedDB mirror of src/sync/work.rs. A WorkStore persists, per remote
7
+ * target scope, the scheduler's intent to send specific stream operations:
8
+ * frozen task bytes, a dependency wait index, and the discovery cursor of the
9
+ * local enumeration. Semantics are fixed by the RS0-02 independent model: a
10
+ * `done` task never nets against re-discovered content (F1 — dedupe covers
11
+ * every status, and a conflicting fingerprint at an already-discovered
12
+ * position is a typed error, not a silent second task), an `acked_local` task
13
+ * must be re-confirmable after a crash (F2), an `inflight` task stays
14
+ * re-acquirable (F3), and `ready` means status `ready|inflight` with every
15
+ * dependency satisfied at operation precision (review finding C, with the
16
+ * L009/L010/L011 follow-ups): a same-turn predecessor must be *present* with
17
+ * its exact fingerprint, a cross-turn parent must be *closed* with a matching
18
+ * seal fingerprint, every direct parent of the task's turn must be closed,
19
+ * and same-turn transitive closure is proven incrementally by the per-turn
20
+ * prefix watermark (`[0x05]` record) — dep lists stay O(1 + parents) no
21
+ * matter how long the turn grows.
22
+ *
23
+ * Storage layout (private to this module, not a wire format) — byte-for-byte
24
+ * the Rust layout. All keys live in one KV space `rsync_work`. Every key
25
+ * embeds the full scope `(remote_id, generation, stream)` with the registry's
26
+ * full generation identity encoding (`gen_len[1] || gen[..] || source_tag[1]`),
27
+ * so equal bytes with different provenance never share a task and a superseded
28
+ * generation's tasks are physically unreachable from the new one (S6). Values
29
+ * are `[version byte] || serde_json` payloads with a fixed DTO field order
30
+ * (deterministic and identical to the Rust serde encoding); the leading
31
+ * version byte is authoritative and a mismatch is `unsupportedVersion`, never
32
+ * silently decoded.
33
+ *
34
+ * | Keys | Value |
35
+ * | --- | --- |
36
+ * | `[0x01] \|\| scope \|\| turn[16] \|\| seq[4 BE]` | task record: `task_seq` (monotonic per scope), fingerprint, deps, status, attempts, frozen bytes (`null` = bytes not fetched locally yet) |
37
+ * | `[0x02] \|\| scope \|\| dep_turn[16] \|\| dep_seq[4 BE]` | wait index: sorted, deduped list of tasks waiting on this dependency; maintained in the same transaction as task status changes |
38
+ * | `[0x03] \|\| scope \|\| "cursor"` | discovery state: `cursor` (last enumerated turn id, `null` = not started) and `enumerated_count` |
39
+ * | `[0x04] \|\| scope \|\| "taskseq"` | task sequence allocator `{next}` |
40
+ * | `[0x05] \|\| scope \|\| turn[16]` | same-turn prefix watermark `{upto}`: every seq in `0..=upto` is present on the target with the exact fingerprint its task record declared; advances one confirmed op per step, never regresses |
41
+ * | `[0x06] \|\| scope \|\| status_tag[1] \|\| task_seq[8 BE]` | status candidate index (RS2-04): one row per non-done task, value `turn[16] \|\| seq[4 BE]`; maintained in the same transaction as every status change |
42
+ * | `[0x07] \|\| scope \|\| "statusidx"` | status-index completeness marker; absent on pre-index scopes, which fall back to full task scans until `resume` rebuilds the index |
43
+ * | `[0x08] \|\| scope \|\| turn[16]` | open-turn record `{offered_upto}` (G009): one row per turn discovered before its seal; deleted in the same transaction that persists the turn's seal op |
44
+ * | `[0x09] \|\| scope \|\| "openidx"` | open-index completeness marker; absent on scopes written before open tracking existed |
45
+ * | `[0x0a] \|\| scope \|\| "events"` | local event checkpoint: version byte + u64 BE, committed with tasks after comparing the previous checkpoint |
46
+ * | `[0x0b] \|\| scope \|\| turn[16] \|\| seq[4 BE]` | empty value; ready/inflight candidate in dependency order |
47
+ * | `[0x0c] \|\| scope` | version byte; complete ordered candidate index, including atomic legacy rebuild |
48
+ *
49
+ * Transactions (T1/T2/T3), each a single IDB readwrite transaction (a throw
50
+ * aborts the native transaction, so a rejected step commits nothing):
51
+ * - T1 (`discoverBatch`): insert-if-absent task creation, wait-index
52
+ * maintenance, sequence allocation, open-turn tracking and the monotonic
53
+ * cursor advance commit atomically; a crash before commit loses nothing and
54
+ * the replay is idempotent.
55
+ * - T2 (`acquire`): the CAS to `inflight` and the attempt increment commit
56
+ * before any network send; the frozen bytes are returned to the caller. The
57
+ * same dependency gate as `ready` runs inside this transaction.
58
+ * - T3 (`ack`/`confirm`): compare-and-swap on the attempt token; `confirm`
59
+ * with the registry check enabled re-reads the registry's current
60
+ * generation *inside* its own write transaction (G009) and refuses the
61
+ * confirmation when it no longer matches the task's scope.
62
+ *
63
+ * Cross-module read coupling: the dependency gate runs through the coverage
64
+ * store's in-transaction readers (`presentExactIn`/`closedMatchesIn`), and
65
+ * `confirm` writes coverage through `markPresentIn` in the same transaction
66
+ * as the task completion (T3/T5). This store never writes coverage keys
67
+ * directly and never touches the network.
68
+ */
69
+ /** KV space holding all work-store keys. */
70
+ export const WORK_SPACE = 'rsync_work';
71
+ /** Current record encoding version. Version 2 binds dependencies to exact
72
+ * fingerprints and persists seal/parents for the atomic confirm (review
73
+ * finding C); version-1 records are refused as unsupported, never decoded. */
74
+ export const RECORD_VERSION = 2;
75
+ export const TASK_KEY_TAG = 0x01;
76
+ export const WAIT_KEY_TAG = 0x02;
77
+ export const CURSOR_KEY_TAG = 0x03;
78
+ /** Local event checkpoint, independent of Turn ID ordering. */
79
+ export const EVENT_CURSOR_KEY_TAG = 0x0a;
80
+ /** Ready/inflight tasks ordered by Turn ID and seq, independent of arrival. */
81
+ export const ORDERED_CANDIDATE_TAG = 0x0b;
82
+ export const ORDERED_CANDIDATE_MARKER_TAG = 0x0c;
83
+ export const TASKSEQ_KEY_TAG = 0x04;
84
+ export const PREFIX_KEY_TAG = 0x05;
85
+ /** Per-status candidate index keys (RS2-04). */
86
+ export const STATUS_INDEX_KEY_TAG = 0x06;
87
+ export const STATUS_INDEX_MARKER_TAG = 0x07;
88
+ /** Open-turn record keys (G009). */
89
+ export const OPEN_TURN_KEY_TAG = 0x08;
90
+ export const OPEN_INDEX_MARKER_TAG = 0x09;
91
+ /** Maximum frozen bytes of one task's package. */
92
+ export const MAX_TASK_BYTES = 1 << 20;
93
+ /** Maximum direct dependencies recorded on one task (cross-turn parent refs
94
+ * plus one same-turn predecessor — never the turn's length, L010). */
95
+ export const MAX_TASK_DEPS = 4096;
96
+ /** Maximum waiters tracked per dependency. */
97
+ export const MAX_WAITERS_PER_DEP = 1 << 20;
98
+ /** Errors returned by WorkStore. `code` mirrors the Rust WorkError variants;
99
+ * `cause` carries structured fields where the Rust variant has them. Native
100
+ * IDB failures propagate as DOMExceptions, as in the registry. */
101
+ export class WorkError extends Error {
102
+ code;
103
+ constructor(code, message = code, options) {
104
+ super(message, options);
105
+ this.code = code;
106
+ this.name = 'WorkError';
107
+ }
108
+ }
109
+ const invalid = (message) => new WorkError('invalid', message);
110
+ const corrupt = (message) => new WorkError('corrupt', message);
111
+ const ALL = Number.MAX_SAFE_INTEGER;
112
+ function compareBytes(a, b) {
113
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
114
+ if (a[i] !== b[i])
115
+ return a[i] - b[i];
116
+ return a.length - b.length;
117
+ }
118
+ function equalBytes(a, b) { return compareBytes(a, b) === 0; }
119
+ function cat(...parts) {
120
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
121
+ let n = 0;
122
+ for (const p of parts) {
123
+ out.set(p, n);
124
+ n += p.length;
125
+ }
126
+ return out;
127
+ }
128
+ function hex(bytes) {
129
+ return [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
130
+ }
131
+ /** Smallest byte string strictly greater than `key`, or undefined when `key`
132
+ * is all `0xff` (its range then extends to the end of the space). */
133
+ function successor(key) {
134
+ const out = key.slice();
135
+ for (let i = out.length - 1; i >= 0; i--)
136
+ if (out[i] !== 255) {
137
+ out[i] = out[i] + 1;
138
+ return out.slice(0, i + 1);
139
+ }
140
+ return undefined;
141
+ }
142
+ function id16(id, what) {
143
+ if (!(id instanceof Uint8Array) || id.length !== 16)
144
+ throw invalid(`${what} must be a 16-byte Uint8Array`);
145
+ return id;
146
+ }
147
+ function u32(value, what) {
148
+ if (!Number.isInteger(value) || value < 0 || value > 0xFFFFFFFF)
149
+ throw invalid(`${what} must be a u32`);
150
+ return value;
151
+ }
152
+ function u32be(n) {
153
+ const out = new Uint8Array(4);
154
+ new DataView(out.buffer).setUint32(0, n);
155
+ return out;
156
+ }
157
+ function u64be(n) {
158
+ if (!Number.isSafeInteger(n) || n < 0)
159
+ throw invalid('task_seq must be a non-negative safe integer');
160
+ const out = new Uint8Array(8);
161
+ new DataView(out.buffer).setBigUint64(0, BigInt(n));
162
+ return out;
163
+ }
164
+ function byteArray(value, what) {
165
+ if (!Array.isArray(value) || value.some(v => !Number.isInteger(v) || v < 0 || v > 255))
166
+ throw corrupt(`record JSON: ${what} must be a byte array`);
167
+ return value;
168
+ }
169
+ /** `[version byte] || JSON` with a fixed DTO field order, byte-identical to
170
+ * the Rust serde encoding. */
171
+ function encode(dto) {
172
+ return cat(Uint8Array.of(RECORD_VERSION), encodeUtf8(JSON.stringify(dto)));
173
+ }
174
+ /** Version-byte check + JSON parse; shape errors are corruption, a version
175
+ * mismatch is `unsupportedVersion`, never silently decoded. */
176
+ function checkVersion(bytes) {
177
+ if (!bytes.length)
178
+ throw corrupt('empty record');
179
+ const version = bytes[0];
180
+ if (version !== RECORD_VERSION)
181
+ throw new WorkError('unsupportedVersion', `unsupported work record version: ${version}`);
182
+ try {
183
+ const parsed = JSON.parse(decodeUtf8(bytes.slice(1)));
184
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
185
+ throw Error('record must be an object');
186
+ return parsed;
187
+ }
188
+ catch (e) {
189
+ if (e instanceof WorkError)
190
+ throw e;
191
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
192
+ }
193
+ }
194
+ function checkInnerV(v) {
195
+ if (v !== RECORD_VERSION)
196
+ throw new WorkError('unsupportedVersion', `unsupported work record version: ${String(v)}`);
197
+ }
198
+ /** The scope bytes shared by every key of one `(remote, generation, stream)`:
199
+ * `remote[16] || generationKeyFragment || stream_len[4 BE] || stream[..]`. */
200
+ function scopeBytes(scope) {
201
+ if (!scope.stream.length)
202
+ throw invalid('empty stream');
203
+ const stream = encodeUtf8(scope.stream);
204
+ if (stream.length > 0xFFFFFFFF)
205
+ throw invalid('stream name too long');
206
+ return cat(id16(scope.remote, 'remote id').slice(), generationKeyFragment(scope.generation), u32be(stream.length), stream);
207
+ }
208
+ /** Task record key: `[TASK_KEY_TAG] || scope || turn[16] || seq[4 BE]`. */
209
+ export function taskKey(scope, task) {
210
+ return cat(Uint8Array.of(TASK_KEY_TAG), scopeBytes(scope), id16(task.turn, 'turn id').slice(), u32be(u32(task.seq, 'seq')));
211
+ }
212
+ /** Wait index key: `[WAIT_KEY_TAG] || scope || dep_turn[16] || dep_seq[4 BE]`. */
213
+ export function waitKey(scope, dep) {
214
+ return cat(Uint8Array.of(WAIT_KEY_TAG), scopeBytes(scope), id16(dep.turn, 'dep turn id').slice(), u32be(u32(dep.seq, 'dep seq')));
215
+ }
216
+ function cursorKey(scope) {
217
+ return cat(Uint8Array.of(CURSOR_KEY_TAG), scopeBytes(scope), encodeUtf8('cursor'));
218
+ }
219
+ /** Value: [RECORD_VERSION] || local_event_cursor[8 BE], matching Rust. */
220
+ export function eventCursorKey(scope) {
221
+ return cat(Uint8Array.of(EVENT_CURSOR_KEY_TAG), scopeBytes(scope), encodeUtf8('events'));
222
+ }
223
+ function* eventCursorIn(tx, scope) {
224
+ const raw = yield* tx.get(WORK_SPACE, eventCursorKey(scope));
225
+ if (raw === undefined)
226
+ return 0n;
227
+ if (raw.length > 0 && raw[0] !== RECORD_VERSION)
228
+ throw new WorkError('unsupportedVersion', `unsupported work record version: ${raw[0]}`);
229
+ if (raw.length !== 9)
230
+ throw corrupt('invalid event checkpoint');
231
+ return new DataView(raw.buffer, raw.byteOffset, raw.byteLength).getBigUint64(1);
232
+ }
233
+ function orderedCandidatePrefix(scope) {
234
+ return cat(Uint8Array.of(ORDERED_CANDIDATE_TAG), scopeBytes(scope));
235
+ }
236
+ function orderedCandidateKey(scope, task) {
237
+ return cat(orderedCandidatePrefix(scope), id16(task.turn, 'turn id'), u32be(u32(task.seq, 'seq')));
238
+ }
239
+ function orderedCandidateMarker(scope) {
240
+ return cat(Uint8Array.of(ORDERED_CANDIDATE_MARKER_TAG), scopeBytes(scope));
241
+ }
242
+ function* orderedCandidatesReady(tx, scope) {
243
+ const raw = yield* tx.get(WORK_SPACE, orderedCandidateMarker(scope));
244
+ if (raw === undefined)
245
+ return false;
246
+ if (raw.length !== 1 || raw[0] !== RECORD_VERSION)
247
+ throw corrupt('invalid ordered candidate marker');
248
+ return true;
249
+ }
250
+ function isSendCandidate(status) {
251
+ return status === 'ready' || status === 'inflight';
252
+ }
253
+ function taskseqKey(scope) {
254
+ return cat(Uint8Array.of(TASKSEQ_KEY_TAG), scopeBytes(scope), encodeUtf8('taskseq'));
255
+ }
256
+ function prefixKey(scope, turn) {
257
+ return cat(Uint8Array.of(PREFIX_KEY_TAG), scopeBytes(scope), id16(turn, 'turn id').slice());
258
+ }
259
+ /** The status index tag of a status, or undefined for `done` (done tasks are
260
+ * not candidates of anything and stay out of the index). */
261
+ function statusTag(status) {
262
+ switch (status) {
263
+ case 'pending_local': return 1;
264
+ case 'ready': return 2;
265
+ case 'inflight': return 3;
266
+ case 'acked_local': return 4;
267
+ case 'done': return undefined;
268
+ }
269
+ }
270
+ /** Status index row prefix for one status: `[STATUS_INDEX_KEY_TAG] || scope ||
271
+ * status_tag[1]`; a full row key appends `task_seq[8 BE]`. */
272
+ function statusIndexPrefix(scope, tag) {
273
+ return cat(Uint8Array.of(STATUS_INDEX_KEY_TAG), scopeBytes(scope), Uint8Array.of(tag));
274
+ }
275
+ function statusIndexMarkerKey(scope) {
276
+ return cat(Uint8Array.of(STATUS_INDEX_MARKER_TAG), scopeBytes(scope), encodeUtf8('statusidx'));
277
+ }
278
+ function openTurnPrefix(scope) {
279
+ return cat(Uint8Array.of(OPEN_TURN_KEY_TAG), scopeBytes(scope));
280
+ }
281
+ function openTurnKey(scope, turn) {
282
+ return cat(openTurnPrefix(scope), id16(turn, 'turn id').slice());
283
+ }
284
+ function openIndexMarkerKey(scope) {
285
+ return cat(Uint8Array.of(OPEN_INDEX_MARKER_TAG), scopeBytes(scope), encodeUtf8('openidx'));
286
+ }
287
+ function sameGeneration(a, b) {
288
+ return a.source === b.source && equalBytes(a.bytes, b.bytes);
289
+ }
290
+ function refKey(task) {
291
+ return `${hex(task.turn)}/${task.seq}`;
292
+ }
293
+ function taskRefFromDto(dto) {
294
+ return { turn: Uint8Array.from(dto.turn), seq: dto.seq };
295
+ }
296
+ function compareRefs(a, b) {
297
+ return compareBytes(a.turn, b.turn) || a.seq - b.seq;
298
+ }
299
+ function compareDeps(a, b) {
300
+ return compareBytes(a.turn, b.turn) || a.seq - b.seq || compareBytes(a.fp, b.fp);
301
+ }
302
+ /** Stored invariants are recomputed and verified, never trusted: a record
303
+ * whose shape disagrees with its own key or status is corruption. */
304
+ function checkTask(key, dto) {
305
+ if (!equalBytes(dto.turn, key.turn) || dto.seq !== key.seq)
306
+ throw corrupt('record identity disagrees with its key');
307
+ for (let i = 1; i < dto.deps.length; i++)
308
+ if (compareDeps(dto.deps[i - 1], dto.deps[i]) >= 0)
309
+ throw corrupt('deps not sorted or deduped');
310
+ if (dto.deps.some(dep => equalBytes(dep.turn, key.turn) && dep.seq === key.seq))
311
+ throw corrupt('task cannot depend on itself');
312
+ const consistent = (() => {
313
+ switch (dto.status) {
314
+ case 'pending_local': return !dto.adopted && dto.bytes === null;
315
+ case 'ready': return !dto.adopted && dto.bytes !== null;
316
+ case 'inflight':
317
+ case 'acked_local': return !dto.adopted && dto.bytes !== null && dto.attempts >= 1;
318
+ // An adopted task starts done with zero attempts and may never
319
+ // have had local bytes; a confirmed done has the frozen package.
320
+ case 'done': return dto.adopted || (dto.bytes !== null && dto.attempts >= 1);
321
+ }
322
+ })();
323
+ if (!consistent)
324
+ throw corrupt('task status inconsistent with bytes/attempts');
325
+ }
326
+ function toTaskDto(raw) {
327
+ let dto;
328
+ try {
329
+ if (!Number.isInteger(raw.v) || !Number.isSafeInteger(raw.task_seq) || !Number.isInteger(raw.seq) || !Number.isInteger(raw.attempts) ||
330
+ typeof raw.is_seal !== 'boolean' || !Array.isArray(raw.deps) || !Array.isArray(raw.parents) ||
331
+ typeof raw.status !== 'string' || !(raw.bytes === null || Array.isArray(raw.bytes)))
332
+ throw Error('task fields');
333
+ const status = raw.status;
334
+ if (!['pending_local', 'ready', 'inflight', 'acked_local', 'done'].includes(status))
335
+ throw Error('task status');
336
+ dto = {
337
+ v: raw.v,
338
+ task_seq: raw.task_seq,
339
+ turn: byteArray(raw.turn, 'turn'),
340
+ seq: raw.seq,
341
+ fingerprint: byteArray(raw.fingerprint, 'fingerprint'),
342
+ deps: raw.deps.map((dep, i) => {
343
+ if (typeof dep !== 'object' || dep === null || Array.isArray(dep))
344
+ throw Error('dep must be an object');
345
+ const o = dep;
346
+ if (!Number.isInteger(o.seq))
347
+ throw Error('dep seq');
348
+ return { turn: byteArray(o.turn, `deps[${i}].turn`), seq: o.seq, fp: byteArray(o.fp, `deps[${i}].fp`) };
349
+ }),
350
+ is_seal: raw.is_seal,
351
+ parents: raw.parents.map((parent, i) => {
352
+ if (typeof parent !== 'object' || parent === null || Array.isArray(parent))
353
+ throw Error('parent must be an object');
354
+ const o = parent;
355
+ return { turn: byteArray(o.turn, `parents[${i}].turn`), seal_fp: byteArray(o.seal_fp, `parents[${i}].seal_fp`) };
356
+ }),
357
+ status: status,
358
+ attempts: raw.attempts,
359
+ bytes: raw.bytes === null ? null : byteArray(raw.bytes, 'bytes'),
360
+ // Records written before adoption existed carry no field.
361
+ adopted: raw.adopted === undefined ? false : raw.adopted === true,
362
+ wire: raw.wire === undefined || raw.wire === null ? undefined : byteArray(raw.wire, 'wire'),
363
+ };
364
+ }
365
+ catch (e) {
366
+ if (e instanceof WorkError)
367
+ throw e;
368
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
369
+ }
370
+ checkInnerV(dto.v);
371
+ if (dto.turn.length !== 16)
372
+ throw corrupt('record JSON: turn must be 16 bytes');
373
+ if (dto.fingerprint.length !== 32)
374
+ throw corrupt('record JSON: fingerprint must be 32 bytes');
375
+ for (const dep of dto.deps)
376
+ if (dep.turn.length !== 16 || dep.fp.length !== 32)
377
+ throw corrupt('record JSON: dep turn/fp size');
378
+ for (const parent of dto.parents)
379
+ if (parent.turn.length !== 16 || parent.seal_fp.length !== 32)
380
+ throw corrupt('record JSON: parent turn/seal_fp size');
381
+ if (raw.adopted !== undefined && typeof raw.adopted !== 'boolean')
382
+ throw corrupt('record JSON: adopted must be a boolean');
383
+ return dto;
384
+ }
385
+ function taskInfoFromDto(dto) {
386
+ return {
387
+ task: { turn: Uint8Array.from(dto.turn), seq: dto.seq },
388
+ taskSeq: dto.task_seq,
389
+ status: dto.status,
390
+ attempts: dto.attempts,
391
+ fingerprint: Uint8Array.from(dto.fingerprint),
392
+ deps: dto.deps.map(dep => ({ turn: Uint8Array.from(dep.turn), seq: dep.seq, fingerprint: Uint8Array.from(dep.fp) })),
393
+ frozenBytes: dto.bytes === null ? undefined : dto.bytes.length,
394
+ };
395
+ }
396
+ /**
397
+ * Task store over a shared IndexedDbStorage owner.
398
+ *
399
+ * Construct with the same IndexedDbStorage the host's Store, RemoteRegistry
400
+ * and CoverageStore use, so tasks, coverage and stream content commit through
401
+ * one fixed owner. The store never opens its own connection and never touches
402
+ * the network.
403
+ */
404
+ export class WorkStore {
405
+ storage;
406
+ /** The coverage store over the same storage owner, used for the
407
+ * dependency gate's in-transaction reads and the confirm's atomic mark. */
408
+ coverage;
409
+ constructor(storage) {
410
+ this.storage = storage;
411
+ this.coverage = new CoverageStore(storage);
412
+ }
413
+ *loadTask(tx, scope, task) {
414
+ const raw = yield* tx.get(WORK_SPACE, taskKey(scope, task));
415
+ if (raw === undefined)
416
+ return undefined;
417
+ const dto = toTaskDto(checkVersion(raw));
418
+ checkTask(task, dto);
419
+ return dto;
420
+ }
421
+ /** Persist one page of enumerated operations in a single write
422
+ * transaction (T1): insert-if-absent task creation, wait-index
423
+ * maintenance, task sequence allocation, open-turn tracking (G009) and
424
+ * the monotonic cursor advance commit atomically or not at all. The
425
+ * cursor never regresses; it only ever covers work already persisted. */
426
+ async discoverBatch(scope, ops, cursorAdvance) {
427
+ return (await this.discoverBatchInner(scope, ops, cursorAdvance));
428
+ }
429
+ /** Last local event covered by this target's durable discovery tasks. */
430
+ async eventCursor(scope) {
431
+ return this.storage.transact(false, tx => eventCursorIn(tx, scope));
432
+ }
433
+ /** Tasks and checkpoint commit together. A stale expected position
434
+ * returns undefined without writing anything. Also advances the compatible
435
+ * Turn ID high-water mark, without using it to skip late older events. */
436
+ async discoverEventBatch(scope, ops, expected, advance) {
437
+ if (expected < 0n || advance <= expected || advance > 0xffffffffffffffffn)
438
+ throw invalid('event checkpoint must advance within u64');
439
+ let turnCursor;
440
+ for (const op of ops)
441
+ if (turnCursor === undefined || compareBytes(op.turn, turnCursor) > 0)
442
+ turnCursor = op.turn;
443
+ return this.discoverBatchInner(scope, ops, turnCursor, { expected, advance });
444
+ }
445
+ async discoverBatchInner(scope, ops, cursorAdvance, eventWindow) {
446
+ for (const op of ops) {
447
+ id16(op.turn, 'turn id');
448
+ u32(op.seq, 'seq');
449
+ fp32check(op.fingerprint);
450
+ }
451
+ if (cursorAdvance !== undefined)
452
+ id16(cursorAdvance, 'cursor advance');
453
+ const coverage = this.coverage;
454
+ return this.storage.transact(true, function* (tx) {
455
+ if (eventWindow !== undefined && (yield* eventCursorIn(tx, scope)) !== eventWindow.expected)
456
+ return undefined;
457
+ const indexReady = yield* ensureStatusIndex(tx, scope);
458
+ const openReady = yield* ensureOpenIndex(tx, scope);
459
+ // Per-turn streaming tracker of this batch (G009): the highest
460
+ // offered seq + 1 and whether the turn's seal op is among the
461
+ // offered ops; applied to the open-turn set below, in the same
462
+ // transaction as the tasks themselves.
463
+ const openTouched = new Map();
464
+ const outcomes = [];
465
+ for (const op of ops) {
466
+ if (openReady) {
467
+ const key = hex(op.turn);
468
+ const entry = openTouched.get(key) ?? { turn: op.turn, upto: 0, seal: false };
469
+ entry.upto = Math.max(entry.upto, op.seq + 1);
470
+ entry.seal ||= op.isSeal;
471
+ openTouched.set(key, entry);
472
+ }
473
+ if (op.bytesLen > MAX_TASK_BYTES)
474
+ throw invalid(`task package exceeds ${MAX_TASK_BYTES} bytes`);
475
+ if (op.bytes !== null && op.bytes.length !== op.bytesLen)
476
+ throw invalid(`bytes length ${op.bytes.length} does not match declared ${op.bytesLen}`);
477
+ if (op.deps.length > MAX_TASK_DEPS)
478
+ throw invalid(`task dependency limit ${MAX_TASK_DEPS} reached`);
479
+ if (op.deps.some(dep => equalBytes(dep.turn, op.turn) && dep.seq === op.seq))
480
+ throw invalid('task cannot depend on itself');
481
+ // A same-turn dependency is the streaming predecessor: an op
482
+ // at seq s carries exactly one, `(turn, s-1, exact fp)`; seq 0
483
+ // carries none. Transitive prefix closure is proven
484
+ // incrementally by the per-turn watermark (module docs), so
485
+ // dep lists stay O(1 + parents) and a long turn's seal never
486
+ // collides with MAX_TASK_DEPS (review C follow-up, L010).
487
+ const sameTurn = op.deps.filter(dep => equalBytes(dep.turn, op.turn));
488
+ const shapeOk = op.seq === 0
489
+ ? sameTurn.length === 0
490
+ : sameTurn.length === 1 && sameTurn[0].seq === op.seq - 1;
491
+ if (!shapeOk)
492
+ throw invalid(`op seq ${op.seq} must list exactly its direct same-turn predecessor (seq ${op.seq - 1}) with its exact fingerprint`);
493
+ const deps = op.deps.map(dep => ({
494
+ turn: [...id16(dep.turn, 'dep turn id')],
495
+ seq: u32(dep.seq, 'dep seq'),
496
+ fp: [...fp32check(dep.fingerprint)],
497
+ }));
498
+ deps.sort(compareDeps);
499
+ const task = { turn: op.turn, seq: op.seq };
500
+ const existing = yield* loadTaskOf(tx, scope, task);
501
+ if (existing !== undefined) {
502
+ if (!equalBytes(existing.fingerprint, op.fingerprint))
503
+ throw new WorkError('contentConflict', `content conflict: existing fingerprint differs`, { cause: { task, existing: Uint8Array.from(existing.fingerprint) } });
504
+ // F1: dedupe covers every status, including done — a
505
+ // repeated discovery after completion is a plain
506
+ // duplicate and never rewrites the record.
507
+ outcomes.push({ kind: 'duplicate' });
508
+ continue;
509
+ }
510
+ const taskSeq = yield* allocTaskSeq(tx, scope);
511
+ // Adoption (RS2-04): an op the target already confirmed
512
+ // present with this exact fingerprint needs no upload.
513
+ const adopted = yield* coverage.presentExactIn(tx, scope, op.turn, op.seq, op.fingerprint);
514
+ const status = adopted ? 'done' : op.bytes !== null ? 'ready' : 'pending_local';
515
+ const dto = {
516
+ v: RECORD_VERSION,
517
+ task_seq: taskSeq,
518
+ turn: [...op.turn],
519
+ seq: op.seq,
520
+ fingerprint: [...op.fingerprint],
521
+ deps,
522
+ is_seal: op.isSeal,
523
+ parents: op.parents.map(parent => ({
524
+ turn: [...id16(parent.turnId, 'parent turn id')],
525
+ seal_fp: [...fp32check(parent.sealFp)],
526
+ })),
527
+ status,
528
+ attempts: 0,
529
+ bytes: op.bytes === null ? null : [...op.bytes],
530
+ adopted,
531
+ };
532
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
533
+ if (adopted) {
534
+ outcomes.push({ kind: 'adopted', task });
535
+ continue;
536
+ }
537
+ if (indexReady)
538
+ yield* statusIndexTrack(tx, scope, taskSeq, task, status);
539
+ if (isSendCandidate(status))
540
+ yield* tx.put(WORK_SPACE, orderedCandidateKey(scope, task), new Uint8Array());
541
+ // Wait index: the new task waits on each of its deps, in the
542
+ // same transaction as the task itself.
543
+ for (const dep of deps)
544
+ yield* waitAdd(tx, scope, { turn: Uint8Array.from(dep.turn), seq: dep.seq }, task);
545
+ outcomes.push({ kind: 'created', task });
546
+ }
547
+ // Open-turn set maintenance (G009), per turn of this batch: a
548
+ // turn whose seal op was just offered leaves the set; any other
549
+ // offered turn keeps a record whose `offered_upto` only ever
550
+ // advances. A duplicate replay reproduces the identical writes.
551
+ if (openReady) {
552
+ for (const entry of [...openTouched.values()].sort((a, b) => compareBytes(a.turn, b.turn))) {
553
+ const key = openTurnKey(scope, entry.turn);
554
+ if (entry.seal) {
555
+ yield* tx.delete(WORK_SPACE, key);
556
+ continue;
557
+ }
558
+ const raw = yield* tx.get(WORK_SPACE, key);
559
+ const existing = raw === undefined ? undefined : toOpenDto(checkVersion(raw)).offered_upto;
560
+ const merged = existing === undefined ? entry.upto : Math.max(existing, entry.upto);
561
+ if (existing !== merged)
562
+ yield* tx.put(WORK_SPACE, key, encode({ v: RECORD_VERSION, offered_upto: merged }));
563
+ }
564
+ }
565
+ // The prefix watermark follows coverage as far as the newly
566
+ // persisted (or previously known) task records allow; coverage
567
+ // may also have advanced through external paths since the last
568
+ // discovery, so every touched turn is re-walked, duplicates
569
+ // included.
570
+ const touchedTurns = new Map();
571
+ for (const op of ops)
572
+ touchedTurns.set(hex(op.turn), op.turn);
573
+ for (const turn of [...touchedTurns.values()].sort(compareBytes))
574
+ yield* advancePrefixIn(tx, scope, coverage, turn);
575
+ // Cursor: monotonic advance, only ever in this same transaction.
576
+ const key = cursorKey(scope);
577
+ const raw = yield* tx.get(WORK_SPACE, key);
578
+ const old = raw === undefined
579
+ ? { v: RECORD_VERSION, cursor: null, enumerated_count: 0 }
580
+ : toCursorDto(checkVersion(raw));
581
+ let newCursor = old.cursor;
582
+ if (cursorAdvance !== undefined && (newCursor === null || compareBytes(cursorAdvance, newCursor) > 0))
583
+ newCursor = [...cursorAdvance];
584
+ const created = outcomes.filter(o => o.kind === 'created' || o.kind === 'adopted').length;
585
+ const enumeratedCount = old.enumerated_count + created;
586
+ if ((newCursor === null) !== (old.cursor === null) || (newCursor !== null && old.cursor !== null && !equalBytes(newCursor, old.cursor)) || enumeratedCount !== old.enumerated_count)
587
+ yield* tx.put(WORK_SPACE, key, encode({ v: RECORD_VERSION, cursor: newCursor, enumerated_count: enumeratedCount }));
588
+ if (eventWindow !== undefined) {
589
+ const value = new Uint8Array(9);
590
+ value[0] = RECORD_VERSION;
591
+ new DataView(value.buffer).setBigUint64(1, eventWindow.advance);
592
+ yield* tx.put(WORK_SPACE, eventCursorKey(scope), value);
593
+ }
594
+ return {
595
+ outcomes,
596
+ cursor: newCursor === null ? undefined : Uint8Array.from(newCursor),
597
+ enumeratedCount,
598
+ };
599
+ });
600
+ }
601
+ /** Tasks that are runnable: status `ready` or `inflight` (F3) and every
602
+ * dependency satisfied at operation precision (review finding C), in
603
+ * creation order, at most `limit`. `pending_local` tasks are never
604
+ * returned. */
605
+ async ready(scope, limit) {
606
+ return this.storage.transact(false, (tx) => {
607
+ const self = this;
608
+ return (function* () {
609
+ const out = [];
610
+ for (const dto of yield* scanCandidates(tx, scope, ['ready', 'inflight'])) {
611
+ if (yield* self.depsSatisfiedIn(tx, scope, dto)) {
612
+ out.push(taskInfoFromDto(dto));
613
+ if (out.length >= limit)
614
+ break;
615
+ }
616
+ }
617
+ return out;
618
+ })();
619
+ });
620
+ }
621
+ /** All status `ready` or `inflight` tasks in creation order, WITHOUT the
622
+ * dependency gate (RS2-04): the scheduler's iteration snapshot; `acquire`
623
+ * re-checks the gate per task inside its own transaction (T2). */
624
+ async candidates(scope) {
625
+ return this.storage.transact(false, function* (tx) {
626
+ const dtos = yield* scanCandidates(tx, scope, ['ready', 'inflight']);
627
+ return dtos.map(taskInfoFromDto);
628
+ });
629
+ }
630
+ /** Candidate keyset in (Turn ID, seq) order. Valid parents have smaller
631
+ * IDs, so reverse imports cannot force repeated descendant retries. */
632
+ async candidatesByTurnAfter(scope, after, limit) {
633
+ for (;;) {
634
+ const page = await this.storage.transact(false, function* (tx) {
635
+ if (!(yield* orderedCandidatesReady(tx, scope)))
636
+ return undefined;
637
+ const prefix = orderedCandidatePrefix(scope);
638
+ const start = after === undefined ? prefix : cat(orderedCandidateKey(scope, after), Uint8Array.of(0));
639
+ const out = [];
640
+ for (const [key, value] of yield* tx.scan(WORK_SPACE, start, successor(prefix), limit)) {
641
+ if (key.length !== prefix.length + 20 || value.length !== 0)
642
+ throw corrupt('invalid ordered candidate row');
643
+ const task = refFromIndexRow(key.slice(prefix.length));
644
+ const dto = yield* loadTaskOf(tx, scope, task);
645
+ if (dto === undefined || !isSendCandidate(dto.status))
646
+ throw corrupt('ordered candidate status mismatch');
647
+ out.push(taskInfoFromDto(dto));
648
+ }
649
+ return out;
650
+ });
651
+ if (page !== undefined)
652
+ return page;
653
+ // Legacy upgrade copies compact references, never done bodies.
654
+ // Rows and completion marker are one native IDB transaction.
655
+ await this.storage.transact(true, function* (tx) {
656
+ if (yield* orderedCandidatesReady(tx, scope))
657
+ return;
658
+ if (!(yield* statusIndexReady(tx, scope)))
659
+ yield* buildStatusIndex(tx, scope);
660
+ for (const status of ['ready', 'inflight']) {
661
+ const prefix = statusIndexPrefix(scope, statusTag(status));
662
+ let start = prefix;
663
+ for (;;) {
664
+ const rows = yield* tx.scan(WORK_SPACE, start, successor(prefix), 1000);
665
+ if (!rows.length)
666
+ break;
667
+ for (const [, value] of rows) {
668
+ if (value.length !== 20)
669
+ throw corrupt('invalid status index value');
670
+ yield* tx.put(WORK_SPACE, cat(orderedCandidatePrefix(scope), value), new Uint8Array());
671
+ }
672
+ start = cat(rows[rows.length - 1][0], Uint8Array.of(0));
673
+ }
674
+ }
675
+ yield* tx.put(WORK_SPACE, orderedCandidateMarker(scope), Uint8Array.of(RECORD_VERSION));
676
+ });
677
+ }
678
+ }
679
+ /** Status-`ready`|`inflight` candidates with `taskSeq > after`, in
680
+ * creation order, at most `limit` (RS2-04): the keyset page a scheduler
681
+ * sweeps without materializing the whole backlog. The dependency gate is
682
+ * NOT applied here — `acquire` re-checks it per task (T2). */
683
+ async candidatesAfter(scope, after, limit) {
684
+ return this.storage.transact(false, function* (tx) {
685
+ let refs = [];
686
+ if (yield* statusIndexReady(tx, scope)) {
687
+ for (const status of ['ready', 'inflight']) {
688
+ const tag = statusTag(status);
689
+ const prefix = statusIndexPrefix(scope, tag);
690
+ const start = after === undefined ? prefix : cat(prefix, u64be(after + 1));
691
+ const rows = yield* tx.scan(WORK_SPACE, start, successor(prefix), limit);
692
+ for (const [key, value] of rows)
693
+ refs.push([keyU64(key), refFromIndexRow(value)]);
694
+ }
695
+ refs.sort((a, b) => a[0] - b[0]);
696
+ refs = refs.slice(0, limit);
697
+ }
698
+ else {
699
+ // Pre-index scope: same result from a full scan (slower,
700
+ // identical semantics).
701
+ refs = (yield* scanTasks(tx, scope))
702
+ .filter(dto => (dto.status === 'ready' || dto.status === 'inflight') && (after === undefined || dto.task_seq > after))
703
+ .map(dto => [dto.task_seq, { turn: Uint8Array.from(dto.turn), seq: dto.seq }]);
704
+ refs = refs.slice(0, limit);
705
+ }
706
+ const out = [];
707
+ for (const [taskSeq, task] of refs) {
708
+ const dto = yield* loadTaskOf(tx, scope, task);
709
+ if (dto === undefined)
710
+ throw corrupt('status index row without a task record');
711
+ if (dto.task_seq !== taskSeq)
712
+ throw corrupt('status index row disagrees with its task record');
713
+ out.push(taskInfoFromDto(dto));
714
+ }
715
+ return out;
716
+ });
717
+ }
718
+ /** All tasks of the scope missing their local bytes, in creation order. */
719
+ async pendingLocal(scope) {
720
+ return this.storage.transact(false, function* (tx) {
721
+ const dtos = yield* scanCandidates(tx, scope, ['pending_local']);
722
+ return dtos.map(taskInfoFromDto);
723
+ });
724
+ }
725
+ /** One task's observable state. */
726
+ async task(scope, task) {
727
+ const self = this;
728
+ return this.storage.transact(false, function* (tx) {
729
+ const dto = yield* self.loadTask(tx, scope, task);
730
+ return dto === undefined ? undefined : taskInfoFromDto(dto);
731
+ });
732
+ }
733
+ /** The persisted discovery position of one scope. */
734
+ async discovery(scope) {
735
+ return this.storage.transact(false, function* (tx) {
736
+ const raw = yield* tx.get(WORK_SPACE, cursorKey(scope));
737
+ if (raw === undefined)
738
+ return { cursor: undefined, enumeratedCount: 0 };
739
+ const dto = toCursorDto(checkVersion(raw));
740
+ return {
741
+ cursor: dto.cursor === null ? undefined : Uint8Array.from(dto.cursor),
742
+ enumeratedCount: dto.enumerated_count,
743
+ };
744
+ });
745
+ }
746
+ /** Freeze one task for sending (T2): compare-and-swap `ready|inflight` to
747
+ * `inflight` with the attempt counter incremented, and return the frozen
748
+ * package. A repeated acquire of an `inflight` task starts a new attempt;
749
+ * the previous token becomes stale. The same dependency gate as `ready`
750
+ * runs inside this transaction (review C follow-up): a task whose deps
751
+ * stopped matching is rejected with `unsatisfiedDeps` and nothing is
752
+ * frozen. */
753
+ async acquire(scope, task) {
754
+ const self = this;
755
+ return this.storage.transact(true, function* (tx) {
756
+ const dto = yield* self.loadTask(tx, scope, task);
757
+ if (dto === undefined)
758
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
759
+ if (dto.status !== 'ready' && dto.status !== 'inflight')
760
+ throw new WorkError('invalidTransition', 'status ready or inflight to acquire', { cause: { task, from: dto.status } });
761
+ if (!(yield* self.depsSatisfiedIn(tx, scope, dto)))
762
+ throw new WorkError('unsatisfiedDeps', 'unsatisfied dependencies', { cause: { task } });
763
+ const previous = dto.status;
764
+ dto.attempts += 1;
765
+ dto.status = 'inflight';
766
+ const attempt = dto.attempts;
767
+ const bytes = dto.bytes;
768
+ if (bytes === null)
769
+ throw corrupt('invariant: non-pending tasks carry frozen bytes');
770
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
771
+ yield* statusIndexUpdate(tx, scope, dto.task_seq, task, previous, 'inflight');
772
+ return {
773
+ token: { scope, task: { turn: Uint8Array.from(task.turn), seq: task.seq }, attempt },
774
+ fingerprint: Uint8Array.from(dto.fingerprint),
775
+ deps: dto.deps.map(dep => ({ turn: Uint8Array.from(dep.turn), seq: dep.seq, fingerprint: Uint8Array.from(dep.fp) })),
776
+ bytes: Uint8Array.from(bytes),
777
+ wire: dto.wire === undefined ? undefined : Uint8Array.from(dto.wire),
778
+ };
779
+ });
780
+ }
781
+ /** Record that the target stored the package: compare-and-swap `inflight`
782
+ * to `acked_local`, bound to the token's attempt. A stale callback (older
783
+ * attempt) is rejected with `attemptMismatch`. */
784
+ async ack(token) {
785
+ const task = token.task;
786
+ return this.storage.transact(true, (tx) => {
787
+ const self = this;
788
+ return (function* () {
789
+ const dto = yield* self.loadTask(tx, token.scope, task);
790
+ if (dto === undefined)
791
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
792
+ if (dto.status !== 'inflight')
793
+ throw new WorkError('invalidTransition', 'status inflight to ack', { cause: { task, from: dto.status } });
794
+ if (dto.attempts !== token.attempt)
795
+ throw new WorkError('attemptMismatch', 'attempt mismatch', { cause: { task, expected: dto.attempts, got: token.attempt } });
796
+ dto.status = 'acked_local';
797
+ yield* tx.put(WORK_SPACE, taskKey(token.scope, task), encode(dto));
798
+ yield* statusIndexUpdate(tx, token.scope, dto.task_seq, task, 'inflight', 'acked_local');
799
+ })();
800
+ });
801
+ }
802
+ /** Confirm one acked task on the target (T3): in a single write
803
+ * transaction — compare-and-swap `acked_local` to `done` bound to the
804
+ * token's attempt, mark the exact operation present in the coverage store
805
+ * (running the closed check with the persisted seal/parents data, T5),
806
+ * advance the turn's prefix watermark, remove the task from its deps'
807
+ * wait lists, and return the tasks waiting on this operation as wakeup
808
+ * hints. Both commit or neither does (F2; a re-mark is a byte-idempotent
809
+ * duplicate).
810
+ *
811
+ * With `checkRegistryGeneration` set, the registry's *current* generation
812
+ * is re-read inside this same transaction and compared against the task's
813
+ * scope: a rebind committed before the confirm transaction starts is
814
+ * always observed and rejected as `generationConflict`, with nothing
815
+ * committed (G009). */
816
+ async confirm(token, checkRegistryGeneration) {
817
+ const task = token.task;
818
+ const coverage = this.coverage;
819
+ return this.storage.transact(true, (tx) => {
820
+ const self = this;
821
+ return (function* () {
822
+ if (checkRegistryGeneration) {
823
+ const current = yield* generationIn(tx, token.scope.remote);
824
+ if (current === undefined)
825
+ throw new WorkError('registry', 'registry failure during confirm: remote not found', { cause: { code: 'notFound', remote: token.scope.remote } });
826
+ if (!sameGeneration(current, token.scope.generation))
827
+ throw new WorkError('generationConflict', 'generation changed', { cause: { current, task } });
828
+ }
829
+ const dto = yield* self.loadTask(tx, token.scope, task);
830
+ if (dto === undefined)
831
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
832
+ if (dto.status !== 'acked_local')
833
+ throw new WorkError('invalidTransition', 'status acked_local to confirm', { cause: { task, from: dto.status } });
834
+ if (dto.attempts !== token.attempt)
835
+ throw new WorkError('attemptMismatch', 'attempt mismatch', { cause: { task, expected: dto.attempts, got: token.attempt } });
836
+ // T3: the coverage mark (with its closed check) commits in the
837
+ // same transaction as the task completion and the wait-index
838
+ // maintenance.
839
+ let coverageResult;
840
+ try {
841
+ coverageResult = yield* coverage.markPresentIn(tx, token.scope, task.turn, task.seq, Uint8Array.from(dto.fingerprint), dto.is_seal, dto.parents.map(parent => ({ turn: parent.turn, seal_fp: parent.seal_fp })));
842
+ }
843
+ catch (e) {
844
+ if (e instanceof CoverageError)
845
+ throw new WorkError('coverage', `coverage failure during confirm: ${e.message}`, { cause: { code: e.code, message: e.message } });
846
+ throw e;
847
+ }
848
+ // The confirmed op may extend its turn's satisfied prefix; the
849
+ // watermark walks forward in the same transaction.
850
+ yield* advancePrefixIn(tx, token.scope, coverage, task.turn);
851
+ dto.status = 'done';
852
+ yield* tx.put(WORK_SPACE, taskKey(token.scope, task), encode(dto));
853
+ yield* statusIndexUpdate(tx, token.scope, dto.task_seq, task, 'acked_local', 'done');
854
+ // Same-transaction wait-index maintenance: the confirmed task
855
+ // no longer waits on its deps; the tasks waiting on this
856
+ // operation are wakeup hints for the scheduler.
857
+ for (const dep of dto.deps)
858
+ yield* waitRemove(tx, token.scope, { turn: Uint8Array.from(dep.turn), seq: dep.seq }, task);
859
+ const woke = yield* waiters(tx, token.scope, task);
860
+ return { task, woke, coverage: coverageResult };
861
+ })();
862
+ });
863
+ }
864
+ /** What a scheduler must replay after a restart (F2/F3): tokens for every
865
+ * `acked_local` task and the refs of every `inflight` task.
866
+ *
867
+ * This is also the upgrade path for databases written before the prefix
868
+ * watermark / status index / open-turn set existed: resume first rebuilds
869
+ * the watermarks from the persisted evidence (each step still requires
870
+ * the seq's task record and an exact present mark in coverage), one turn
871
+ * per write transaction, resuming from the persisted watermark, then
872
+ * rebuilds the missing indexes (one transaction each, markers commit with
873
+ * the rows). */
874
+ async resume(scope) {
875
+ const coverage = this.coverage;
876
+ const indexReady = await this.storage.transact(false, function* (tx) {
877
+ return yield* statusIndexReady(tx, scope);
878
+ });
879
+ const turns = await this.storage.transact(false, function* (tx) {
880
+ const candidates = indexReady
881
+ // A complete index covers every turn that can still need a
882
+ // watermark walk: turns whose tasks all completed have their
883
+ // watermarks persisted by confirm/discover already.
884
+ ? yield* scanCandidates(tx, scope, ['pending_local', 'ready', 'inflight', 'acked_local'])
885
+ : yield* scanTasks(tx, scope);
886
+ const byHex = new Map();
887
+ for (const dto of candidates)
888
+ byHex.set(hex(Uint8Array.from(dto.turn)), Uint8Array.from(dto.turn));
889
+ return [...byHex.values()].sort(compareBytes);
890
+ });
891
+ for (const turn of turns) {
892
+ await this.storage.transact(true, function* (tx) {
893
+ yield* advancePrefixIn(tx, scope, coverage, turn);
894
+ });
895
+ }
896
+ if (!indexReady) {
897
+ // Pre-index scope: rebuild the complete status index (one
898
+ // transaction; the marker commits with the rows).
899
+ await this.storage.transact(true, function* (tx) {
900
+ yield* buildStatusIndex(tx, scope);
901
+ });
902
+ }
903
+ const openReady = await this.storage.transact(false, function* (tx) {
904
+ return yield* openIndexReady(tx, scope);
905
+ });
906
+ if (!openReady) {
907
+ // Scope written before open-turn tracking existed (G009): rebuild
908
+ // the set from the persisted task records (one transaction).
909
+ await this.storage.transact(true, function* (tx) {
910
+ yield* buildOpenIndex(tx, scope);
911
+ });
912
+ }
913
+ return this.storage.transact(false, function* (tx) {
914
+ const confirm = [];
915
+ const reacquire = [];
916
+ for (const dto of yield* scanCandidates(tx, scope, ['inflight', 'acked_local'])) {
917
+ const task = { turn: Uint8Array.from(dto.turn), seq: dto.seq };
918
+ if (dto.status === 'acked_local')
919
+ confirm.push({ scope, task, attempt: dto.attempts });
920
+ else if (dto.status === 'inflight')
921
+ reacquire.push(task);
922
+ }
923
+ return { confirm, reacquire };
924
+ });
925
+ }
926
+ /** Supply the local bytes of a `pending_local` task, moving it to
927
+ * `ready`. Oversized packages are rejected and the task stays pending. */
928
+ /** Bind the first ciphertext of an inflight task. Encrypt happens
929
+ * outside this transaction; the write only records the exact bytes that
930
+ * will be appended. A second bind of identical bytes is a no-op. */
931
+ async bindWire(token, wire) {
932
+ if (wire.length > MAX_TASK_BYTES + 64)
933
+ throw invalid('bound ciphertext exceeds the task package ceiling');
934
+ const task = token.task;
935
+ const self = this;
936
+ return this.storage.transact(true, function* (tx) {
937
+ const dto = yield* self.loadTask(tx, token.scope, task);
938
+ if (dto === undefined)
939
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
940
+ if (dto.status !== 'inflight')
941
+ throw new WorkError('invalidTransition', 'status inflight to bind wire', { cause: { task, from: dto.status } });
942
+ if (dto.attempts !== token.attempt)
943
+ throw new WorkError('attemptMismatch', 'attempt mismatch', { cause: { task, expected: dto.attempts, got: token.attempt } });
944
+ if (dto.wire !== undefined) {
945
+ if (!equalBytes(dto.wire, wire))
946
+ throw invalid('task already has a different bound ciphertext');
947
+ return;
948
+ }
949
+ dto.wire = [...wire];
950
+ yield* tx.put(WORK_SPACE, taskKey(token.scope, task), encode(dto));
951
+ });
952
+ }
953
+ async fillBytes(scope, task, bytes) {
954
+ if (bytes.length > MAX_TASK_BYTES)
955
+ throw invalid(`task package exceeds ${MAX_TASK_BYTES} bytes`);
956
+ const self = this;
957
+ return this.storage.transact(true, function* (tx) {
958
+ const dto = yield* self.loadTask(tx, scope, task);
959
+ if (dto === undefined)
960
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
961
+ if (dto.status !== 'pending_local')
962
+ throw new WorkError('invalidTransition', 'status pending_local to fill bytes', { cause: { task, from: dto.status } });
963
+ dto.bytes = [...bytes];
964
+ dto.status = 'ready';
965
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
966
+ yield* statusIndexUpdate(tx, scope, dto.task_seq, task, 'pending_local', 'ready');
967
+ });
968
+ }
969
+ /** The scope's open (still streaming) turns in key order, keyset-paged by
970
+ * `after` (G009): the executor re-reads these turns every discovery cycle
971
+ * and re-offers ops from each recorded `offeredUpto`. A legacy scope
972
+ * without the completeness marker has no rows here; its set is rebuilt by
973
+ * `resume`. */
974
+ async openTurns(scope, after, limit) {
975
+ return this.storage.transact(false, function* (tx) {
976
+ const prefix = openTurnPrefix(scope);
977
+ const start = after === undefined ? prefix : cat(prefix, after);
978
+ const rows = yield* tx.scan(WORK_SPACE, start, successor(prefix), limit + (after === undefined ? 0 : 1));
979
+ const out = [];
980
+ for (const [key, raw] of rows) {
981
+ const turn = key.slice(key.length - 16);
982
+ if (after !== undefined && equalBytes(after, turn))
983
+ continue;
984
+ const dto = toOpenDto(checkVersion(raw));
985
+ out.push({ turn, offeredUpto: dto.offered_upto });
986
+ }
987
+ return out;
988
+ });
989
+ }
990
+ /** Operation-precision dependency gate shared by `ready` and `acquire`,
991
+ * inside the caller's transaction. Same-turn ancestry requires the turn's
992
+ * prefix watermark to cover `seq - 1` and every recorded same-turn dep
993
+ * (the direct predecessor) to be present with its exact fingerprint. A
994
+ * cross-turn dep needs the parent's *complete* op range on the target
995
+ * with a matching seal fingerprint (`closed`, the recursive assertion, or
996
+ * the direct complete-turn evidence a reverse-history window establishes
997
+ * — see N017 P1-C), and every direct parent of the task's turn must
998
+ * satisfy the same check (review C follow-up). */
999
+ *depsSatisfiedIn(tx, scope, dto) {
1000
+ if (dto.seq > 0) {
1001
+ const covered = yield* prefixSatisfiedIn(tx, scope, Uint8Array.from(dto.turn));
1002
+ if (covered === undefined || covered < dto.seq - 1)
1003
+ return false;
1004
+ }
1005
+ for (const dep of dto.deps) {
1006
+ const ok = equalBytes(dep.turn, dto.turn)
1007
+ // Same-turn predecessor: exact presence, not closure.
1008
+ ? yield* this.coverage.presentExactIn(tx, scope, Uint8Array.from(dep.turn), dep.seq, Uint8Array.from(dep.fp))
1009
+ // Cross-turn parent seal: closed or complete on the target.
1010
+ : yield* this.coverage.parentAdmissibleIn(tx, scope, Uint8Array.from(dep.turn), Uint8Array.from(dep.fp));
1011
+ if (!ok)
1012
+ return false;
1013
+ }
1014
+ for (const parent of dto.parents) {
1015
+ if (!(yield* this.coverage.parentAdmissibleIn(tx, scope, Uint8Array.from(parent.turn), Uint8Array.from(parent.seal_fp))))
1016
+ return false;
1017
+ }
1018
+ return true;
1019
+ }
1020
+ }
1021
+ // ---------------------------------------------------------------------------
1022
+ // Transaction-internal helpers (composed by the public methods above).
1023
+ // ---------------------------------------------------------------------------
1024
+ function fp32check(fp) {
1025
+ if (!(fp instanceof Uint8Array) || fp.length !== 32)
1026
+ throw invalid('fingerprint must be a 32-byte Uint8Array');
1027
+ return fp;
1028
+ }
1029
+ function keyU64(key) {
1030
+ if (key.length < 8)
1031
+ throw corrupt('status index key too short');
1032
+ return Number(new DataView(key.buffer, key.byteOffset + key.length - 8, 8).getBigUint64(0));
1033
+ }
1034
+ function refFromIndexRow(value) {
1035
+ if (value.length !== 20)
1036
+ throw corrupt('status index value malformed');
1037
+ return {
1038
+ turn: value.slice(0, 16),
1039
+ seq: new DataView(value.buffer, value.byteOffset + 16, 4).getUint32(0),
1040
+ };
1041
+ }
1042
+ /** A task-record load usable from the free-function helpers. */
1043
+ function* loadTaskOf(tx, scope, task) {
1044
+ const raw = yield* tx.get(WORK_SPACE, taskKey(scope, task));
1045
+ if (raw === undefined)
1046
+ return undefined;
1047
+ const dto = toTaskDto(checkVersion(raw));
1048
+ checkTask(task, dto);
1049
+ return dto;
1050
+ }
1051
+ /** Allocate the next per-scope task sequence inside the current transaction;
1052
+ * a rollback gives the number back, so replays never skip or repeat
1053
+ * sequences (T1). */
1054
+ function* allocTaskSeq(tx, scope) {
1055
+ const key = taskseqKey(scope);
1056
+ const raw = yield* tx.get(WORK_SPACE, key);
1057
+ const next = raw === undefined ? 0 : toTaskSeqDto(checkVersion(raw)).next;
1058
+ yield* tx.put(WORK_SPACE, key, encode({ v: RECORD_VERSION, next: next + 1 }));
1059
+ return next;
1060
+ }
1061
+ /** Append `task` to the wait list of `dep` (sorted, deduped). */
1062
+ function* waitAdd(tx, scope, dep, task) {
1063
+ const key = waitKey(scope, dep);
1064
+ const raw = yield* tx.get(WORK_SPACE, key);
1065
+ const existing = raw === undefined ? [] : toWaitDto(checkVersion(raw)).waiters;
1066
+ if (existing.length >= MAX_WAITERS_PER_DEP)
1067
+ throw invalid(`waiter limit ${MAX_WAITERS_PER_DEP} reached`);
1068
+ const entry = { turn: [...task.turn], seq: task.seq };
1069
+ if (!existing.some(waiter => equalBytes(waiter.turn, entry.turn) && waiter.seq === entry.seq)) {
1070
+ existing.push(entry);
1071
+ existing.sort(compareRefs);
1072
+ yield* tx.put(WORK_SPACE, key, encode({ v: RECORD_VERSION, waiters: existing }));
1073
+ }
1074
+ }
1075
+ /** Remove `task` from the wait list of `dep`; emptied lists are deleted. */
1076
+ function* waitRemove(tx, scope, dep, task) {
1077
+ const key = waitKey(scope, dep);
1078
+ const raw = yield* tx.get(WORK_SPACE, key);
1079
+ if (raw === undefined)
1080
+ return;
1081
+ const existing = toWaitDto(checkVersion(raw)).waiters;
1082
+ const remaining = existing.filter(waiter => !(equalBytes(waiter.turn, task.turn) && waiter.seq === task.seq));
1083
+ if (!remaining.length)
1084
+ yield* tx.delete(WORK_SPACE, key);
1085
+ else if (remaining.length !== existing.length)
1086
+ yield* tx.put(WORK_SPACE, key, encode({ v: RECORD_VERSION, waiters: remaining }));
1087
+ }
1088
+ /** The waiters recorded for one dependency (wakeup hints). */
1089
+ function* waiters(tx, scope, dep) {
1090
+ const raw = yield* tx.get(WORK_SPACE, waitKey(scope, dep));
1091
+ if (raw === undefined)
1092
+ return [];
1093
+ return toWaitDto(checkVersion(raw)).waiters.map(taskRefFromDto);
1094
+ }
1095
+ /** The persisted prefix watermark of one turn inside the caller's
1096
+ * transaction: `upto` means every seq in `0..=upto` is confirmed present with
1097
+ * the exact fingerprint its task record declared. */
1098
+ function* prefixSatisfiedIn(tx, scope, turn) {
1099
+ const raw = yield* tx.get(WORK_SPACE, prefixKey(scope, turn));
1100
+ if (raw === undefined)
1101
+ return undefined;
1102
+ return toPrefixDto(checkVersion(raw)).upto;
1103
+ }
1104
+ /** Advance the prefix watermark of `turn` as far as the target's coverage
1105
+ * allows, inside the caller's write transaction. Each step requires the seq's
1106
+ * own task record (its declared fingerprint is the content binding) and an
1107
+ * exact present mark; the walk stops at the first gap, conflict or
1108
+ * undiscovered op. One op crosses the watermark at most once over the scope's
1109
+ * lifetime, so the walk is amortized O(1) per confirmed op. */
1110
+ function* advancePrefixIn(tx, scope, coverage, turn) {
1111
+ let upto = yield* prefixSatisfiedIn(tx, scope, turn);
1112
+ for (;;) {
1113
+ const next = upto === undefined ? 0 : upto + 1;
1114
+ if (next > 0xFFFFFFFF)
1115
+ break;
1116
+ const task = yield* loadTaskOf(tx, scope, { turn, seq: next });
1117
+ if (task === undefined)
1118
+ break;
1119
+ if (!(yield* coverage.presentExactIn(tx, scope, turn, next, Uint8Array.from(task.fingerprint))))
1120
+ break;
1121
+ upto = next;
1122
+ }
1123
+ if (upto !== undefined) {
1124
+ const key = prefixKey(scope, turn);
1125
+ const value = encode({ v: RECORD_VERSION, upto });
1126
+ const existing = yield* tx.get(WORK_SPACE, key);
1127
+ if (existing === undefined || !equalBytes(existing, value))
1128
+ yield* tx.put(WORK_SPACE, key, value);
1129
+ }
1130
+ }
1131
+ /** Whether the scope's status index is complete (marker present). */
1132
+ function* statusIndexReady(tx, scope) {
1133
+ const raw = yield* tx.get(WORK_SPACE, statusIndexMarkerKey(scope));
1134
+ if (raw === undefined)
1135
+ return false;
1136
+ checkVersion(raw);
1137
+ return true;
1138
+ }
1139
+ /** The index-readiness decision of a discovery transaction: an existing
1140
+ * marker means incremental maintenance; no marker and no task records yet
1141
+ * means a fresh scope, where the marker is created so every later write
1142
+ * maintains the index; no marker with existing tasks means a pre-index
1143
+ * (legacy) scope, which stays on full scans until `resume` rebuilds the
1144
+ * index (correctness never depends on the marker). */
1145
+ function* ensureStatusIndex(tx, scope) {
1146
+ if (yield* statusIndexReady(tx, scope))
1147
+ return true;
1148
+ const prefix = cat(Uint8Array.of(TASK_KEY_TAG), scopeBytes(scope));
1149
+ const any = yield* tx.scan(WORK_SPACE, prefix, successor(prefix), 1);
1150
+ if (any.length)
1151
+ return false;
1152
+ yield* tx.put(WORK_SPACE, statusIndexMarkerKey(scope), encode({ v: RECORD_VERSION }));
1153
+ yield* tx.put(WORK_SPACE, orderedCandidateMarker(scope), Uint8Array.of(RECORD_VERSION));
1154
+ return true;
1155
+ }
1156
+ /** Whether the scope's open-turn set is complete (marker present). */
1157
+ function* openIndexReady(tx, scope) {
1158
+ const raw = yield* tx.get(WORK_SPACE, openIndexMarkerKey(scope));
1159
+ if (raw === undefined)
1160
+ return false;
1161
+ checkVersion(raw);
1162
+ return true;
1163
+ }
1164
+ /** The open-index readiness decision of a discovery transaction, mirroring
1165
+ * `ensureStatusIndex` (G009): a complete set is maintained incrementally; a
1166
+ * fresh scope gets the marker with its first batch; a scope with tasks but no
1167
+ * marker was written before open tracking existed and stays untracked until
1168
+ * `resume` rebuilds the set — its already-scanned streaming turns simply
1169
+ * re-offer nothing until then, exactly the pre-G009 behavior, never a silent
1170
+ * wrong answer. */
1171
+ function* ensureOpenIndex(tx, scope) {
1172
+ if (yield* openIndexReady(tx, scope))
1173
+ return true;
1174
+ const prefix = cat(Uint8Array.of(TASK_KEY_TAG), scopeBytes(scope));
1175
+ const any = yield* tx.scan(WORK_SPACE, prefix, successor(prefix), 1);
1176
+ if (any.length)
1177
+ return false;
1178
+ yield* tx.put(WORK_SPACE, openIndexMarkerKey(scope), encode({ v: RECORD_VERSION }));
1179
+ return true;
1180
+ }
1181
+ /** Insert the task's candidate row, inside the caller's transaction. Only
1182
+ * called when the index is complete for the scope. */
1183
+ function* statusIndexTrack(tx, scope, taskSeq, task, status) {
1184
+ const tag = statusTag(status);
1185
+ if (tag === undefined)
1186
+ return;
1187
+ const key = cat(statusIndexPrefix(scope, tag), u64be(taskSeq));
1188
+ yield* tx.put(WORK_SPACE, key, cat(id16(task.turn, 'turn id').slice(), u32be(task.seq)));
1189
+ }
1190
+ /** Remove the task's candidate row for one status (missing rows are already
1191
+ * gone), inside the caller's transaction. */
1192
+ function* statusIndexUntrack(tx, scope, taskSeq, status) {
1193
+ const tag = statusTag(status);
1194
+ if (tag === undefined)
1195
+ return;
1196
+ yield* tx.delete(WORK_SPACE, cat(statusIndexPrefix(scope, tag), u64be(taskSeq)));
1197
+ }
1198
+ /** A lifecycle transition's index maintenance: one marker read, and when the
1199
+ * index is complete the old row moves to the new status in the same
1200
+ * transaction as the status change itself. Pre-index scopes skip this (their
1201
+ * readers fall back to full scans). */
1202
+ function* statusIndexUpdate(tx, scope, taskSeq, task, from, to) {
1203
+ if (isSendCandidate(from) !== isSendCandidate(to)) {
1204
+ const key = orderedCandidateKey(scope, task);
1205
+ if (isSendCandidate(to))
1206
+ yield* tx.put(WORK_SPACE, key, new Uint8Array());
1207
+ else
1208
+ yield* tx.delete(WORK_SPACE, key);
1209
+ }
1210
+ if (!(yield* statusIndexReady(tx, scope)))
1211
+ return;
1212
+ yield* statusIndexUntrack(tx, scope, taskSeq, from);
1213
+ yield* statusIndexTrack(tx, scope, taskSeq, task, to);
1214
+ }
1215
+ /** All task records of one scope in creation order (task sequences are
1216
+ * allocated monotonically by enumeration, so sorting by `task_seq` is the
1217
+ * discovery order regardless of key order). */
1218
+ function* scanTasks(tx, scope) {
1219
+ const prefix = cat(Uint8Array.of(TASK_KEY_TAG), scopeBytes(scope));
1220
+ const rows = yield* tx.scan(WORK_SPACE, prefix, successor(prefix), ALL);
1221
+ const tasks = [];
1222
+ for (const [, raw] of rows) {
1223
+ const dto = toTaskDto(checkVersion(raw));
1224
+ checkTask({ turn: Uint8Array.from(dto.turn), seq: dto.seq }, dto);
1225
+ tasks.push(dto);
1226
+ }
1227
+ tasks.sort((a, b) => a.task_seq - b.task_seq);
1228
+ return tasks;
1229
+ }
1230
+ /** Candidate tasks of the given statuses in creation order. With a complete
1231
+ * index this reads only the candidate rows and their records; without one it
1232
+ * falls back to a full task scan (identical results). Index rows that
1233
+ * disagree with their task record are corruption. */
1234
+ function* scanCandidates(tx, scope, statuses) {
1235
+ if (!(yield* statusIndexReady(tx, scope))) {
1236
+ const all = yield* scanTasks(tx, scope);
1237
+ return all.filter(dto => statuses.includes(dto.status));
1238
+ }
1239
+ let refs = [];
1240
+ for (const status of statuses) {
1241
+ const tag = statusTag(status);
1242
+ if (tag === undefined)
1243
+ continue;
1244
+ const prefix = statusIndexPrefix(scope, tag);
1245
+ const rows = yield* tx.scan(WORK_SPACE, prefix, successor(prefix), ALL);
1246
+ for (const [key, value] of rows)
1247
+ refs.push([keyU64(key), refFromIndexRow(value)]);
1248
+ }
1249
+ refs.sort((a, b) => a[0] - b[0]);
1250
+ const out = [];
1251
+ for (const [taskSeq, task] of refs) {
1252
+ const dto = yield* loadTaskOf(tx, scope, task);
1253
+ if (dto === undefined)
1254
+ throw corrupt('status index row without a task record');
1255
+ if (dto.task_seq !== taskSeq || !statuses.includes(dto.status))
1256
+ throw corrupt('status index row disagrees with its task record');
1257
+ out.push(dto);
1258
+ }
1259
+ return out;
1260
+ }
1261
+ /** Rebuild the complete status index of a pre-index scope from a full task
1262
+ * scan, in one transaction (a partial index must never become visible; the
1263
+ * marker commits last with the rows). */
1264
+ function* buildStatusIndex(tx, scope) {
1265
+ const tasks = yield* scanTasks(tx, scope);
1266
+ for (const dto of tasks) {
1267
+ const task = { turn: Uint8Array.from(dto.turn), seq: dto.seq };
1268
+ yield* statusIndexTrack(tx, scope, dto.task_seq, task, dto.status);
1269
+ if (isSendCandidate(dto.status))
1270
+ yield* tx.put(WORK_SPACE, orderedCandidateKey(scope, task), new Uint8Array());
1271
+ }
1272
+ yield* tx.put(WORK_SPACE, statusIndexMarkerKey(scope), encode({ v: RECORD_VERSION }));
1273
+ yield* tx.put(WORK_SPACE, orderedCandidateMarker(scope), Uint8Array.of(RECORD_VERSION));
1274
+ }
1275
+ /** Rebuild the complete open-turn set of a scope written before open
1276
+ * tracking existed (G009), from a full task scan, in one transaction. The
1277
+ * persisted tasks are the evidence: a turn with no seal task may still grow,
1278
+ * so it re-enters the set with `offered_upto` just past its highest
1279
+ * discovered seq; a turn whose seal task exists can never grow again (sealed
1280
+ * turns are immutable) and stays out. */
1281
+ function* buildOpenIndex(tx, scope) {
1282
+ const tasks = yield* scanTasks(tx, scope);
1283
+ const byTurn = new Map();
1284
+ for (const dto of tasks) {
1285
+ const key = hex(Uint8Array.from(dto.turn));
1286
+ const entry = byTurn.get(key) ?? { turn: Uint8Array.from(dto.turn), upto: 0, hasSeal: false };
1287
+ entry.upto = Math.max(entry.upto, dto.seq + 1);
1288
+ entry.hasSeal ||= dto.is_seal;
1289
+ byTurn.set(key, entry);
1290
+ }
1291
+ for (const entry of [...byTurn.values()].sort((a, b) => compareBytes(a.turn, b.turn))) {
1292
+ if (entry.hasSeal)
1293
+ continue;
1294
+ yield* tx.put(WORK_SPACE, openTurnKey(scope, entry.turn), encode({ v: RECORD_VERSION, offered_upto: entry.upto }));
1295
+ }
1296
+ yield* tx.put(WORK_SPACE, openIndexMarkerKey(scope), encode({ v: RECORD_VERSION }));
1297
+ }
1298
+ function toCursorDto(raw) {
1299
+ if (!Number.isInteger(raw.v) || !(raw.cursor === null || Array.isArray(raw.cursor)) || !Number.isSafeInteger(raw.enumerated_count))
1300
+ throw corrupt('cursor fields');
1301
+ checkInnerV(raw.v);
1302
+ const cursor = raw.cursor === null ? null : byteArray(raw.cursor, 'cursor');
1303
+ if (cursor !== null && cursor.length !== 16)
1304
+ throw corrupt('record JSON: cursor must be 16 bytes');
1305
+ return { v: raw.v, cursor, enumerated_count: raw.enumerated_count };
1306
+ }
1307
+ function toTaskSeqDto(raw) {
1308
+ if (!Number.isInteger(raw.v) || !Number.isSafeInteger(raw.next))
1309
+ throw corrupt('taskseq fields');
1310
+ checkInnerV(raw.v);
1311
+ return { v: raw.v, next: raw.next };
1312
+ }
1313
+ function toWaitDto(raw) {
1314
+ if (!Number.isInteger(raw.v) || !Array.isArray(raw.waiters))
1315
+ throw corrupt('wait index fields');
1316
+ checkInnerV(raw.v);
1317
+ const waiters = raw.waiters.map((waiter, i) => {
1318
+ if (typeof waiter !== 'object' || waiter === null || Array.isArray(waiter))
1319
+ throw corrupt('waiter must be an object');
1320
+ const o = waiter;
1321
+ if (!Number.isInteger(o.seq))
1322
+ throw corrupt('waiter seq');
1323
+ return { turn: byteArray(o.turn, `waiters[${i}].turn`), seq: o.seq };
1324
+ });
1325
+ for (const waiter of waiters)
1326
+ if (waiter.turn.length !== 16)
1327
+ throw corrupt('record JSON: waiter turn must be 16 bytes');
1328
+ for (let i = 1; i < waiters.length; i++)
1329
+ if (compareRefs(waiters[i - 1], waiters[i]) >= 0)
1330
+ throw corrupt('waiters not sorted or deduped');
1331
+ return { v: raw.v, waiters };
1332
+ }
1333
+ function toPrefixDto(raw) {
1334
+ if (!Number.isInteger(raw.v) || !Number.isInteger(raw.upto))
1335
+ throw corrupt('prefix watermark fields');
1336
+ checkInnerV(raw.v);
1337
+ return { v: raw.v, upto: raw.upto };
1338
+ }
1339
+ function toOpenDto(raw) {
1340
+ if (!Number.isInteger(raw.v) || !Number.isInteger(raw.offered_upto))
1341
+ throw corrupt('open-turn fields');
1342
+ checkInnerV(raw.v);
1343
+ return { v: raw.v, offered_upto: raw.offered_upto };
1344
+ }