pi-better-background-tasks 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -4
- package/package.json +3 -1
- package/src/adapter-contract.ts +16 -2
- package/src/batch.ts +108 -0
- package/src/delivery-observer.ts +42 -0
- package/src/goal-provider.ts +72 -5
- package/src/index.ts +39 -0
- package/src/navigator-provider.ts +175 -6
- package/src/observed-waits.ts +3677 -0
- package/src/output.ts +22 -2
- package/src/process.ts +100 -1
- package/src/runtime.ts +189 -10
- package/src/sandbox.ts +276 -2
- package/src/shared-callback-batcher.ts +18 -1
- package/src/shared-execution-policy.ts +2 -0
- package/src/shared-failure-observations.ts +78 -24
- package/src/shared-log-utils.ts +277 -31
- package/src/shared-operation-coordinator/index.ts +113 -0
- package/src/shared-operation-coordinator/src/errors.ts +75 -0
- package/src/shared-operation-coordinator/src/operations.ts +376 -0
- package/src/shared-operation-coordinator/src/outbox.ts +431 -0
- package/src/shared-operation-coordinator/src/rows.ts +439 -0
- package/src/shared-operation-coordinator/src/schema.ts +244 -0
- package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/src/shared-operation-coordinator/src/store.ts +397 -0
- package/src/shared-operation-coordinator/src/types.ts +648 -0
- package/src/shared-operation-coordinator/src/validate.ts +239 -0
- package/src/shared-operation-coordinator/src/waits.ts +1378 -0
- package/src/stall.ts +4 -1
- package/src/supervisor/README.md +111 -0
- package/src/supervisor/emit-runner.mjs +101 -0
- package/src/supervisor/generated/conditions.mjs +96 -0
- package/src/supervisor/generated/identity.mjs +95 -0
- package/src/supervisor/generated/process-identity.mjs +43 -0
- package/src/supervisor/generated/process.mjs +514 -0
- package/src/supervisor/generated/runner.mjs +872 -0
- package/src/supervisor/generated/store.mjs +605 -0
- package/src/supervisor/generated/types.mjs +50 -0
- package/src/supervisor/identity.ts +99 -0
- package/src/supervisor/index.ts +37 -0
- package/src/supervisor/invocation.ts +44 -0
- package/src/supervisor/runner.ts +982 -0
- package/src/supervisor/store.ts +649 -0
- package/src/supervisor/supervisor.ts +730 -0
- package/src/supervisor/types.ts +384 -0
- package/src/tools.ts +410 -12
- package/src/types.ts +41 -1
package/src/shared-log-utils.ts
CHANGED
|
@@ -135,7 +135,14 @@ export const OUTPUT_PAGE_DEFAULTS = {
|
|
|
135
135
|
|
|
136
136
|
export type OutputBudgetSurface = keyof typeof OUTPUT_BUDGET_BYTES;
|
|
137
137
|
|
|
138
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Why a supplied cursor was not followed. `cursor-corrupt` means the payload
|
|
140
|
+
* itself failed its integrity check — a hand-copied character, not evidence
|
|
141
|
+
* that the source changed or that the cursor belongs to another scope (#617).
|
|
142
|
+
* A corrupt cursor only resumes from an offset a witness recomputed from the
|
|
143
|
+
* current source proves; otherwise the page restarts at byte 0.
|
|
144
|
+
*/
|
|
145
|
+
export type PageReset = "stale-cursor" | "source-replaced" | "compacted" | "cursor-corrupt";
|
|
139
146
|
export type EvidenceGapKind = "capture" | "retention" | "read";
|
|
140
147
|
export type StatusChange = "none" | "failure" | "content" | "reset";
|
|
141
148
|
export type EnvelopeSectionName =
|
|
@@ -191,6 +198,12 @@ export interface PageResult {
|
|
|
191
198
|
appendReady?: boolean;
|
|
192
199
|
/** Bytes of a trailing, still-incomplete UTF-8 sequence withheld until the writer completes it. */
|
|
193
200
|
pendingBytes?: number;
|
|
201
|
+
/**
|
|
202
|
+
* `backward` marks an end-anchored page: the text ends at the cursor's upper
|
|
203
|
+
* bound, `omittedBytes` counts earlier bytes not shown, and `nextCursor`
|
|
204
|
+
* continues toward the start of the file.
|
|
205
|
+
*/
|
|
206
|
+
direction?: "backward";
|
|
194
207
|
}
|
|
195
208
|
|
|
196
209
|
export interface FilePageRequest extends PageRequest {
|
|
@@ -205,6 +218,14 @@ export interface FilePageRequest extends PageRequest {
|
|
|
205
218
|
captureGaps?: Array<{ bytes: number; detail?: string }>;
|
|
206
219
|
/** Pin pagination to this many leading bytes; defaults to the size at first read. */
|
|
207
220
|
snapshotBytes?: number;
|
|
221
|
+
/**
|
|
222
|
+
* Start an uncursored read from the newest retained byte instead of byte 0
|
|
223
|
+
* (issue #618). The first page is end-anchored and `nextCursor` then pages
|
|
224
|
+
* toward the oldest byte; reaching the start hands back an append-ready
|
|
225
|
+
* cursor. A backward cursor keeps this direction on its own, so the request
|
|
226
|
+
* flag is only needed to start such a pager.
|
|
227
|
+
*/
|
|
228
|
+
direction?: "backward";
|
|
208
229
|
}
|
|
209
230
|
|
|
210
231
|
export interface VerbatimPage {
|
|
@@ -224,6 +245,8 @@ export interface VerbatimPage {
|
|
|
224
245
|
endByte?: number;
|
|
225
246
|
appendReady?: boolean;
|
|
226
247
|
pendingBytes?: number;
|
|
248
|
+
/** `backward` marks an end-anchored page whose `nextCursor` reads earlier bytes. */
|
|
249
|
+
direction?: "backward";
|
|
227
250
|
/** Where `nextCursor` is accepted when that is not the tool that returned it. */
|
|
228
251
|
via?: string;
|
|
229
252
|
}
|
|
@@ -286,10 +309,15 @@ interface CursorPayload {
|
|
|
286
309
|
i?: string;
|
|
287
310
|
h?: string;
|
|
288
311
|
hl?: number;
|
|
312
|
+
/** Position witness: the byte window before the offset (`k: "f"`), or the source snapshot (`k: "t"`). */
|
|
289
313
|
w?: string;
|
|
290
314
|
c?: string;
|
|
291
315
|
f?: string;
|
|
292
316
|
a?: 1;
|
|
317
|
+
/** End-anchored page: `o` is the page's upper bound and `nextCursor` reads earlier bytes. */
|
|
318
|
+
b?: 1;
|
|
319
|
+
/** Integrity tag over every other field; see `cursorIntegrityTag`. */
|
|
320
|
+
x?: string;
|
|
293
321
|
}
|
|
294
322
|
|
|
295
323
|
function positiveInt(value: unknown): number | undefined {
|
|
@@ -438,10 +466,44 @@ function resourceTag(resource: string): string {
|
|
|
438
466
|
return hashBytes(encoder.encode(resource)).slice(0, 16);
|
|
439
467
|
}
|
|
440
468
|
|
|
469
|
+
/**
|
|
470
|
+
* Cursors that carry an offset are tagged, so a hand-copied cursor can be
|
|
471
|
+
* recognised as damaged. Status cursors are not: they hold no offset, a
|
|
472
|
+
* damaged one already falls back to the current facts, and their payload sits
|
|
473
|
+
* in 1 KiB status responses where every cursor byte competes with decision
|
|
474
|
+
* facts (`remote setup: …` was clipped once the cursor grew).
|
|
475
|
+
*/
|
|
476
|
+
function isTaggedCursorKind(kind: CursorPayload["k"]): boolean {
|
|
477
|
+
return kind !== "s";
|
|
478
|
+
}
|
|
479
|
+
|
|
441
480
|
function encodeCursor(payload: CursorPayload): string {
|
|
442
|
-
|
|
481
|
+
const tagged = isTaggedCursorKind(payload.k) ? { ...payload, x: cursorIntegrityTag(payload) } : payload;
|
|
482
|
+
return CURSOR_PREFIX + Buffer.from(JSON.stringify(tagged), "utf8").toString("base64url");
|
|
443
483
|
}
|
|
444
484
|
|
|
485
|
+
/**
|
|
486
|
+
* Integrity tag over every payload field except the tag itself.
|
|
487
|
+
*
|
|
488
|
+
* Cursors are re-typed by the model. One mistyped base64url character used to
|
|
489
|
+
* decode into a payload that still parsed: when the changed field was the
|
|
490
|
+
* source digest the pager reported `source-replaced`, restarted at byte 0 and
|
|
491
|
+
* minted the same cursor again — the caller could never reach the rest of the
|
|
492
|
+
* text (#617). The tag makes a near-miss detectable as corruption instead of
|
|
493
|
+
* being read as a different source.
|
|
494
|
+
*/
|
|
495
|
+
function cursorIntegrityTag(payload: CursorPayload): string {
|
|
496
|
+
const { x: _ignored, ...rest } = payload;
|
|
497
|
+
// 36 bits: enough to catch an accidental edit, and short enough that the
|
|
498
|
+
// cursor stays a small thing to copy.
|
|
499
|
+
return shortHash(encoder.encode(JSON.stringify(rest))).slice(0, 6);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Structural decode only: a corrupted payload still reports its kind and
|
|
504
|
+
* resource so it can be classified and, where the offset is still meaningful,
|
|
505
|
+
* resumed. `cursorIntegrityOk` is the separate integrity verdict.
|
|
506
|
+
*/
|
|
445
507
|
function decodeCursor(cursor: string | undefined): CursorPayload | undefined {
|
|
446
508
|
if (!cursor || !cursor.startsWith(CURSOR_PREFIX)) return undefined;
|
|
447
509
|
try {
|
|
@@ -453,6 +515,39 @@ function decodeCursor(cursor: string | undefined): CursorPayload | undefined {
|
|
|
453
515
|
return undefined;
|
|
454
516
|
}
|
|
455
517
|
|
|
518
|
+
/** False when any payload field was altered after the cursor was minted. */
|
|
519
|
+
function cursorIntegrityOk(parsed: CursorPayload): boolean {
|
|
520
|
+
if (!isTaggedCursorKind(parsed.k)) return true;
|
|
521
|
+
return typeof parsed.x === "string" && parsed.x === cursorIntegrityTag(parsed);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Digest of one source snapshot at one offset. A text cursor carries it in `v`
|
|
526
|
+
* and, recomputed against the current text, it answers both questions a
|
|
527
|
+
* continuation needs: is this still the same source, and is this still its
|
|
528
|
+
* offset? A changed source or a shifted offset changes it (#617).
|
|
529
|
+
*/
|
|
530
|
+
function textSnapshotDigest(revision: string, offset: number): string {
|
|
531
|
+
return shortHash(encoder.encode(`t\0${revision}\0${offset}`));
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Second, independent witness of the same fact, stored in `w`: the snapshot,
|
|
536
|
+
* its length, and the offset. Both witnesses are recomputed from the current
|
|
537
|
+
* text, so damage to either one alone still leaves a usable cursor — the
|
|
538
|
+
* reported one-character miscopy keeps the page advancing instead of replaying
|
|
539
|
+
* page 1 forever, while a genuinely replaced or shifted source fails both.
|
|
540
|
+
*/
|
|
541
|
+
function textOffsetWitness(revision: string, offset: number, length: number): string {
|
|
542
|
+
return shortHash(encoder.encode(`t\0${revision}\0${length}\0${offset}`)).slice(0, 6);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Decoded page offset, or NaN when the field did not survive decoding. */
|
|
546
|
+
function cursorOffset(parsed: CursorPayload): number {
|
|
547
|
+
const o = parsed.o;
|
|
548
|
+
return typeof o === "number" && Number.isFinite(o) ? Math.floor(o) : Number.NaN;
|
|
549
|
+
}
|
|
550
|
+
|
|
456
551
|
export function cursorKind(cursor: string | undefined): "t" | "f" | "s" | "l" | undefined {
|
|
457
552
|
if (cursor?.startsWith(ROW_CURSOR_PREFIX)) return decodeRowCursor(cursor) ? "l" : undefined;
|
|
458
553
|
return decodeCursor(cursor)?.k;
|
|
@@ -491,6 +586,14 @@ function emptyPage(overrides: Partial<PageResult> & Pick<PageResult, "revision"
|
|
|
491
586
|
* Page exact UTF-8 text. Consecutive pages concatenate to the original string.
|
|
492
587
|
* Cursors are caller-owned: the same cursor plus maxBytes always yields the
|
|
493
588
|
* same page, and two callers do not share consumption.
|
|
589
|
+
*
|
|
590
|
+
* A cursor that fails its integrity check is reported as `cursor-corrupt`,
|
|
591
|
+
* never as a replaced source, and never replays page 1 blindly: it resumes at
|
|
592
|
+
* its decoded offset only when a witness recomputed from the current text
|
|
593
|
+
* proves that offset still belongs to the same snapshot. Otherwise — a
|
|
594
|
+
* replaced, grown, or shifted source, a damaged offset, or a cursor from
|
|
595
|
+
* before the witnesses existed — the page restarts at byte 0, so no unread
|
|
596
|
+
* text is skipped (#617).
|
|
494
597
|
*/
|
|
495
598
|
export function pageVerbatimText(text: string, request: PageRequest = {}): PageResult {
|
|
496
599
|
const maxBytes = pagerBudget(request.maxBytes, OUTPUT_BUDGET_BYTES.answer);
|
|
@@ -501,20 +604,43 @@ export function pageVerbatimText(text: string, request: PageRequest = {}): PageR
|
|
|
501
604
|
let reset: PageReset | undefined;
|
|
502
605
|
const parsed = decodeCursor(request.cursor);
|
|
503
606
|
if (request.cursor) {
|
|
504
|
-
if (!parsed || parsed.k !== "t"
|
|
607
|
+
if (!parsed || parsed.k !== "t") {
|
|
608
|
+
reset = "stale-cursor";
|
|
609
|
+
} else if (!cursorIntegrityOk(parsed) || parsed.w === undefined) {
|
|
610
|
+
// A payload without its position witness (a cursor minted before this
|
|
611
|
+
// format) is treated the same as a damaged one: its offset is unproven.
|
|
612
|
+
reset = "cursor-corrupt";
|
|
613
|
+
if ((parsed.r ?? undefined) === resource) {
|
|
614
|
+
const decoded = cursorOffset(parsed);
|
|
615
|
+
const inside = Number.isFinite(decoded) && decoded >= 0 && decoded <= encoded.length;
|
|
616
|
+
// Two independent witnesses of "this snapshot at this offset": either
|
|
617
|
+
// one surviving a single damaged field keeps a static-source cursor
|
|
618
|
+
// moving instead of looping on page 1.
|
|
619
|
+
const witnessed = inside && (
|
|
620
|
+
parsed.v === textSnapshotDigest(revision, decoded)
|
|
621
|
+
|| (parsed.w !== undefined && parsed.w === textOffsetWitness(revision, decoded, encoded.length))
|
|
622
|
+
);
|
|
623
|
+
if (witnessed) offset = decoded;
|
|
624
|
+
}
|
|
625
|
+
} else if ((parsed.r ?? undefined) !== resource) {
|
|
505
626
|
reset = "stale-cursor";
|
|
506
|
-
} else if (parsed.v !== revision) {
|
|
507
|
-
reset = "source-replaced";
|
|
508
627
|
} else {
|
|
509
628
|
offset = Math.min(encoded.length, Math.max(0, Math.floor(parsed.o ?? 0)));
|
|
629
|
+
if (parsed.v !== textSnapshotDigest(revision, offset)) {
|
|
630
|
+
// Same cursor, different text: restart at byte 0 rather than serving
|
|
631
|
+
// bytes from a position that no longer means what it did.
|
|
632
|
+
reset = "source-replaced";
|
|
633
|
+
offset = 0;
|
|
634
|
+
}
|
|
510
635
|
}
|
|
511
636
|
}
|
|
512
637
|
const mint = (o: number): string => encodeCursor({
|
|
513
638
|
k: "t",
|
|
514
639
|
...(resource !== undefined ? { r: resource } : {}),
|
|
515
|
-
v: revision,
|
|
640
|
+
v: textSnapshotDigest(revision, o),
|
|
516
641
|
o,
|
|
517
642
|
n: encoded.length,
|
|
643
|
+
w: textOffsetWitness(revision, o, encoded.length),
|
|
518
644
|
});
|
|
519
645
|
const make = (start: number, end: number): PageResult => ({
|
|
520
646
|
text: decoder.decode(encoded.subarray(start, end)),
|
|
@@ -598,6 +724,35 @@ function fileReadError(
|
|
|
598
724
|
});
|
|
599
725
|
}
|
|
600
726
|
|
|
727
|
+
/**
|
|
728
|
+
* Start byte of an end-anchored page inside `window` (the bytes immediately
|
|
729
|
+
* before its upper bound). A backward page starts just after the first newline
|
|
730
|
+
* that keeps at least half the window, so consecutive pages concatenate; when
|
|
731
|
+
* no such newline exists (one oversized line) it starts on the next whole code
|
|
732
|
+
* point and the page begins mid-line rather than stalling.
|
|
733
|
+
*/
|
|
734
|
+
function backwardPageStart(window: Buffer): number {
|
|
735
|
+
let start = 0;
|
|
736
|
+
while (start < window.length && isContinuation(window[start]!)) start += 1;
|
|
737
|
+
const floor = Math.ceil(window.length / 2);
|
|
738
|
+
for (let i = start; i < floor; i += 1) {
|
|
739
|
+
if (window[i] === NEWLINE) return i + 1;
|
|
740
|
+
}
|
|
741
|
+
return start;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Largest boundary <= `end` that does not split a UTF-8 sequence, looking only
|
|
746
|
+
* at the bytes retained up to `end`. Used for the newest retained byte, which
|
|
747
|
+
* a writer can leave inside a code point it has not finished emitting.
|
|
748
|
+
*/
|
|
749
|
+
function completeCodePointEnd(fd: number, end: number): number {
|
|
750
|
+
if (end <= 0) return 0;
|
|
751
|
+
const from = Math.max(0, end - 4);
|
|
752
|
+
const tail = readAt(fd, from, end - from);
|
|
753
|
+
return from + utf8SafeEnd(tail, 0, tail.length);
|
|
754
|
+
}
|
|
755
|
+
|
|
601
756
|
/**
|
|
602
757
|
* Page retained file bytes without skipping unread ranges. Snapshot high-water
|
|
603
758
|
* marks keep a page stable while the file appends. Cursors bind the resource
|
|
@@ -640,32 +795,46 @@ export function pageRetainedFile(path: string, request: FilePageRequest = {}): P
|
|
|
640
795
|
let appendReady = false;
|
|
641
796
|
|
|
642
797
|
if (request.cursor) {
|
|
643
|
-
if (!parsed || parsed.k !== "f"
|
|
798
|
+
if (!parsed || parsed.k !== "f") {
|
|
644
799
|
reset = "stale-cursor";
|
|
645
|
-
} else if (parsed.i !== identity) {
|
|
646
|
-
reset = "source-replaced";
|
|
647
800
|
} else {
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
reset = "
|
|
660
|
-
} else if (
|
|
661
|
-
|
|
662
|
-
// cursor changed without a declared compaction: rewritten in place,
|
|
663
|
-
// or deleted and recreated on a reused inode with coarse timestamps.
|
|
664
|
-
reset = "source-replaced";
|
|
801
|
+
// A hand-copied cursor is never reported as a replaced source: that was
|
|
802
|
+
// a false claim, and the restart replayed page 1 forever (#617). A
|
|
803
|
+
// damaged payload is also never resumed: its offset *and* its direction
|
|
804
|
+
// come from a payload that failed its integrity check, so the pass
|
|
805
|
+
// restarts at its own anchor (byte 0 forward, the newest byte backward)
|
|
806
|
+
// instead of continuing somewhere the caller never reached (#617 R1).
|
|
807
|
+
const corrupt = !cursorIntegrityOk(parsed);
|
|
808
|
+
const reason = (clean: PageReset): PageReset => (corrupt ? "cursor-corrupt" : clean);
|
|
809
|
+
if (parsed.r !== resource) {
|
|
810
|
+
reset = reason("stale-cursor");
|
|
811
|
+
} else if (parsed.i !== identity) {
|
|
812
|
+
reset = reason("source-replaced");
|
|
813
|
+
} else if (corrupt) {
|
|
814
|
+
reset = "cursor-corrupt";
|
|
665
815
|
} else {
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
816
|
+
const o = Math.max(0, Math.floor(parsed.o ?? 0));
|
|
817
|
+
const n = Math.max(0, Math.floor(parsed.n ?? 0));
|
|
818
|
+
const headLength = Math.max(0, Math.floor(parsed.hl ?? 0));
|
|
819
|
+
const generationChanged = generation !== undefined && parsed.g !== generation;
|
|
820
|
+
const bytesIntact = o <= n
|
|
821
|
+
&& n <= size
|
|
822
|
+
&& headLength <= size
|
|
823
|
+
&& (!parsed.h || shortHash(head.subarray(0, headLength)) === parsed.h)
|
|
824
|
+
&& (o === 0 || windowHash(o) === parsed.w);
|
|
825
|
+
if (generationChanged) {
|
|
826
|
+
// The consumer declared a compaction/replacement of this file.
|
|
827
|
+
reset = "compacted";
|
|
828
|
+
} else if (!bytesIntact) {
|
|
829
|
+
// Same file object as far as stat can tell, but the bytes behind the
|
|
830
|
+
// cursor changed without a declared compaction: rewritten in place,
|
|
831
|
+
// or deleted and recreated on a reused inode with coarse timestamps.
|
|
832
|
+
reset = "source-replaced";
|
|
833
|
+
} else {
|
|
834
|
+
offset = o;
|
|
835
|
+
snapshot = n;
|
|
836
|
+
appendReady = parsed.a === 1;
|
|
837
|
+
}
|
|
669
838
|
}
|
|
670
839
|
}
|
|
671
840
|
}
|
|
@@ -674,7 +843,7 @@ export function pageRetainedFile(path: string, request: FilePageRequest = {}): P
|
|
|
674
843
|
snapshot = Math.max(snapshot, initialSnapshot());
|
|
675
844
|
}
|
|
676
845
|
|
|
677
|
-
const mint = (o: number, n: number, append: boolean): string => {
|
|
846
|
+
const mint = (o: number, n: number, append: boolean, back = false): string => {
|
|
678
847
|
const window = windowHash(o);
|
|
679
848
|
return encodeCursor({
|
|
680
849
|
k: "f",
|
|
@@ -687,6 +856,7 @@ export function pageRetainedFile(path: string, request: FilePageRequest = {}): P
|
|
|
687
856
|
hl: head.length,
|
|
688
857
|
...(window ? { w: window } : {}),
|
|
689
858
|
...(append ? { a: 1 } : {}),
|
|
859
|
+
...(back ? { b: 1 as const } : {}),
|
|
690
860
|
});
|
|
691
861
|
};
|
|
692
862
|
const base = {
|
|
@@ -694,6 +864,80 @@ export function pageRetainedFile(path: string, request: FilePageRequest = {}): P
|
|
|
694
864
|
...(reset ? { reset } : {}),
|
|
695
865
|
};
|
|
696
866
|
|
|
867
|
+
// A backward cursor keeps its own direction (even after a reset, which
|
|
868
|
+
// restarts at the newest bytes); the request flag starts one.
|
|
869
|
+
const backward = parsed?.k === "f" ? parsed.b === 1 : request.direction === "backward";
|
|
870
|
+
if (backward) {
|
|
871
|
+
if (!request.cursor || reset) offset = snapshot;
|
|
872
|
+
if (offset > snapshot) offset = snapshot;
|
|
873
|
+
const mintBackward = (o: number): string => mint(o, snapshot, false, true);
|
|
874
|
+
const revision = fileRevision(generation, identity, snapshot);
|
|
875
|
+
// The newest retained byte can stop inside a code point the writer has not
|
|
876
|
+
// finished. Withhold that suffix like the forward pager does, and anchor
|
|
877
|
+
// the append cursor at its first byte, so the whole character arrives once
|
|
878
|
+
// the writer completes it. Every other page starts where a previous page
|
|
879
|
+
// already aligned.
|
|
880
|
+
const snapshotEnd = completeCodePointEnd(opened, snapshot);
|
|
881
|
+
if (offset <= 0) {
|
|
882
|
+
// Nothing earlier is retained: hand back the forward append-ready cursor.
|
|
883
|
+
return emptyPage({
|
|
884
|
+
revision,
|
|
885
|
+
cursor: mintBackward(0),
|
|
886
|
+
nextCursor: mint(snapshotEnd, snapshotEnd, true),
|
|
887
|
+
totalBytes: snapshot,
|
|
888
|
+
startByte: 0,
|
|
889
|
+
endByte: 0,
|
|
890
|
+
appendReady: true,
|
|
891
|
+
direction: "backward",
|
|
892
|
+
...(snapshotEnd < snapshot ? { pendingBytes: snapshot - snapshotEnd } : {}),
|
|
893
|
+
...base,
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
const from = Math.max(0, offset - maxBytes);
|
|
897
|
+
const window = readAt(opened, from, offset - from);
|
|
898
|
+
const withheldFrom = offset === snapshot ? snapshotEnd : offset;
|
|
899
|
+
const pendingBytes = offset - withheldFrom;
|
|
900
|
+
// Byte 0 is always a valid page start; otherwise start at the first line
|
|
901
|
+
// boundary that keeps as much of the window as possible.
|
|
902
|
+
const reachedStart = from === 0;
|
|
903
|
+
const start = reachedStart ? 0 : from + backwardPageStart(window.subarray(0, withheldFrom - from));
|
|
904
|
+
if (!reachedStart && start >= withheldFrom) {
|
|
905
|
+
// Budget is smaller than the next code point behind the cursor: stay put.
|
|
906
|
+
const here = mintBackward(offset);
|
|
907
|
+
return emptyPage({
|
|
908
|
+
revision,
|
|
909
|
+
cursor: here,
|
|
910
|
+
nextCursor: here,
|
|
911
|
+
hasMore: true,
|
|
912
|
+
omittedBytes: offset,
|
|
913
|
+
totalBytes: snapshot,
|
|
914
|
+
startByte: offset,
|
|
915
|
+
endByte: offset,
|
|
916
|
+
direction: "backward",
|
|
917
|
+
...(pendingBytes > 0 ? { pendingBytes } : {}),
|
|
918
|
+
...base,
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
return {
|
|
922
|
+
text: decoder.decode(window.subarray(start - from, withheldFrom - from)),
|
|
923
|
+
revision,
|
|
924
|
+
cursor: mintBackward(offset),
|
|
925
|
+
// Reaching the oldest byte hands the whole pass back to forward polling:
|
|
926
|
+
// the append cursor sits on the newest complete code point, so a withheld
|
|
927
|
+
// character is returned whole rather than skipped.
|
|
928
|
+
nextCursor: reachedStart ? mint(snapshotEnd, snapshotEnd, true) : mintBackward(start),
|
|
929
|
+
hasMore: !reachedStart,
|
|
930
|
+
omittedBytes: start,
|
|
931
|
+
totalBytes: snapshot,
|
|
932
|
+
startByte: start,
|
|
933
|
+
endByte: withheldFrom,
|
|
934
|
+
...(reachedStart ? { appendReady: true } : {}),
|
|
935
|
+
...(pendingBytes > 0 ? { pendingBytes } : {}),
|
|
936
|
+
direction: "backward",
|
|
937
|
+
...base,
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
697
941
|
if (offset > snapshot) offset = snapshot;
|
|
698
942
|
if (offset >= snapshot) {
|
|
699
943
|
return emptyPage({
|
|
@@ -1088,7 +1332,9 @@ function formatContinuation(info: {
|
|
|
1088
1332
|
? `omittedRows=${page.omittedRows}`
|
|
1089
1333
|
: `omittedBytes=${page.omittedBytes}`;
|
|
1090
1334
|
const cursor = page.nextCursor ? ` nextCursor=${page.nextCursor}${page.via ? ` (${page.via})` : ""}` : "";
|
|
1091
|
-
|
|
1335
|
+
// End-anchored pages count earlier bytes and continue toward the start.
|
|
1336
|
+
const direction = page.direction === "backward" ? " (newest-first page; nextCursor reads earlier bytes)" : "";
|
|
1337
|
+
lines.push(`hasMore=${page.hasMore} ${amount}${cursor}${direction}`);
|
|
1092
1338
|
} else if (page?.appendReady && page.nextCursor) {
|
|
1093
1339
|
lines.push(`end nextCursor=${page.nextCursor} (reuse to read only bytes appended later)`);
|
|
1094
1340
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/index.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Durable operation coordinator.
|
|
4
|
+
*
|
|
5
|
+
* A small, reusable library that records what a harness is waiting for and who
|
|
6
|
+
* owns the result. It provides no provider transport, no process launch, no tool
|
|
7
|
+
* execution and no model call: Background Tasks, Subagents and the parent
|
|
8
|
+
* harness share these records instead of duplicating a journal.
|
|
9
|
+
*
|
|
10
|
+
* The contracts here implement the accepted invariant in
|
|
11
|
+
* `docs/adr/0020-observed-waits-retain-an-owner.md` and the record shapes in
|
|
12
|
+
* `docs/plans/observed-waits-design.md`.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { openStore } from "operation-coordinator";
|
|
16
|
+
*
|
|
17
|
+
* const store = openStore({ path: join(agentDir, "operation-coordinator.sqlite") });
|
|
18
|
+
* store.registerOperation({ operationId, taskId, launchToken, owner, observer });
|
|
19
|
+
* // later, from the supervisor:
|
|
20
|
+
* store.recordTerminalOutcome({ operationId, eventId, outcome: "succeeded", owner, evidence });
|
|
21
|
+
* // the owner interprets the evidence it read, then consumes the wait:
|
|
22
|
+
* store.recordEvidenceRead({ waitId, generation, owner, operationId, terminalRevision: 1 });
|
|
23
|
+
* store.acknowledgeResult({ waitId, generation, owner, disposition: "continue", note, terminalRevisions });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Rules the store enforces by itself:
|
|
27
|
+
*
|
|
28
|
+
* - an owner, task id and launch token are immutable once registered;
|
|
29
|
+
* - one durable operation per background task, and one pending wait generation
|
|
30
|
+
* per owner identity;
|
|
31
|
+
* - a parked worker reaches `waiting`/`ready` only with checkpoint and writer
|
|
32
|
+
* exit proof, and a dependency that settled earlier is never missed;
|
|
33
|
+
* - duplicate terminal events and replayed reconciliation produce one terminal
|
|
34
|
+
* revision and one delivery per wait generation;
|
|
35
|
+
* - resume attempt ids and launch tokens are persisted before spawn, and one
|
|
36
|
+
* generation has one active claim;
|
|
37
|
+
* - cancellation increments a fencing epoch and invalidates the pending claim;
|
|
38
|
+
* - an acknowledgement requires a recorded read of the exact evidence revision by
|
|
39
|
+
* the owner, and only then are evidence pins released;
|
|
40
|
+
* - no credential, token value or environment value is stored; obvious secret
|
|
41
|
+
* material in a note or reference is refused.
|
|
42
|
+
*
|
|
43
|
+
* `node:sqlite` (Node 24+) is required. There is no in-memory fallback: an
|
|
44
|
+
* unavailable or unreadable database disables the feature instead of pretending
|
|
45
|
+
* to be durable.
|
|
46
|
+
*/
|
|
47
|
+
export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
|
|
48
|
+
export type {
|
|
49
|
+
AcknowledgeDisposition,
|
|
50
|
+
AcknowledgeResultInput,
|
|
51
|
+
AcknowledgeResultOutput,
|
|
52
|
+
CancelWaitInput,
|
|
53
|
+
CancelWaitResult,
|
|
54
|
+
ClaimOutboxInput,
|
|
55
|
+
ClaimResumeInput,
|
|
56
|
+
EvidenceKind,
|
|
57
|
+
EvidencePinRecord,
|
|
58
|
+
EvidenceReadRecord,
|
|
59
|
+
EvidenceRefInput,
|
|
60
|
+
HoldFailedResumeInput,
|
|
61
|
+
HoldFailedResumeResult,
|
|
62
|
+
ObserverHealth,
|
|
63
|
+
ObserverIdentity,
|
|
64
|
+
OperationEvidenceRecord,
|
|
65
|
+
OperationFilter,
|
|
66
|
+
OperationPhase,
|
|
67
|
+
OperationRecord,
|
|
68
|
+
OutboxDispatchClaim,
|
|
69
|
+
OutboxDispatchInput,
|
|
70
|
+
OutboxEventRecord,
|
|
71
|
+
OutboxFilter,
|
|
72
|
+
OutboxState,
|
|
73
|
+
OwnerIdentity,
|
|
74
|
+
OwnerKind,
|
|
75
|
+
PublishResumeAttemptInput,
|
|
76
|
+
PublishResumeAttemptResult,
|
|
77
|
+
RecordEvidencePinInput,
|
|
78
|
+
RecordEvidencePinResult,
|
|
79
|
+
RecordEvidenceReadInput,
|
|
80
|
+
RecordEvidenceReadResult,
|
|
81
|
+
RecordSupervisionInput,
|
|
82
|
+
RecordTerminalOutcomeInput,
|
|
83
|
+
RecordTerminalOutcomeResult,
|
|
84
|
+
RegisterOperationInput,
|
|
85
|
+
RegisterOperationResult,
|
|
86
|
+
RegisterWaitInput,
|
|
87
|
+
RegisterWaitResult,
|
|
88
|
+
ReleaseOutboxInput,
|
|
89
|
+
ReleaseResumeClaimInput,
|
|
90
|
+
ReleaseResumeClaimResult,
|
|
91
|
+
ResumeClaimFilter,
|
|
92
|
+
ResumeClaimRecord,
|
|
93
|
+
ResumeClaimResult,
|
|
94
|
+
ResumeClaimState,
|
|
95
|
+
ResumeLeaseIdentity,
|
|
96
|
+
StoreOptions,
|
|
97
|
+
SupervisionIdentity,
|
|
98
|
+
TerminalOutcome,
|
|
99
|
+
TransitionWaitPhaseInput,
|
|
100
|
+
TransitionWaitPhaseResult,
|
|
101
|
+
WaitAcknowledgement,
|
|
102
|
+
WaitDependencyInput,
|
|
103
|
+
WaitDependencyRecord,
|
|
104
|
+
WaitFilter,
|
|
105
|
+
WaitParkIntent,
|
|
106
|
+
WaitPhase,
|
|
107
|
+
WaitRecord,
|
|
108
|
+
WaitRef,
|
|
109
|
+
} from "./src/types.ts";
|
|
110
|
+
export { StoreError, isStoreError } from "./src/errors.ts";
|
|
111
|
+
export type { StoreErrorCode } from "./src/errors.ts";
|
|
112
|
+
export { openStore, ownerDiff } from "./src/store.ts";
|
|
113
|
+
export type { Store } from "./src/store.ts";
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/errors.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Refusals from the durable operation coordinator.
|
|
4
|
+
*
|
|
5
|
+
* Every refusal is a typed `code` so a transport can turn it into a specific
|
|
6
|
+
* model-facing reason instead of a generic failure. A refusal never leaves a
|
|
7
|
+
* partial record: all writes run inside one immediate transaction.
|
|
8
|
+
*/
|
|
9
|
+
export type StoreErrorCode =
|
|
10
|
+
/** The database was written by another schema version. Records are left untouched. */
|
|
11
|
+
| "schema-version"
|
|
12
|
+
/** This runtime has no `node:sqlite`, so durability cannot be promised. */
|
|
13
|
+
| "sqlite-unavailable"
|
|
14
|
+
/** Another process holds the write lock for longer than the configured budget. */
|
|
15
|
+
| "store-busy"
|
|
16
|
+
/** A stored row could not be parsed back into its record shape. */
|
|
17
|
+
| "store-corruption"
|
|
18
|
+
/** Caller input is malformed, out of bounds, or looks like credential material. */
|
|
19
|
+
| "validation"
|
|
20
|
+
/** The operation id is not registered in this store. */
|
|
21
|
+
| "unknown-operation"
|
|
22
|
+
/** An operation already exists with different immutable launch identity. */
|
|
23
|
+
| "operation-conflict"
|
|
24
|
+
/** The background task id belongs to a different owner. */
|
|
25
|
+
| "task-ownership"
|
|
26
|
+
/** The caller is not the recorded owner of the record it wants to change. */
|
|
27
|
+
| "foreign-owner"
|
|
28
|
+
/** A different terminal event is already recorded for this operation. */
|
|
29
|
+
| "terminal-conflict"
|
|
30
|
+
/** The owner already has a pending wait generation. */
|
|
31
|
+
| "pending-wait-generation"
|
|
32
|
+
/** The wait id / generation is not registered in this store. */
|
|
33
|
+
| "unknown-wait"
|
|
34
|
+
/** The requested wait phase transition is not allowed from the current phase. */
|
|
35
|
+
| "wait-phase"
|
|
36
|
+
/** The caller's view of the current phase is out of date (out-of-order call). */
|
|
37
|
+
| "stale-phase"
|
|
38
|
+
/** The caller addressed a generation that is not the current one. */
|
|
39
|
+
| "stale-generation"
|
|
40
|
+
/** The caller's cancellation epoch is out of date; the wait changed underneath. */
|
|
41
|
+
| "stale-cancel-epoch"
|
|
42
|
+
/** Not every dependency has a terminal outcome yet. */
|
|
43
|
+
| "dependencies-unsettled"
|
|
44
|
+
/** A parked wait tried to reach waiting/ready without checkpoint and writer proof. */
|
|
45
|
+
| "checkpoint-proof"
|
|
46
|
+
/** A published resume cannot be held without proven writer exit and a free lease. */
|
|
47
|
+
| "resume-proof"
|
|
48
|
+
/** Another resume claim is already active for this wait generation. */
|
|
49
|
+
| "concurrent-claim"
|
|
50
|
+
/** The resume claim is not in a state that allows the requested step. */
|
|
51
|
+
| "claim-state"
|
|
52
|
+
/** The attempt id is already published by another resume claim. */
|
|
53
|
+
| "attempt-conflict"
|
|
54
|
+
/** The owner must record reading the exact terminal evidence before acknowledging. */
|
|
55
|
+
| "evidence-read-required"
|
|
56
|
+
/** The acknowledged evidence revision is not the dependency's terminal revision. */
|
|
57
|
+
| "stale-evidence"
|
|
58
|
+
/** The outbox event is not in a state that allows the requested step. */
|
|
59
|
+
| "outbox-state"
|
|
60
|
+
/** The store has been closed. */
|
|
61
|
+
| "closed";
|
|
62
|
+
|
|
63
|
+
export class StoreError extends Error {
|
|
64
|
+
readonly code: StoreErrorCode;
|
|
65
|
+
|
|
66
|
+
constructor(code: StoreErrorCode, message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = "StoreError";
|
|
69
|
+
this.code = code;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function isStoreError(error: unknown): error is StoreError {
|
|
74
|
+
return error instanceof StoreError;
|
|
75
|
+
}
|